text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import JNI_ENV_METHODS from "../data/jni_env.json";
import { JNIThreadManager } from "./jni_thread_manager";
import { JavaVMInterceptor } from "./java_vm_interceptor";
import { JNIMethod } from "./jni_method";
import { ReferenceManager } from "../utils/reference_manager";
import { Types } from "../utils/types";
import { JavaMethod } from "../utils/java_method";
import { Config } from "../utils/config";
import { JNIInvocationContext } from "../";
import { JNICallbackManager } from "../internal/jni_callback_manager";
const TYPE_NAME_START = 0;
const TYPE_NAME_END = -1;
const COPY_ARRAY_INDEX = 0;
const JNI_ENV_INDEX = 0;
abstract class JNIEnvInterceptor {
protected references: ReferenceManager;
protected threads: JNIThreadManager;
protected callbackManager: JNICallbackManager;
protected javaVMInterceptor: JavaVMInterceptor | null;
protected shadowJNIEnv: NativePointer;
protected methods: Map<string, JavaMethod>;
protected fastMethodLookup: Map<string, NativeCallback>;
protected vaArgsBacktraces: Map<number, NativePointer[]>;
public constructor (
references: ReferenceManager,
threads: JNIThreadManager,
callbackManager: JNICallbackManager
) {
this.references = references;
this.threads = threads;
this.callbackManager = callbackManager;
this.javaVMInterceptor = null;
this.shadowJNIEnv = NULL;
this.methods = new Map<string, JavaMethod>();
this.fastMethodLookup = new Map<string, NativeCallback>();
this.vaArgsBacktraces = new Map<number, NativePointer[]>();
}
public isInitialised (): boolean {
return !this.shadowJNIEnv.equals(NULL);
}
public get (): NativePointer {
return this.shadowJNIEnv;
}
public create (): NativePointer {
const END_INDEX = 1;
const threadId = Process.getCurrentThreadId();
const jniEnv = this.threads.getJNIEnv(threadId);
const jniEnvOffset = 4;
const jniEnvLength = 232;
const newJNIEnvStruct = Memory.alloc(Process.pointerSize * jniEnvLength);
this.references.add(newJNIEnvStruct);
const newJNIEnv = Memory.alloc(Process.pointerSize);
newJNIEnv.writePointer(newJNIEnvStruct);
this.references.add(newJNIEnv);
for (let i = jniEnvOffset; i < jniEnvLength; i++) {
const method = JNI_ENV_METHODS[i];
const offset = i * Process.pointerSize;
const jniEnvStruct = jniEnv.readPointer();
const methodAddr = jniEnvStruct.add(offset).readPointer();
if (method.args[method.args.length - END_INDEX] === "...") {
const callback = this.createJNIVarArgIntercept(i, methodAddr);
const trampoline = this.createStubFunction();
this.references.add(trampoline);
// ensure the CpuContext will be populated
Interceptor.replace(trampoline, callback);
newJNIEnvStruct.add(offset).writePointer(trampoline);
} else {
const callback = this.createJNIIntercept(i, methodAddr);
const trampoline = this.createStubFunction();
this.references.add(trampoline);
// ensure the CpuContext will be populated
Interceptor.replace(trampoline, callback);
newJNIEnvStruct.add(offset).writePointer(trampoline);
}
}
this.shadowJNIEnv = newJNIEnv;
return newJNIEnv;
}
public setJavaVMInterceptor (javaVMInterceptor: JavaVMInterceptor): void {
this.javaVMInterceptor = javaVMInterceptor;
}
public createStubFunction (): NativeCallback {
// eslint-disable-next-line @typescript-eslint/no-empty-function
return new NativeCallback((): void => { }, "void", []);
}
protected createJNIVarArgIntercept (
id: number,
methodPtr: NativePointer
): NativePointer {
const self = this;
const method = JNI_ENV_METHODS[id];
const text = Memory.alloc(Process.pageSize);
const data = Memory.alloc(Process.pageSize);
this.references.add(text);
this.references.add(data);
const vaArgsCallback = this.createJNIVarArgInitialCallback(
method, methodPtr
);
this.references.add(vaArgsCallback);
self.buildVaArgParserShellcode(text, data, vaArgsCallback);
const config = Config.getInstance();
Interceptor.attach(text, function (this: InvocationContext): void {
let backtraceType = Backtracer.ACCURATE;
if (config.backtrace === "fuzzy") {
backtraceType = config.backtrace;
}
self.vaArgsBacktraces.set(
this.threadId, Thread.backtrace(this.context, backtraceType)
);
});
return text;
}
private addJavaArgsForJNIIntercept (
method: JNIMethod,
args: NativeArgumentValue[]
): NativeArgumentValue[] {
const LAST_INDEX = -1;
const FIRST_INDEX = 0;
const METHOD_ID_INDEX = 2;
const NON_VIRTUAL_METHOD_ID_INDEX = 3;
let methodIndex = METHOD_ID_INDEX;
if (method.name.includes("Nonvirtual")) {
methodIndex = NON_VIRTUAL_METHOD_ID_INDEX;
}
const lastParamType = method.args.slice(LAST_INDEX)[FIRST_INDEX];
if (!["va_list", "jvalue*"].includes(lastParamType)) {
return args.slice(COPY_ARRAY_INDEX);
}
const clonedArgs = args.slice(COPY_ARRAY_INDEX);
const midPtr = args[methodIndex] as NativePointer;
if (!this.methods.has(midPtr.toString())) {
send({
type: "error",
message: "Failed to find corresponding method ID " +
"for method \"" + method.name + "\" call."
});
return args.slice(COPY_ARRAY_INDEX);
}
const javaMethod = this.methods.get(midPtr.toString()) as JavaMethod;
const nativeJTypes = javaMethod.nativeParams;
const readPtr = args.slice(LAST_INDEX)[FIRST_INDEX] as NativePointer;
if (lastParamType === "va_list") {
this.setUpVaListArgExtract(readPtr);
}
const UNION_SIZE = 8;
for (let i = 0; i < nativeJTypes.length; i++) {
const type = Types.convertNativeJTypeToFridaType(nativeJTypes[i]);
let val = undefined;
if (lastParamType === "va_list") {
const currentPtr = this.extractVaListArgValue(javaMethod, i);
val = this.readValue(currentPtr, type, true);
} else {
val = this.readValue(readPtr.add(UNION_SIZE * i), type);
}
clonedArgs.push(val);
}
if (lastParamType === "va_list") {
this.resetVaListArgExtract();
}
return clonedArgs;
}
private handleGetMethodResult (
args: NativeArgumentValue[],
ret: NativeReturnValue
): void {
const SIG_INDEX = 3;
const signature = (args[SIG_INDEX] as NativePointer).readCString();
if (signature !== null) {
const methodSig = new JavaMethod(signature);
this.methods.set((ret as NativePointer).toString(), methodSig);
}
}
private handleGetJavaVM (
args: NativeArgumentValue[],
ret: NativeReturnValue
): void {
if (this.javaVMInterceptor !== null) {
const JNI_OK = 0;
const JAVA_VM_INDEX = 1;
if (ret === JNI_OK) {
const javaVMPtr = args[JAVA_VM_INDEX] as NativePointer;
this.threads.setJavaVM(javaVMPtr.readPointer());
let javaVM = undefined;
if (!this.javaVMInterceptor.isInitialised()) {
javaVM = this.javaVMInterceptor.create();
} else {
javaVM = this.javaVMInterceptor.get();
}
javaVMPtr.writePointer(javaVM);
}
}
}
private handleRegisterNatives (args: NativeArgumentValue[]): void {
const METHOD_INDEX = 2;
const SIZE_INDEX = 3;
const JNI_METHOD_SIZE = 3;
const self = this;
const methods = args[METHOD_INDEX] as NativePointer;
const size = args[SIZE_INDEX] as number;
for (let i = 0; i < size * JNI_METHOD_SIZE; i += JNI_METHOD_SIZE) {
const methodsPtr = methods;
const namePtr = methodsPtr
.add(i * Process.pointerSize)
.readPointer();
const name = namePtr.readCString();
const sigOffset = 1;
const sigPtr = methodsPtr
.add((i + sigOffset) * Process.pointerSize)
.readPointer();
const sig = sigPtr.readCString();
const addrOffset = 2;
const addr = methodsPtr
.add((i + addrOffset) * Process.pointerSize)
.readPointer();
if (name === null || sig === null) {
continue;
}
Interceptor.attach(addr, {
onEnter (args: NativeArgumentValue[]): void {
const check = name + sig;
const config = Config.getInstance();
const EMPTY_ARRAY_LEN = 0;
if (config.includeExport.length > EMPTY_ARRAY_LEN) {
const included = config.includeExport.filter(
(i: string): boolean => check.includes(i)
);
if (included.length === EMPTY_ARRAY_LEN) {
return;
}
}
if (config.excludeExport.length > EMPTY_ARRAY_LEN) {
const excluded = config.excludeExport.filter(
(e: string): boolean => check.includes(e)
);
if (excluded.length > EMPTY_ARRAY_LEN) {
return;
}
}
if (!self.threads.hasJNIEnv(this.threadId)) {
self.threads.setJNIEnv(
this.threadId, args[JNI_ENV_INDEX] as NativePointer
);
}
args[JNI_ENV_INDEX] = self.shadowJNIEnv;
}
});
}
}
private handleJNIInterceptResult (
method: JNIMethod,
args: NativeArgumentValue[],
ret: NativeReturnValue
): void {
const name = method.name;
if (["GetMethodID", "GetStaticMethodID"].includes(name)) {
this.handleGetMethodResult(args, ret);
} else if (method.name === "GetJavaVM") {
this.handleGetJavaVM(args, ret);
} else if (method.name === "RegisterNatives") {
this.handleRegisterNatives(args);
}
}
private createJNIIntercept (
id: number,
methodPtr: NativePointer
): NativeCallback {
const self = this;
const METHOD_ID_INDEX = 2;
const method = JNI_ENV_METHODS[id];
const config = Config.getInstance();
const paramTypes = method.args.map(
(t: string): string => Types.convertNativeJTypeToFridaType(t)
);
const retType = Types.convertNativeJTypeToFridaType(method.ret);
const nativeFunction = new NativeFunction(methodPtr, retType, paramTypes);
const nativeCallback = new NativeCallback(function (
this: InvocationContext
): NativeReturnValue {
const threadId = this.threadId;
const jniEnv = self.threads.getJNIEnv(threadId);
const args: NativeArgumentValue[] = [].slice.call(arguments);
args[JNI_ENV_INDEX] = jniEnv;
const clonedArgs = self.addJavaArgsForJNIIntercept(method, args);
const ctx: JNIInvocationContext = {
jniAddress: methodPtr,
threadId: threadId,
methodDef: method,
};
if (config.backtrace === "accurate") {
ctx.backtrace = Thread.backtrace(this.context, Backtracer.ACCURATE);
} else if (config.backtrace === "fuzzy") {
ctx.backtrace = Thread.backtrace(this.context, Backtracer.FUZZY);
}
if (args.length !== clonedArgs.length) {
// eslint-disable-next-line @typescript-eslint/no-base-to-string
const key = args[METHOD_ID_INDEX].toString();
ctx.javaMethod = self.methods.get(key);
}
self.callbackManager.doBeforeCallback(method.name, ctx, clonedArgs);
let ret = nativeFunction.apply(null, args);
ret = self.callbackManager.doAfterCallback(method.name, ctx, ret);
self.handleJNIInterceptResult(method, args, ret);
return ret;
} as NativeCallbackImplementation, retType, paramTypes);
this.references.add(nativeCallback);
return nativeCallback;
}
private createJNIVarArgMainCallback (
method: JNIMethod,
methodPtr: NativePointer,
initialparamTypes: string[],
mainParamTypes: string[],
retType: string
): NativeCallback {
const self = this;
const mainCallback = new NativeCallback(function (
this: InvocationContext
): NativeReturnValue {
const METHOD_ID_INDEX = 2;
const threadId = this.threadId;
const args: NativeArgumentValue[] = [].slice.call(arguments);
const jniEnv = self.threads.getJNIEnv(threadId);
// eslint-disable-next-line @typescript-eslint/no-base-to-string
const key = args[METHOD_ID_INDEX].toString();
const jmethod = self.methods.get(key);
args[JNI_ENV_INDEX] = jniEnv;
const ctx: JNIInvocationContext = {
backtrace: self.vaArgsBacktraces.get(this.threadId),
jniAddress: methodPtr,
threadId: threadId,
methodDef: method,
javaMethod: jmethod
};
self.callbackManager.doBeforeCallback(method.name, ctx, args);
let ret = new NativeFunction(methodPtr,
retType,
initialparamTypes).apply(null, args);
ret = self.callbackManager.doAfterCallback(method.name, ctx, ret);
self.vaArgsBacktraces.delete(this.threadId);
return ret;
} as NativeCallbackImplementation, retType, mainParamTypes);
return mainCallback;
}
private createJNIVarArgInitialCallback (
method: JNIMethod,
methodPtr: NativePointer
): NativeCallback {
const self = this;
const vaArgsCallback = new NativeCallback(function (): NativeReturnValue {
const METHOD_ID_INDEX = 2;
// eslint-disable-next-line @typescript-eslint/no-base-to-string
const methodId = (arguments[METHOD_ID_INDEX] as NativeArgumentValue).toString();
const javaMethod = self.methods.get(methodId) as JavaMethod;
if (self.fastMethodLookup.has(methodId)) {
return self.fastMethodLookup.get(methodId) as NativeReturnValue;
}
const originalParams = method.args
.slice(TYPE_NAME_START, TYPE_NAME_END)
.map((t: string): string => Types.convertNativeJTypeToFridaType(t));
const callbackParams = originalParams.slice(COPY_ARRAY_INDEX);
originalParams.push("...");
javaMethod.fridaParams.forEach((p: string): void => {
callbackParams.push(p === "float" ? "double" : p);
originalParams.push(p);
});
const retType = Types.convertNativeJTypeToFridaType(method.ret);
const mainCallback = self.createJNIVarArgMainCallback(
method, methodPtr, originalParams, callbackParams, retType
);
self.references.add(mainCallback);
self.fastMethodLookup.set(methodId, mainCallback);
return mainCallback;
}, "pointer", ["pointer", "pointer", "pointer"]);
return vaArgsCallback;
}
private readValue (
currentPtr: NativePointer,
type: string,
extend?: boolean
): NativeArgumentValue {
let val: NativeArgumentValue = NULL;
if (type === "char") {
val = currentPtr.readS8();
} else if (type === "int16") {
val = currentPtr.readS16();
} else if (type === "uint16") {
val = currentPtr.readU16();
} else if (type === "int") {
val = currentPtr.readS32();
} else if (type === "int64") {
val = currentPtr.readS64();
} else if (type === "float") {
if (extend === true) {
val = currentPtr.readDouble();
} else {
val = currentPtr.readFloat();
}
} else if (type === "double") {
val = currentPtr.readDouble();
} else if (type === "pointer") {
val = currentPtr.readPointer();
}
return val;
}
protected abstract buildVaArgParserShellcode(
text: NativePointer,
data: NativePointer,
parser: NativeCallback
): void;
protected abstract setUpVaListArgExtract(vaList: NativePointer): void;
protected abstract extractVaListArgValue(
method: JavaMethod,
index: number
): NativePointer;
protected abstract resetVaListArgExtract(): void;
}
export { JNIEnvInterceptor }; | the_stack |
import { BadRequestException, Inject, Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/sequelize'
import type { Logger } from '@island.is/logging'
import { LOGGER_PROVIDER } from '@island.is/logging'
import { Op, Sequelize, WhereOptions } from 'sequelize'
import { IdentityResource } from '../entities/models/identity-resource.model'
import { ApiScope } from '../entities/models/api-scope.model'
import { ApiResource } from '../entities/models/api-resource.model'
import { ApiResourceScope } from '../entities/models/api-resource-scope.model'
import { IdentityResourceUserClaim } from '../entities/models/identity-resource-user-claim.model'
import { ApiResourceSecret } from '../entities/models/api-resource-secret.model'
import { ApiResourceUserClaim } from '../entities/models/api-resource-user-claim.model'
import { ApiScopeUserClaim } from '../entities/models/api-scope-user-claim.model'
import { IdentityResourcesDTO } from '../entities/dto/identity-resources.dto'
import { ApiScopesDTO } from '../entities/dto/api-scopes.dto'
import { ApiResourcesDTO } from '../entities/dto/api-resources.dto'
import sha256 from 'crypto-js/sha256'
import Base64 from 'crypto-js/enc-base64'
import { ApiResourceSecretDTO } from '../entities/dto/api-resource-secret.dto'
import { ApiResourceAllowedScopeDTO } from '../entities/dto/api-resource-allowed-scope.dto'
import { UserClaimDTO } from '../entities/dto/user-claim.dto'
import { ApiScopeGroupDTO } from '../entities/dto/api-scope-group.dto'
import { ApiScopeGroup } from '../entities/models/api-scope-group.model'
import { uuid } from 'uuidv4'
import { Domain } from '../entities/models/domain.model'
import { PagedRowsDto } from '../entities/dto/paged-rows.dto'
import { DomainDTO } from '../entities/dto/domain.dto'
@Injectable()
export class ResourcesService {
constructor(
@InjectModel(Domain)
private domainModel: typeof Domain,
@InjectModel(IdentityResource)
private identityResourceModel: typeof IdentityResource,
@InjectModel(ApiScope)
private apiScopeModel: typeof ApiScope,
@InjectModel(ApiResource)
private apiResourceModel: typeof ApiResource,
@InjectModel(ApiScopeGroup)
private apiScopeGroup: typeof ApiScopeGroup,
@InjectModel(ApiResourceScope)
private apiResourceScopeModel: typeof ApiResourceScope,
@InjectModel(IdentityResourceUserClaim)
private identityResourceUserClaimModel: typeof IdentityResourceUserClaim,
@InjectModel(ApiScopeUserClaim)
private apiScopeUserClaimModel: typeof ApiScopeUserClaim,
@InjectModel(ApiResourceUserClaim)
private apiResourceUserClaim: typeof ApiResourceUserClaim,
@InjectModel(ApiResourceSecret)
private apiResourceSecret: typeof ApiResourceSecret,
@InjectModel(ApiResourceScope)
private apiResourceScope: typeof ApiResourceScope,
@Inject(LOGGER_PROVIDER)
private logger: Logger,
@Inject(Sequelize)
private sequelize: Sequelize,
) {}
/** Get's all identity resources and total count of rows */
async findAndCountAllIdentityResources(
page: number,
count: number,
): Promise<{
rows: IdentityResource[]
count: number
} | null> {
page--
const offset = page * count
return this.identityResourceModel.findAndCountAll({
limit: count,
offset: offset,
include: [IdentityResourceUserClaim],
distinct: true,
})
}
/** Finds Api resources with searchString and returns with paging */
async findApiResources(searchString: string, page: number, count: number) {
if (!searchString) {
throw new BadRequestException('Search String must be provided')
}
searchString = searchString.trim()
if (isNaN(+searchString)) {
return this.findApiResourcesByName(searchString, page, count)
} else {
return this.findApiResourcesByNationalId(searchString, page, count)
}
}
/** Finds all Api resources without paging */
async findAllApiResources(): Promise<ApiResource[] | null> {
return this.apiResourceModel.findAll({ order: [['name', 'asc']] })
}
/** Finds Api resources with by national Id and returns with paging */
async findApiResourcesByNationalId(
searchString: string,
page: number,
count: number,
) {
if (!searchString) {
throw new BadRequestException('Search String must be provided')
}
page--
const offset = page * count
return this.apiResourceModel.findAndCountAll({
where: { nationalId: searchString },
limit: count,
offset: offset,
include: [ApiResourceUserClaim, ApiResourceScope, ApiResourceSecret],
distinct: true,
})
}
/** Finds Api resources with by name */
async findApiResourcesByName(
searchString: string,
page: number,
count: number,
) {
if (!searchString) {
throw new BadRequestException('Search String must be provided')
}
page--
const offset = page * count
return this.apiResourceModel.findAndCountAll({
where: { name: searchString },
limit: count,
offset: offset,
include: [ApiResourceUserClaim, ApiResourceScope, ApiResourceSecret],
distinct: true,
})
}
/** Get's all Api resources and total count of rows */
async findAndCountAllApiResources(
page: number,
count: number,
): Promise<{
rows: ApiResource[]
count: number
} | null> {
page--
const offset = page * count
return this.apiResourceModel.findAndCountAll({
limit: count,
offset: offset,
include: [ApiResourceUserClaim, ApiResourceScope, ApiResourceSecret],
distinct: true,
})
}
/** Get's all Api scopes and total count of rows */
async findAndCountAllApiScopes(
page: number,
count: number,
): Promise<{
rows: ApiScope[]
count: number
} | null> {
page--
const offset = page * count
return this.apiScopeModel.findAndCountAll({
limit: count,
offset: offset,
include: [ApiScopeUserClaim, ApiScopeGroup],
distinct: true,
})
}
/** Get's all Api scopes that are access controlled */
async findAllAccessControlledApiScopes(): Promise<ApiScope[]> {
return this.apiScopeModel.findAll({
where: {
isAccessControlled: true,
name: {
[Op.not]: '@island.is/auth/admin:root',
},
},
include: [ApiScopeGroup],
})
}
/** Gets Identity resource by name */
async getIdentityResourceByName(
name: string,
): Promise<IdentityResource | null> {
this.logger.debug('Getting data about identity resource with name: ', name)
if (!name) {
throw new BadRequestException('Name must be provided')
}
const identityResource = await this.identityResourceModel.findByPk(name, {
raw: true,
})
if (identityResource) {
identityResource.userClaims = await this.identityResourceUserClaimModel.findAll(
{
where: { identityResourceName: identityResource.name },
raw: true,
},
)
}
return identityResource
}
/** Gets API scope by name */
async getApiScopeByName(name: string): Promise<ApiScope | null> {
this.logger.debug('Getting data about api scope with name: ', name)
if (!name) {
throw new BadRequestException('Name must be provided')
}
const apiScope = await this.apiScopeModel.findByPk(name, {
raw: true,
include: [ApiScopeGroup],
})
if (apiScope) {
apiScope.userClaims = await this.apiScopeUserClaimModel.findAll({
where: { apiScopeName: apiScope.name },
raw: true,
})
}
return apiScope
}
/** Gets API scope or IdentityResource by name */
async isScopeNameAvailable(name: string): Promise<boolean> {
this.logger.debug(
'Checking if api scope or identity resource is available with name: ',
name,
)
if (!name) {
return false
}
const apiScope = await this.apiScopeModel.findByPk(name)
if (apiScope) {
return false
}
const idr = await this.identityResourceModel.findByPk(name)
if (idr) {
return false
}
return true
}
/** Gets API scope by name */
async getApiResourceByName(name: string): Promise<ApiResource | null> {
this.logger.debug('Getting data about api scope with name: ', name)
if (!name) {
throw new BadRequestException('Name must be provided')
}
const apiResource = await this.apiResourceModel.findByPk(name, {
raw: true,
})
if (apiResource) {
await this.findApiResourceAssociations(apiResource)
.then<any, never>((result: any) => {
apiResource.userClaims = result[0]
apiResource.scopes = result[1]
apiResource.apiSecrets = result[2]
})
.catch((error) =>
this.logger.error(`Error in findAssociations: ${error}`),
)
}
return apiResource
}
private findApiResourceAssociations(apiResource: ApiResource): Promise<any> {
return Promise.all([
this.apiResourceUserClaim.findAll({
where: { apiResourceName: apiResource.name },
raw: true,
}), // 0
this.apiResourceScope.findAll({
where: { apiResourceName: apiResource.name },
raw: true,
}), // 1
this.apiResourceSecret.findAll({
where: { apiResourceName: apiResource.name },
raw: true,
}), // 2
])
}
/** Get identity resources by scope names */
async findIdentityResourcesByScopeName(
scopeNames: string[],
): Promise<IdentityResource[]> {
this.logger.debug(`Finding identity resources for scope names`, scopeNames)
const whereOptions: WhereOptions = {
name: {
[Op.in]: scopeNames,
},
}
return this.identityResourceModel.findAll({
where: scopeNames ? whereOptions : undefined,
include: [IdentityResourceUserClaim],
})
}
/** Gets Api scopes by scope names */
async findApiScopesByNameAsync(scopeNames: string[]): Promise<ApiScope[]> {
this.logger.debug(`Finding api scopes for scope names`, scopeNames)
const whereOptions: WhereOptions = {
name: {
[Op.in]: scopeNames,
},
}
return this.apiScopeModel.findAll({
where: scopeNames ? whereOptions : undefined,
include: [ApiScopeUserClaim, ApiScopeGroup],
})
}
/** Gets Api scopes with Explicit Delegation Grant */
async findApiScopesWithExplicitDelegationGrant(): Promise<ApiScope[]> {
this.logger.debug(`Finding api scopes with Explicit Delegation Grant`)
return this.apiScopeModel.findAll({
where: { allowExplicitDelegationGrant: true },
include: [ApiScopeGroup],
})
}
/** Filters out scopes that don't have delegation grant and are access controlled */
async findAllowedDelegationApiScopeListForUser(scopes: string[]) {
this.logger.debug(`Finding allowed api scopes for scopes ${scopes}`)
return this.apiScopeModel.findAll({
where: {
name: {
[Op.in]: scopes,
},
allowExplicitDelegationGrant: true,
},
include: [ApiScopeGroup],
})
}
/** Filters out Identity Resources that don't have delegation grant and are access controlled */
async findAllowedDelegationIdentityResourceListForUser(
identityResources: string[],
) {
this.logger.debug(
`Finding allowed Identity Resources for identity resources: ${identityResources}`,
)
return this.identityResourceModel.findAll({
where: {
name: {
[Op.in]: identityResources,
},
allowExplicitDelegationGrant: true,
alsoForDelegatedUser: false,
},
})
}
/** Gets Api scopes with Explicit Delegation Grant */
async findIdentityResourcesWithExplicitDelegationGrant(): Promise<
IdentityResource[]
> {
this.logger.debug(
`Finding identity resources with Explicit Delegation Grant`,
)
return this.identityResourceModel.findAll({
where: { allowExplicitDelegationGrant: true },
})
}
/** Gets api resources by api resource names */
async findApiResourcesByNameAsync(
apiResourceNames: string[],
): Promise<ApiResource[]> {
this.logger.debug(
`Finding api resources for resource names`,
apiResourceNames,
)
const whereOptions: WhereOptions = {
name: {
[Op.in]: apiResourceNames,
},
}
return this.apiResourceModel.findAll({
where: apiResourceNames ? whereOptions : undefined,
include: [ApiResourceSecret, ApiResourceScope, ApiResourceUserClaim],
})
}
/** Get Api resources by scope names */
async findApiResourcesByScopeNameAsync(
apiResourceScopeNames: string[],
): Promise<ApiResource[]> {
this.logger.debug(
`Finding api resources for resource scope names`,
apiResourceScopeNames,
)
const scopesWhereOptions: WhereOptions = {
scopeName: {
[Op.in]: apiResourceScopeNames,
},
}
const scopes = await this.apiResourceScopeModel.findAll({
raw: true,
where: apiResourceScopeNames ? scopesWhereOptions : undefined,
})
const whereOptions: WhereOptions = {
name: {
[Op.in]: scopes.map((scope) => scope.apiResourceName),
},
}
return this.apiResourceModel.findAll({
where: whereOptions,
include: [ApiResourceSecret, ApiResourceScope, ApiResourceUserClaim],
})
}
/** Creates a new identity resource */
async createIdentityResource(
identityResource: IdentityResourcesDTO,
): Promise<IdentityResource> {
this.logger.debug('Creating a new identity resource')
return await this.identityResourceModel.create({ ...identityResource })
}
/** Updates an existing Identity resource */
async updateIdentityResource(
identityResource: IdentityResourcesDTO,
name: string,
): Promise<IdentityResource | null> {
this.logger.debug('Updating identity resource with name: ', name)
if (!name) {
throw new BadRequestException('Name must be provided')
}
await this.identityResourceModel.update(
{ ...identityResource },
{ where: { name: name } },
)
return await this.getIdentityResourceByName(name)
}
/** Soft delete on an identity resource by name */
async deleteIdentityResource(name: string): Promise<number> {
this.logger.debug('Soft deleting an identity resource with name: ', name)
if (!name) {
throw new BadRequestException('Name must be provided')
}
const result = await this.identityResourceModel.update(
{ archived: new Date(), enabled: false },
{ where: { name: name } },
)
return result[0]
}
/** Creates a new Api Resource */
async createApiResource(apiResource: ApiResourcesDTO): Promise<ApiResource> {
this.logger.debug('Creating a new api resource')
return await this.apiResourceModel.create({ ...apiResource })
}
/** Creates a new Api Scope */
async createApiScope(apiScope: ApiScopesDTO): Promise<ApiScope> {
this.logger.debug('Creating a new api scope')
return await this.apiScopeModel.create({ ...apiScope })
}
/** Updates an existing API scope */
async updateApiScope(
apiScope: ApiScopesDTO,
name: string,
): Promise<ApiScope | null> {
this.logger.debug('Updating api scope with name: ', name)
if (!name) {
throw new BadRequestException('Name must be provided')
}
await this.apiScopeModel.update({ ...apiScope }, { where: { name: name } })
return this.getApiScopeByName(name)
}
/** Updates an existing API scope */
async updateApiResource(
apiResource: ApiResourcesDTO,
name: string,
): Promise<ApiResource | null> {
this.logger.debug('Updating api resource with name: ', name)
if (!name) {
throw new BadRequestException('Name must be provided')
}
await this.apiResourceModel.update(
{ ...apiResource },
{ where: { name: name } },
)
return this.getApiResourceByName(name)
}
/** Soft delete on an API scope */
async deleteApiScope(name: string): Promise<number> {
this.logger.debug('Soft deleting api scope with name: ', name)
if (!name) {
throw new BadRequestException('Name must be provided')
}
const result = await this.apiScopeModel.update(
{ archived: new Date(), enabled: false },
{ where: { name: name } },
)
return result[0]
}
/** Soft delete on an API resource */
async deleteApiResource(name: string): Promise<number> {
this.logger.debug('Soft deleting an api resource with name: ', name)
if (!name) {
throw new BadRequestException('Name must be provided')
}
const result = await this.apiResourceModel.update(
{ archived: new Date(), enabled: false },
{ where: { name: name } },
)
return result[0]
}
async addResourceUserClaim(
identityResourceName: string,
claimName: string,
): Promise<IdentityResourceUserClaim> {
if (!identityResourceName || !claimName) {
throw new BadRequestException('Name and resourceName must be provided')
}
return await this.identityResourceUserClaimModel.create({
identityResourceName: identityResourceName,
claimName: claimName,
})
}
async removeResourceUserClaim(
identityResourceName: string,
claimName: string,
): Promise<number> {
if (!identityResourceName || !claimName) {
throw new BadRequestException('Name and resourceName must be provided')
}
return await this.identityResourceUserClaimModel.destroy({
where: {
identityResourceName: identityResourceName,
claimName: claimName,
},
})
}
/** Adds user claim to Api Scope */
async addApiScopeUserClaim(
apiScopeName: string,
claimName: string,
): Promise<ApiScopeUserClaim> {
if (!apiScopeName || !claimName) {
throw new BadRequestException('Name and apiScopeName must be provided')
}
return await this.apiScopeUserClaimModel.create({
apiScopeName: apiScopeName,
claimName: claimName,
})
}
/** Removes user claim from Api Scope */
async removeApiScopeUserClaim(
apiScopeName: string,
claimName: string,
): Promise<number> {
if (!apiScopeName || !claimName) {
throw new BadRequestException('Name and apiScopeName must be provided')
}
return await this.apiScopeUserClaimModel.destroy({
where: {
apiScopeName: apiScopeName,
claimName: claimName,
},
})
}
/** Adds user claim to Api Resource */
async addApiResourceUserClaim(
apiResourceName: string,
claimName: string,
): Promise<ApiResourceUserClaim> {
if (!apiResourceName || !claimName) {
throw new BadRequestException('Name and apiResourceName must be provided')
}
return await this.apiResourceUserClaim.create({
apiResourceName: apiResourceName,
claimName: claimName,
})
}
/** Removes user claim from Api Resource */
async removeApiResourceUserClaim(
apiResourceName: string,
claimName: string,
): Promise<number> {
if (!apiResourceName || !claimName) {
throw new BadRequestException('Name and apiScopeName must be provided')
}
return await this.apiResourceUserClaim.destroy({
where: {
apiResourceName: apiResourceName,
claimName: claimName,
},
})
}
/** Add secret to ApiResource */
async addApiResourceSecret(
apiSecret: ApiResourceSecretDTO,
): Promise<ApiResourceSecret> {
const words = sha256(apiSecret.value)
const secret = Base64.stringify(words)
return this.apiResourceSecret.create({
apiResourceName: apiSecret.apiResourceName,
value: secret,
description: apiSecret.description,
type: apiSecret.type,
})
}
/** Remove a secret from Api Resource */
async removeApiResourceSecret(
apiSecret: ApiResourceSecretDTO,
): Promise<number> {
return this.apiResourceSecret.destroy({
where: {
apiResourceName: apiSecret.apiResourceName,
value: apiSecret.value,
},
})
}
/** Adds an allowed scope to api resource */
async addApiResourceAllowedScope(
resourceAllowedScope: ApiResourceAllowedScopeDTO,
): Promise<ApiResourceScope> {
this.logger.debug(
`Adding allowed scope - "${resourceAllowedScope.scopeName}" to api resource - "${resourceAllowedScope.apiResourceName}"`,
)
if (!resourceAllowedScope) {
throw new BadRequestException(
'resourceAllowedScope object must be provided',
)
}
return await this.apiResourceScope.create({ ...resourceAllowedScope })
}
/** Removes an allowed scope from api Resource */
async removeApiResourceAllowedScope(
apiResourceName: string,
scopeName: string,
): Promise<number> {
this.logger.debug(
`Removing scope - "${scopeName}" from api resource - "${apiResourceName}"`,
)
if (!apiResourceName || !scopeName) {
throw new BadRequestException(
'scopeName and apiResourceName must be provided',
)
}
return await this.apiResourceScope.destroy({
where: { apiResourceName: apiResourceName, scopeName: scopeName },
})
}
/** Removes connections from ApiResourceScope for an Api Scope */
async removeApiScopeFromApiResourceScope(scopeName: string): Promise<number> {
return await this.apiResourceScope.destroy({
where: { scopeName: scopeName },
})
}
/** Get the Api resource conntected to Api Scope */
async findApiResourceScopeByScopeName(
scopeName: string,
): Promise<ApiResourceScope | null> {
return await this.apiResourceScope.findOne({
where: { scopeName: scopeName },
})
}
// User Claims
/** Gets all Identity Resource User Claims */
async findAllIdentityResourceUserClaims(): Promise<
IdentityResourceUserClaim[]
> {
return this.identityResourceUserClaimModel.findAll({
attributes: [
[Sequelize.fn('DISTINCT', Sequelize.col('claim_name')), 'claimName'],
],
})
}
/** Gets all Api Scope User Claims */
async findAllApiScopeUserClaims(): Promise<ApiScopeUserClaim[]> {
return this.apiScopeUserClaimModel.findAll({
attributes: [
[Sequelize.fn('DISTINCT', Sequelize.col('claim_name')), 'claimName'],
],
})
}
/** Gets all Api Resource User Claims */
async findAllApiResourceUserClaims(): Promise<ApiResourceUserClaim[]> {
return this.apiResourceUserClaim.findAll({
attributes: [
[Sequelize.fn('DISTINCT', Sequelize.col('claim_name')), 'claimName'],
],
})
}
/** Creates a new user claim for Api Resource */
async createApiResourceUserClaim(
claim: UserClaimDTO,
): Promise<ApiResourceUserClaim> {
return this.apiResourceUserClaim.create({
apiResourceName: claim.resourceName,
claimName: claim.claimName,
})
}
/** Creates a new user claim for Identity Resource */
async createIdentityResourceUserClaim(
claim: UserClaimDTO,
): Promise<IdentityResourceUserClaim> {
return this.identityResourceUserClaimModel.create({
identityResourceName: claim.resourceName,
claimName: claim.claimName,
})
}
/** Creates a new user claim for Api Scope */
async createApiScopeUserClaim(
claim: UserClaimDTO,
): Promise<ApiScopeUserClaim> {
return this.apiScopeUserClaimModel.create({
apiScopeName: claim.resourceName,
claimName: claim.claimName,
})
}
// #region ApiScopeGroup
/** Creates a new Api Scope Group */
async createApiScopeGroup(group: ApiScopeGroupDTO): Promise<ApiScopeGroup> {
const id = uuid()
return this.apiScopeGroup.create({ id: id, ...group })
}
/** Updates an existing ApiScopeGroup */
async updateApiScopeGroup(
group: ApiScopeGroupDTO,
id: string,
): Promise<[number, ApiScopeGroup[]]> {
return this.apiScopeGroup.update({ ...group }, { where: { id: id } })
}
/** Delete ApiScopeGroup */
async deleteApiScopeGroup(id: string): Promise<number> {
return this.apiScopeGroup.destroy({ where: { id: id } })
}
/** Returns all ApiScopeGroups */
async findAllApiScopeGroups(): Promise<ApiScopeGroup[]> {
return this.apiScopeGroup.findAll({
order: [['name', 'asc']],
include: [ApiScope],
})
}
/** Returns all ApiScopeGroups by name if specified with Paging */
async findAndCountAllApiScopeGroups(
searchString: string,
page: number,
count: number,
): Promise<{
rows: ApiScopeGroup[]
count: number
}> {
page--
const offset = page * count
if (!searchString || searchString.length === 0) {
searchString = '%'
}
return this.apiScopeGroup.findAndCountAll({
limit: count,
offset: offset,
where: { name: { [Op.iLike]: `%${searchString}%` } },
order: [['name', 'asc']],
include: [ApiScope],
})
}
/** Finds Api SCope Group by Id */
async findApiScopeGroupByPk(id: string): Promise<ApiScopeGroup | null> {
return this.apiScopeGroup.findByPk(id, { include: [ApiScope] })
}
// #endregion ApiScopeGroup
async findActorApiScopes(requestedScopes: string[]): Promise<string[]> {
const scopes: ApiScope[] = await this.apiScopeModel.findAll({
where: {
alsoForDelegatedUser: true,
name: { [Op.in]: requestedScopes },
},
include: [ApiScopeGroup],
})
return scopes.map((s: ApiScope): string => s.name)
}
// #region Domain
/** Find all domains with or without paging */
async findAllDomains(
searchString: string | null = null,
page: number | null = null,
count: number | null = null,
): Promise<Domain[] | PagedRowsDto<Domain>> {
if (page && count) {
if (page > 0 && count > 0) {
page!--
const offset = page! * count!
if (!searchString || searchString.length === 0) {
searchString = '%'
}
return this.domainModel.findAndCountAll({
limit: count,
offset: offset,
where: { name: { [Op.iLike]: `%${searchString}%` } },
order: [['name', 'asc']],
include: [ApiScopeGroup],
})
}
}
return this.domainModel.findAll({ order: [['name', 'asc']] })
}
/** Gets domain by name */
async findDomainByPk(name: string): Promise<Domain | null> {
return this.domainModel.findByPk(name)
}
/** Creates a new Domain */
async createDomain(domain: DomainDTO): Promise<Domain> {
return this.domainModel.create({ ...domain })
}
/** Updates an existing Domain */
async updateDomain(
domain: DomainDTO,
name: string,
): Promise<[number, Domain[]]> {
return this.domainModel.update({ ...domain }, { where: { name: name } })
}
/** Delete Domain */
async deleteDomain(name: string): Promise<number> {
return this.domainModel.destroy({ where: { name: name } })
}
// #endregion Domain
} | the_stack |
function array_sort(o: any, comparator?: any): any {
"use strict";
function min(a: any, b: any) {
return a < b ? a : b;
}
function stringComparator(a: any, b: any) {
var aString = a.string;
var bString = b.string;
var aLength = aString.length;
var bLength = bString.length;
var length = min(aLength, bLength);
for (var i = 0; i < length; ++i) {
var aCharCode = aString.charCodeAt(i);
var bCharCode = bString.charCodeAt(i);
if (aCharCode === bCharCode) {
continue;
}
return aCharCode - bCharCode;
}
return aLength - bLength;
}
// Move undefineds and holes to the end of a sparse array. Result is [values..., undefineds..., holes...].
function compactSparse(array: any, dst: any, src: any, length: any) {
var seen: any = { };
var valueCount = 0;
var undefinedCount = 0;
// Clean up after the in-progress non-sparse compaction that failed.
for (let i = dst; i < src; ++i) {
delete array[i];
}
for (var obj = array; obj; obj = Object.getPrototypeOf(obj)) {
var propertyNames = Object.getOwnPropertyNames(obj);
for (var i = 0; i < propertyNames.length; ++i) {
var index = propertyNames[i];
if (index < length) { // Exclude non-numeric properties and properties past length.
if (seen[index]) { // Exclude duplicates.
continue;
}
seen[index] = 1;
var value = array[index];
delete array[index];
if (value === undefined) {
++undefinedCount;
continue;
}
array[valueCount++] = value;
}
}
}
for (var i = valueCount; i < valueCount + undefinedCount; ++i) {
array[i] = undefined;
}
return valueCount;
}
function compactSlow(array: any, length: any) {
var holeCount = 0;
for (var dst = 0, src = 0; src < length; ++src) {
if (!(src in array)) {
++holeCount;
if (holeCount < 256) {
continue;
}
return compactSparse(array, dst, src, length);
}
var value = array[src];
if (value === undefined) {
continue;
}
array[dst++] = value;
}
var valueCount = dst;
var undefinedCount = length - valueCount - holeCount;
for (var i = valueCount; i < valueCount + undefinedCount; ++i) {
array[i] = undefined;
}
for (var i = valueCount + undefinedCount; i < length; ++i) {
delete array[i];
}
return valueCount;
}
// Move undefineds and holes to the end of an array. Result is [values..., undefineds..., holes...].
function compact(array: any, length: any) {
for (var i = 0; i < array.length; ++i) {
if (array[i] === undefined) {
return compactSlow(array, length);
}
}
return length;
}
function merge(dst: any, src: any, srcIndex: any, srcEnd: any, width: any, comparator: any) {
var left = srcIndex;
var leftEnd = min(left + width, srcEnd);
var right = leftEnd;
var rightEnd = min(right + width, srcEnd);
for (var dstIndex = left; dstIndex < rightEnd; ++dstIndex) {
if (right < rightEnd) {
if (left >= leftEnd) {
dst[dstIndex] = src[right++];
continue;
}
let comparisonResult = comparator(src[right], src[left]);
if ((typeof comparisonResult === "boolean" && !comparisonResult) || comparisonResult < 0) {
dst[dstIndex] = src[right++];
continue;
}
}
dst[dstIndex] = src[left++];
}
}
function mergeSort(array: any, valueCount: any, comparator: any) {
var buffer : any = [ ];
buffer.length = valueCount;
var dst = buffer;
var src = array;
for (var width = 1; width < valueCount; width *= 2) {
for (var srcIndex = 0; srcIndex < valueCount; srcIndex += 2 * width) {
merge(dst, src, srcIndex, valueCount, width, comparator);
}
var tmp = src;
src = dst;
dst = tmp;
}
if (src !== array) {
for(var i = 0; i < valueCount; i++) {
array[i] = src[i];
}
}
}
function bucketSort(array: any, dst: any, bucket: any, depth: any) {
if (bucket.length < 32 || depth > 32) {
mergeSort(bucket, bucket.length, stringComparator);
for (var i = 0; i < bucket.length; ++i) {
array[dst++] = bucket[i].value;
}
return dst;
}
var buckets: any = [ ];
for (var i = 0; i < bucket.length; ++i) {
var entry = bucket[i];
var string = entry.string;
if (string.length === depth) {
array[dst++] = entry.value;
continue;
}
var c = string.charCodeAt(depth);
if (!buckets[c]) {
buckets[c] = [ ];
}
buckets[c][buckets[c].length] = entry;
}
for (var i = 0; i < buckets.length; ++i) {
if (!buckets[i]) {
continue;
}
dst = bucketSort(array, dst, buckets[i], depth + 1);
}
return dst;
}
function comparatorSort(array: any, length: any, comparator: any) {
var valueCount = compact(array, length);
mergeSort(array, valueCount, comparator);
}
function stringSort(array: any, length: any) {
var valueCount = compact(array, length);
var strings = new Array(valueCount);
for (var i = 0; i < valueCount; ++i) {
strings[i] = { string: array[i], value: array[i] };
}
bucketSort(array, 0, strings, 0);
}
var array = o;
var length = array.length >>> 0;
// For compatibility with Firefox and Chrome, do nothing observable
// to the target array if it has 0 or 1 sortable properties.
if (length < 2) {
return array;
}
if (typeof comparator === "function") {
comparatorSort(array, length, comparator);
}
else if (comparator === null || comparator === undefined) {
stringSort(array, length);
}
else {
throw new TypeError("Array.prototype.sort requires the comparsion function be a function or undefined");
}
return array;
}
var stopifyArrayPrototype = {
__proto__: Array.prototype,
map: function(f: any) {
if (arguments.length !== 1) {
throw new Error(`.map requires 1 argument`);
}
let result = [ ];
for (let i = 0; i < this.length; ++i) {
result.push(f(this[i]));
}
return stopifyArray(result);
},
filter: function(f: any) {
if (arguments.length !== 1) {
throw new Error(`.filter requires 1 argument`);
}
let result = [ ];
for (let i = 0; i < this.length; ++i) {
if (f(this[i])) {
result.push(this[i]);
}
}
return stopifyArray(result);
},
reduceRight: function(f: any, init: any) {
if (arguments.length !== 2) {
throw new Error(`.reduceRight requires 2 arguments`);
}
var arrLen = this.length;
var acc = init;
var i = arrLen - 1;
while (i >= 0) {
acc = f(acc, this[i]);
i = i - 1;
}
return acc;
},
reduce: function(f: any, init: any) {
if (arguments.length !== 2) {
throw new Error(`.reduce requires 2 arguments`);
}
var arrLen = this.length;
var acc = init;
var i = 0;
while (i < arrLen) {
acc = f(acc, this[i]);
i = i + 1;
}
return acc;
},
some: function(pred: any) {
if (arguments.length !== 1) {
throw new Error(`.some requires 1 argument`);
}
var i = 0;
var l = this.length;
while (i < l) {
if (pred(this[i])) {
return true;
}
i = i + 1;
}
return false;
},
every: function(pred: any) {
if (arguments.length !== 1) {
throw new Error(`.every requires 1 argument`);
}
var i = 0;
var l = this.length;
while (i < l) {
if (!pred(this[i])) {
return false;
}
i = i + 1;
}
return true;
},
find: function(pred: any) {
if (arguments.length !== 1) {
throw new Error(`.find requires 1 argument`);
}
var i = 0;
var l = this.length;
while (i < l) {
if (pred(this[i])) {
return this[i];
}
i = i + 1;
}
},
findIndex: function(pred: any) {
if (arguments.length !== 1) {
throw new Error(`.findIndex requires 1 argument`);
}
var i = 0;
var l = this.length;
while (i < l) {
if (pred(this[i])) {
return i;
}
i = i + 1;
}
return -1;
},
// NOTE(arjun): Ignores thisArg
forEach(f: any) {
if (arguments.length !== 1) {
throw new Error(`.forEach requires 1 argument`);
}
var i = 0;
var l = this.length;
while (i < l) {
f(this[i]);
i = i + 1;
}
},
sort: function(comparator: any) {
if (arguments.length !== 1) {
throw new Error(`.sort requires 1 argument`);
}
return stopifyArray(array_sort(this, comparator));
},
slice: function(begin: any, end: any) {
if (arguments.length !== 2) {
throw new Error(`.slice requires 2 arguments`);
}
if (begin < 0 || end > this.length) {
throw new Error(`.slice requires begin and end range to be within array`);
}
return stopifyArray(Array.prototype.slice.call(this, begin, end));
},
concat: function(anotherArray: any) {
if (arguments.length !== 1) {
throw new Error(`.concat requires 1 argument`);
}
return stopifyArray(Array.prototype.concat.call(this, anotherArray));
},
flat: function(depth: any) {
const nArgs = arguments.length;
if (nArgs > 1) {
throw new Error('.flat requires 0 or 1 argument');
}
if (nArgs === 1 && (typeof depth !== 'number' || depth < 1)) {
throw new Error('the depth argumeth to .flat must be a positive integer');
}
if (nArgs === 0) {
depth = 1;
}
return stopifyArray(Array.prototype.flat.call(this, depth));
},
flatMap: function(f: any) {
if (arguments.length !== 1) {
throw new Error(`.flatMap requires 1 argument`);
}
let result = [ ];
for (let i = 0; i < this.length; ++i) {
let arr = f(this[i]);
for (let j = 0; j < arr.length; ++j) {
result.push(arr[j]);
}
}
return stopifyArray(result);
},
};
export function stopifyArray(arr: any) {
// @stopify flat
Reflect.setPrototypeOf(arr, stopifyArrayPrototype);
return arr;
} | the_stack |
import * as tf from '../index';
import {ALL_ENVS, describeWithFlags} from '../jasmine_util';
import {Tensor4D} from '../tensor';
import {expectArraysClose, expectArraysEqual} from '../test_util';
const sqArr = (arr: number[]) => arr.map(d => d * d);
const sumArr = (arr: number[]) => arr.reduce((prev, curr) => prev + curr, 0);
// tslint:disable-next-line:no-any
const flatten = (arr: any): number[] => {
// tslint:disable-next-line:no-any
return arr.reduce((prev: any, curr: any) => {
return prev.concat(Array.isArray(curr) ? flatten(curr) : curr);
}, []);
};
describeWithFlags('localResponseNormalization with Tensor3D', ALL_ENVS, () => {
it('throws error with invalid input', () => {
// tslint:disable-next-line:no-any
const x: any = tf.tensor2d([1, 20, 300, 4], [1, 4]);
const radius = 3;
expect(() => x.localResponseNormalization(radius)).toThrowError();
});
it('throws error with invalid radius', () => {
const x = tf.tensor3d([1, 20, 300, 4], [1, 1, 4]);
const radius = 0.5;
expect(() => x.localResponseNormalization(radius)).toThrowError();
});
it('computes simple normalization across channels', async () => {
const xT = tf.tensor3d([1, 20, 300, 4], [1, 1, 4]);
const radius = 1;
const bias = 1;
const alpha = 1;
const beta = 0.5;
const result = xT.localResponseNormalization(radius, bias, alpha, beta);
const f = (...vals: number[]) =>
Math.pow(bias + alpha * sumArr(sqArr(vals)), -beta);
const x = await xT.array();
expectArraysClose(await result.data(), [
x[0][0][0] * f(x[0][0][0], x[0][0][1]),
x[0][0][1] * f(x[0][0][0], x[0][0][1], x[0][0][2]),
x[0][0][2] * f(x[0][0][1], x[0][0][2], x[0][0][3]),
x[0][0][3] * f(x[0][0][2], x[0][0][3]),
]);
});
it('uses beta = 1.0 to test GPU optimization', async () => {
const xT = tf.tensor3d([1, 20, 300, 4], [1, 1, 4]);
const radius = 1;
const bias = 1;
const alpha = 1;
const beta = 1.0;
const result = xT.localResponseNormalization(radius, bias, alpha, beta);
const f = (...vals: number[]) =>
Math.pow(bias + alpha * sumArr(sqArr(vals)), -beta);
const x = await xT.array();
expectArraysClose(await result.data(), [
x[0][0][0] * f(x[0][0][0], x[0][0][1]),
x[0][0][1] * f(x[0][0][0], x[0][0][1], x[0][0][2]),
x[0][0][2] * f(x[0][0][1], x[0][0][2], x[0][0][3]),
x[0][0][3] * f(x[0][0][2], x[0][0][3]),
]);
});
it('uses beta = 0.75 to test GPU optimization', async () => {
const xT = tf.tensor3d([1, 20, 300, 4], [1, 1, 4]);
const radius = 1;
const bias = 1;
const alpha = 1;
const beta = 0.75;
const result = xT.localResponseNormalization(radius, bias, alpha, beta);
const f = (...vals: number[]) =>
Math.pow(bias + alpha * sumArr(sqArr(vals)), -beta);
const x = await xT.array();
expectArraysClose(await result.data(), [
x[0][0][0] * f(x[0][0][0], x[0][0][1]),
x[0][0][1] * f(x[0][0][0], x[0][0][1], x[0][0][2]),
x[0][0][2] * f(x[0][0][1], x[0][0][2], x[0][0][3]),
x[0][0][3] * f(x[0][0][2], x[0][0][3]),
]);
});
it('computes complex normalization across channels', async () => {
const xT = tf.tensor3d(
[1, 20, 300, 4, 5, 15, 24, 200, 1, 20, 300, 4, 5, 15, 24, 200],
[2, 2, 4]);
const radius = 1;
const bias = 1;
const alpha = 1;
const beta = 0.5;
const result = xT.localResponseNormalization(radius, bias, alpha, beta);
const f = (...vals: number[]) =>
Math.pow(bias + alpha * sumArr(sqArr(vals)), -beta);
// 1 | 2 | 3 | 4
// ------- | ------- | ------- | -------
// o x . . | x o x . | . x o x | . . x o
const x = await xT.array();
expectArraysClose(await result.data(), [
// 1 - 4
x[0][0][0] * f(x[0][0][0], x[0][0][1]),
x[0][0][1] * f(x[0][0][0], x[0][0][1], x[0][0][2]),
x[0][0][2] * f(x[0][0][1], x[0][0][2], x[0][0][3]),
x[0][0][3] * f(x[0][0][2], x[0][0][3]),
// 1 - 4
x[0][1][0] * f(x[0][1][0], x[0][1][1]),
x[0][1][1] * f(x[0][1][0], x[0][1][1], x[0][1][2]),
x[0][1][2] * f(x[0][1][1], x[0][1][2], x[0][1][3]),
x[0][1][3] * f(x[0][1][2], x[0][1][3]),
// 1 - 4
x[1][0][0] * f(x[1][0][0], x[1][0][1]),
x[1][0][1] * f(x[1][0][0], x[1][0][1], x[1][0][2]),
x[1][0][2] * f(x[1][0][1], x[1][0][2], x[1][0][3]),
x[1][0][3] * f(x[1][0][2], x[1][0][3]),
// 1 - 4
x[1][1][0] * f(x[1][1][0], x[1][1][1]),
x[1][1][1] * f(x[1][1][0], x[1][1][1], x[1][1][2]),
x[1][1][2] * f(x[1][1][1], x[1][1][2], x[1][1][3]),
x[1][1][3] * f(x[1][1][2], x[1][1][3]),
]);
});
it('yields same result as tensorflow', async () => {
// t = tf.random_uniform([1, 3, 3, 8])
// l = tf.nn.lrn(t, depth_radius=2)
// print(tf.Session().run([t, l]))
const input = [
[
[
0.95782757, 0.12892687, 0.63624668, 0.70160735, 0.77376258,
0.54166114, 0.71172535, 0.65087497
],
[
0.91872108, 0.38846886, 0.37847793, 0.50477624, 0.42154622,
0.43310916, 0.36253822, 0.07576156
],
[
0.48662257, 0.4154036, 0.81704032, 0.91660416, 0.87671542, 0.64215934,
0.29933751, 0.90671134
]
],
[
[
0.6208992, 0.60847163, 0.41475761, 0.2127713, 0.65306914, 0.13923979,
0.32003641, 0.28183973
],
[
0.04751575, 0.26870155, 0.45150304, 0.58678186, 0.99118924,
0.58878231, 0.30913198, 0.18836617
],
[
0.16166461, 0.56322742, 0.67908955, 0.2269547, 0.38491273, 0.97113752,
0.51210916, 0.69430435
]
],
[
[
0.06625497, 0.13011181, 0.59202921, 0.88871598, 0.6366322, 0.47911358,
0.96530843, 0.74259472
],
[
0.62660718, 0.0445286, 0.18430257, 0.76863647, 0.87511849, 0.53588808,
0.27980685, 0.30281997
],
[
0.73987067, 0.91034842, 0.26241004, 0.72832751, 0.78974342,
0.50751543, 0.05434644, 0.8231523
]
]
];
const expected = [
[
[
0.62630326, 0.07662392, 0.34354961, 0.41885775, 0.42621866,
0.29751951, 0.42365381, 0.4364861
],
[
0.62828875, 0.251122, 0.23605582, 0.36483878, 0.30624411, 0.32672295,
0.29576892, 0.06582346
],
[
0.3376624, 0.24321821, 0.42558169, 0.46646208, 0.45103404, 0.32380751,
0.17021206, 0.59476018
]
],
[
[
0.44719055, 0.43318295, 0.26775005, 0.14921051, 0.49148726,
0.10764983, 0.25084552, 0.25714993
],
[
0.04202608, 0.21094096, 0.27973703, 0.34166718, 0.57487047,
0.35158369, 0.19708875, 0.15495601
],
[
0.12034657, 0.41341963, 0.47968671, 0.13278878, 0.22735766,
0.57154536, 0.30411762, 0.42352781
]
],
[
[
0.05656794, 0.08849642, 0.36951816, 0.53186077, 0.33065733,
0.24236222, 0.54666328, 0.45085984
],
[
0.52425432, 0.03133496, 0.11043368, 0.46954039, 0.5271349, 0.31946796,
0.1876673, 0.25085902
],
[
0.47316891, 0.5277527, 0.13831842, 0.40036613, 0.50113004, 0.28860986,
0.03395459, 0.59127772
]
]
];
const x = tf.tensor3d(flatten(input), [3, 3, 8]);
const radius = 2;
const bias = 1;
const alpha = 1;
const beta = 0.5;
const result = x.localResponseNormalization(radius, bias, alpha, beta);
expectArraysClose(await result.data(), flatten(expected));
});
it('accepts a tensor-like object', async () => {
const x = [[[1, 20, 300, 4]]]; // 1x1x4
const radius = 1;
const bias = 1;
const alpha = 1;
const beta = 0.5;
const result = tf.localResponseNormalization(x, radius, bias, alpha, beta);
const f = (...vals: number[]) =>
Math.pow(bias + alpha * sumArr(sqArr(vals)), -beta);
expectArraysClose(await result.data(), [
x[0][0][0] * f(x[0][0][0], x[0][0][1]),
x[0][0][1] * f(x[0][0][0], x[0][0][1], x[0][0][2]),
x[0][0][2] * f(x[0][0][1], x[0][0][2], x[0][0][3]),
x[0][0][3] * f(x[0][0][2], x[0][0][3]),
]);
});
});
describeWithFlags('localResponseNormalization with Tensor4D', ALL_ENVS, () => {
it('throws error with invalid input', () => {
// tslint:disable-next-line:no-any
const x: any = tf.tensor2d([1, 20, 300, 4], [1, 4]);
const radius = 3;
expect(() => x.localResponseNormalization(radius)).toThrowError();
});
it('throws error with invalid radius', () => {
const x = tf.tensor4d([1, 20, 300, 4], [1, 1, 1, 4]);
const radius = 0.5;
expect(() => x.localResponseNormalization(radius)).toThrowError();
});
it('computes simple normalization across channels', async () => {
const xT = tf.tensor4d([1, 20, 300, 4, 1, 20, 300, 4], [2, 1, 1, 4]);
const radius = 1;
const bias = 1;
const alpha = 1;
const beta = 0.5;
const result = xT.localResponseNormalization(radius, bias, alpha, beta);
const f = (...vals: number[]) =>
Math.pow(bias + alpha * sumArr(sqArr(vals)), -beta);
// Easier to read using these vars
const b0 = 0;
const b1 = 1;
const x = await xT.array();
expectArraysClose(await result.data(), [
x[b0][0][0][0] * f(x[b0][0][0][0], x[b0][0][0][1]),
x[b0][0][0][1] * f(x[b0][0][0][0], x[b0][0][0][1], x[b0][0][0][2]),
x[b0][0][0][2] * f(x[b0][0][0][1], x[b0][0][0][2], x[b0][0][0][3]),
x[b0][0][0][3] * f(x[b0][0][0][2], x[b0][0][0][3]),
x[b1][0][0][0] * f(x[b1][0][0][0], x[b1][0][0][1]),
x[b1][0][0][1] * f(x[b1][0][0][0], x[b1][0][0][1], x[b1][0][0][2]),
x[b1][0][0][2] * f(x[b1][0][0][1], x[b1][0][0][2], x[b1][0][0][3]),
x[b1][0][0][3] * f(x[b1][0][0][2], x[b1][0][0][3]),
]);
});
it('yields same result as tensorflow', async () => {
// t = tf.random_uniform([2, 3, 3, 8])
// l = tf.nn.lrn(t, depth_radius=2)
// print(tf.Session().run([t, l]))
const input = [
[
[
[
0.5659827, 0.57000327, 0.75555623, 0.89843333, 0.55120194,
0.53531718, 0.56402838, 0.95481384
],
[
0.57334661, 0.65172958, 0.75794137, 0.80764937, 0.376616,
0.92726362, 0.36422753, 0.60535395
],
[
0.82404268, 0.01054764, 0.4649173, 0.91637003, 0.82287347, 0.043468,
0.44953859, 0.92056584
]
],
[
[
0.68583369, 0.52534163, 0.53325927, 0.39608097, 0.9337523,
0.37397444, 0.81212556, 0.5697
],
[
0.34278774, 0.57656682, 0.2356832, 0.02636456, 0.49111438,
0.17981696, 0.65398049, 0.70132935
],
[
0.14241767, 0.68376505, 0.65419888, 0.69369483, 0.21489143,
0.46235347, 0.0559243, 0.60612857
]
],
[
[
0.59678483, 0.09368539, 0.3017447, 0.36870825, 0.68145788,
0.52048779, 0.46136606, 0.94114387
],
[
0.3156569, 0.75275254, 0.31970251, 0.3154043, 0.61088014,
0.13359487, 0.99048364, 0.33625424
],
[
0.82103574, 0.52066624, 0.63629258, 0.42294252, 0.93214262,
0.57041013, 0.66087878, 0.7019999
]
]
],
[
[
[
0.21894431, 0.43085241, 0.79883206, 0.19462204, 0.68623316,
0.08703053, 0.82380795, 0.85634673
],
[
0.45011401, 0.70312083, 0.86319792, 0.83205295, 0.67109787,
0.82081223, 0.46556532, 0.46408331
],
[
0.07028461, 0.0038743, 0.44619524, 0.0611403, 0.96373355,
0.80561554, 0.42428243, 0.46897113
]
],
[
[
0.21006894, 0.48764861, 0.36842632, 0.23030031, 0.69685507,
0.31707478, 0.68662715, 0.0639503
],
[
0.53940296, 0.50777435, 0.12625301, 0.12324154, 0.89205229,
0.69380629, 0.33191144, 0.81000078
],
[
0.52650976, 0.71220326, 0.07246161, 0.08874547, 0.42528927,
0.36320579, 0.54055619, 0.79342318
]
],
[
[
0.75916636, 0.74499428, 0.76877356, 0.87210917, 0.93040991,
0.49491942, 0.70801985, 0.14901721
],
[
0.27037835, 0.89302075, 0.69147241, 0.23044991, 0.98916364,
0.60161841, 0.63691151, 0.56759977
],
[
0.56307781, 0.92782414, 0.25880754, 0.98518133, 0.04097319,
0.24640906, 0.54566145, 0.99261606
]
]
]
];
const expected = [
[
[
[
0.38019636, 0.32782161, 0.414222, 0.49507114, 0.3040463, 0.28107059,
0.33586296, 0.60191077
],
[
0.37577698, 0.37752095, 0.42895618, 0.4225589, 0.2054275,
0.52219951, 0.23032214, 0.39414096
],
[
0.59856331, 0.00637784, 0.25168711, 0.5541048, 0.48015645,
0.02301128, 0.27214608, 0.6427291
]
],
[
[
0.48127589, 0.35518789, 0.30486941, 0.23976389, 0.52926594,
0.21061926, 0.46920502, 0.39090639
],
[
0.27937523, 0.46979892, 0.17829391, 0.02044933, 0.37045884,
0.12140442, 0.44160855, 0.50198948
],
[
0.10289387, 0.44164398, 0.41853485, 0.42720893, 0.14580171,
0.31817055, 0.043797, 0.48155668
]
],
[
[
0.49458414, 0.07425242, 0.21042404, 0.26262277, 0.46205613,
0.30202535, 0.27406475, 0.61140078
],
[
0.23736385, 0.55076694, 0.2135559, 0.21463785, 0.38077739,
0.08309806, 0.62830603, 0.23137885
],
[
0.5355776, 0.32740855, 0.3451882, 0.24221195, 0.51988536,
0.31387195, 0.37391993, 0.46748781
]
]
],
[
[
[
0.16003507, 0.31178808, 0.51775187, 0.12722474, 0.40769571,
0.05085804, 0.48455271, 0.5505302
],
[
0.2880325, 0.39714804, 0.45591024, 0.4131493, 0.34525412, 0.4554069,
0.29119283, 0.31980222
],
[
0.0640529, 0.00352532, 0.3052578, 0.03666528, 0.56009793,
0.46656418, 0.24587312, 0.32762629
]
],
[
[
0.17643087, 0.40210918, 0.2634095, 0.16233148, 0.4649446,
0.21803913, 0.47819966, 0.05093931
],
[
0.43121469, 0.403974, 0.08191212, 0.07693455, 0.57362044,
0.39671475, 0.19025819, 0.54028469
],
[
0.39356521, 0.53120333, 0.05151648, 0.06554616, 0.33433318,
0.2425479, 0.36161765, 0.5536595
]
],
[
[
0.46011236, 0.39919043, 0.36865807, 0.43511948, 0.46734285,
0.26861796, 0.43624333, 0.11205748
],
[
0.17642327, 0.57622254, 0.37609601, 0.12030836, 0.54640025,
0.34052721, 0.36361033, 0.3926385
],
[
0.37581176, 0.51741964, 0.14429154, 0.57254595, 0.02646073,
0.13531584, 0.35629693, 0.64837402
]
]
]
];
const x = tf.tensor4d(flatten(input), [2, 3, 3, 8]);
const radius = 2;
const result = x.localResponseNormalization(radius);
expectArraysClose(await result.data(), flatten(expected));
});
it('yields same result as tensorflow with inner most dims of odd shape',
async () => {
// t = tf.random_uniform([1, 5, 5, 3])
// l = tf.nn.lrn(t, depth_radius=2)
// print(tf.Session().run([t, l]))
const input = [[
[
[0.08576167, 0.5713569, 0.10008252],
[0.9822943, 0.11068773, 0.5733849],
[0.52175903, 0.7347398, 0.760726], [0.7118578, 0.3927865, 0.7521831],
[0.849753, 0.43948555, 0.42316127]
],
[
[0.5843748, 0.27483034, 0.45537806],
[0.91386235, 0.56130767, 0.2968701],
[0.37907827, 0.11928034, 0.32693362],
[0.8294349, 0.9177762, 0.01197743],
[0.44460166, 0.22238493, 0.93720853]
],
[
[0.12325168, 0.62378526, 0.6220398],
[0.9955342, 0.8281578, 0.9977399],
[0.78915524, 0.48492992, 0.70430815],
[0.856709, 0.91682327, 0.53920233],
[0.9217057, 0.32411182, 0.16391528]
],
[
[0.3235209, 0.43057775, 0.5644517],
[0.93911314, 0.09265935, 0.05458856],
[0.06284857, 0.6895604, 0.88354754],
[0.32220483, 0.72595966, 0.3620714],
[0.15844965, 0.931878, 0.8501971]
],
[
[0.07301581, 0.7518866, 0.40925968],
[0.82419384, 0.40474093, 0.53465044],
[0.34532738, 0.21671772, 0.50855494],
[0.04778886, 0.7952956, 0.64908195],
[0.8807392, 0.09571135, 0.7910882]
]
]];
const expected = [[
[
[0.07398141, 0.4928751, 0.08633514],
[0.6468731, 0.07289152, 0.37759283],
[0.33744285, 0.4751862, 0.49199253],
[0.4770374, 0.2632181, 0.50406057],
[0.58718365, 0.30368677, 0.2924066]
],
[
[0.45850667, 0.21563481, 0.35729447],
[0.6108259, 0.37517825, 0.19842808],
[0.3370665, 0.10606097, 0.29070085],
[0.52141804, 0.5769532, 0.00752952],
[0.30495936, 0.15253738, 0.6428463]
],
[
[0.09209093, 0.46607855, 0.4647744],
[0.51949346, 0.43215245, 0.5206444],
[0.5143535, 0.31606635, 0.45905212],
[0.50611794, 0.54163164, 0.31854454],
[0.65478665, 0.23025146, 0.11644664]
],
[
[0.25507566, 0.3394832, 0.4450343],
[0.68247277, 0.06733745, 0.03967063],
[0.04180532, 0.45867857, 0.587714],
[0.24273802, 0.546913, 0.27277213], [0.097959, 0.5761189, 0.525621]
],
[
[0.05538246, 0.57030565, 0.31042328],
[0.56486595, 0.27739152, 0.36642575],
[0.2892991, 0.18155594, 0.42604348],
[0.03332775, 0.55463576, 0.452667],
[0.56725365, 0.06164437, 0.50951254]
]
]];
const x = tf.tensor4d(input, [1, 5, 5, 3]);
const radius = 2;
const result = x.localResponseNormalization(radius);
expectArraysClose(await result.data(), flatten(expected));
});
it('throws when passed a non-tensor', () => {
const e =
/Argument 'x' passed to 'localResponseNormalization' must be a Tensor/;
expect(() => tf.localResponseNormalization({} as tf.Tensor3D))
.toThrowError(e);
});
it('gradient with 3D input', async () => {
const input = [
[
[
0.95782757, 0.12892687, 0.63624668, 0.70160735, 0.77376258,
0.54166114, 0.71172535, 0.65087497
],
[
0.91872108, 0.38846886, 0.37847793, 0.50477624, 0.42154622,
0.43310916, 0.36253822, 0.07576156
],
[
0.48662257, 0.4154036, 0.81704032, 0.91660416, 0.87671542, 0.64215934,
0.29933751, 0.90671134
]
],
[
[
0.6208992, 0.60847163, 0.41475761, 0.2127713, 0.65306914, 0.13923979,
0.32003641, 0.28183973
],
[
0.04751575, 0.26870155, 0.45150304, 0.58678186, 0.99118924,
0.58878231, 0.30913198, 0.18836617
],
[
0.16166461, 0.56322742, 0.67908955, 0.2269547, 0.38491273, 0.97113752,
0.51210916, 0.69430435
]
],
[
[
0.06625497, 0.13011181, 0.59202921, 0.88871598, 0.6366322, 0.47911358,
0.96530843, 0.74259472
],
[
0.62660718, 0.0445286, 0.18430257, 0.76863647, 0.87511849, 0.53588808,
0.27980685, 0.30281997
],
[
0.73987067, 0.91034842, 0.26241004, 0.72832751, 0.78974342,
0.50751543, 0.05434644, 0.8231523
]
]
];
const expected = [[
[
[
0.27552658, 0.52414668, 0.11137494, 0.24928074, 0.07215497,
0.16210511, 0.19277242, 0.38672262
],
[
0.23314378, 0.38181645, 0.30470729, 0.35180706, 0.37793165,
0.41450983, 0.60044503, 0.83605933
],
[
0.51801264, 0.38517883, 0.02934788, 0.03102355, 0.08222333,
0.09746625, 0.4151727, 0.29936206
]
],
[
[
0.37059873, 0.32463685, 0.26611608, 0.54228389, 0.30733055,
0.66392428, 0.55629295, 0.79049641
],
[
0.87162501, 0.68129337, 0.35793597, 0.18797961, -0.03660985,
0.23235559, 0.48184156, 0.76417446
],
[
0.65893668, 0.41059417, 0.26254228, 0.40696776, 0.3330358, 0.01789692,
0.3162199, 0.28867012
]
],
[
[
0.83880937, 0.62594998, 0.324698, 0.13046435, 0.09858654, 0.17851587,
0.09067203, 0.30748016
],
[
0.57213897, 0.67710453, 0.45385274, 0.19951296, 0.07371041,
0.20141563, 0.51362634, 0.7163325
],
[
0.33668244, 0.09696329, 0.33500126, 0.08948036, 0.26512182,
0.19593786, 0.59144169, 0.379444
]
]
]];
const radius = 2.0;
const bias = 1.0;
const alpha = 1.0;
const beta = 0.5;
const t = tf.tensor3d(input);
const dy = tf.onesLike(t);
const gradients = tf.grad(
(t: tf.Tensor3D) =>
tf.localResponseNormalization(t, radius, bias, alpha, beta))(t, dy);
expectArraysEqual(gradients.shape, t.shape);
expectArraysClose(await gradients.data(), flatten(expected));
});
it('gradient with clones', () => {
const t = tf.zeros([3, 3, 8]);
const radius = 2.0;
const bias = 1.0;
const alpha = 1.0;
const beta = 0.5;
const dt = tf.grad(
(t: tf.Tensor3D) =>
tf.localResponseNormalization(t.clone(), radius, bias, alpha, beta)
.clone())(t);
expectArraysEqual(dt.shape, t.shape);
});
it('gradient with 4D input', async () => {
const input = [
[
[
[
0.5659827, 0.57000327, 0.75555623, 0.89843333, 0.55120194,
0.53531718, 0.56402838, 0.95481384
],
[
0.57334661, 0.65172958, 0.75794137, 0.80764937, 0.376616,
0.92726362, 0.36422753, 0.60535395
],
[
0.82404268, 0.01054764, 0.4649173, 0.91637003, 0.82287347, 0.043468,
0.44953859, 0.92056584
]
],
[
[
0.68583369, 0.52534163, 0.53325927, 0.39608097, 0.9337523,
0.37397444, 0.81212556, 0.5697
],
[
0.34278774, 0.57656682, 0.2356832, 0.02636456, 0.49111438,
0.17981696, 0.65398049, 0.70132935
],
[
0.14241767, 0.68376505, 0.65419888, 0.69369483, 0.21489143,
0.46235347, 0.0559243, 0.60612857
]
],
[
[
0.59678483, 0.09368539, 0.3017447, 0.36870825, 0.68145788,
0.52048779, 0.46136606, 0.94114387
],
[
0.3156569, 0.75275254, 0.31970251, 0.3154043, 0.61088014,
0.13359487, 0.99048364, 0.33625424
],
[
0.82103574, 0.52066624, 0.63629258, 0.42294252, 0.93214262,
0.57041013, 0.66087878, 0.7019999
]
]
],
[
[
[
0.21894431, 0.43085241, 0.79883206, 0.19462204, 0.68623316,
0.08703053, 0.82380795, 0.85634673
],
[
0.45011401, 0.70312083, 0.86319792, 0.83205295, 0.67109787,
0.82081223, 0.46556532, 0.46408331
],
[
0.07028461, 0.0038743, 0.44619524, 0.0611403, 0.96373355,
0.80561554, 0.42428243, 0.46897113
]
],
[
[
0.21006894, 0.48764861, 0.36842632, 0.23030031, 0.69685507,
0.31707478, 0.68662715, 0.0639503
],
[
0.53940296, 0.50777435, 0.12625301, 0.12324154, 0.89205229,
0.69380629, 0.33191144, 0.81000078
],
[
0.52650976, 0.71220326, 0.07246161, 0.08874547, 0.42528927,
0.36320579, 0.54055619, 0.79342318
]
],
[
[
0.75916636, 0.74499428, 0.76877356, 0.87210917, 0.93040991,
0.49491942, 0.70801985, 0.14901721
],
[
0.27037835, 0.89302075, 0.69147241, 0.23044991, 0.98916364,
0.60161841, 0.63691151, 0.56759977
],
[
0.56307781, 0.92782414, 0.25880754, 0.98518133, 0.04097319,
0.24640906, 0.54566145, 0.99261606
]
]
]
];
const dyVals = [
[
[
[
1.40394282, -1.68962789, -0.21134049, 1.15015793, 1.51244378,
0.42844626, -2.70123291, 0.06449971
],
[
-0.29038581, 0.67567694, 0.95617437, -1.07383668, 0.20920482,
0.39050213, -0.81124371, 2.42158198
],
[
-1.01235235, -0.63514435, -1.49017262, -0.01205151, 0.78492945,
-0.20330679, -2.31419802, -0.31220308
]
],
[
[
0.07061944, -0.46716127, 0.91232526, -1.30444264, -0.07080109,
0.13207501, 0.26701283, -0.48946589
],
[
-0.74995744, -0.79466617, -1.03790498, -0.32234526, 1.33345711,
0.11863081, 1.93010819, 0.47857195
],
[
0.37702683, -0.7804451, 0.45868117, 1.06967258, -0.65336537,
0.3594887, 0.62512684, 0.77009726
]
],
[
[
0.76865023, 1.00893021, -0.24408816, -0.3943336, 0.47094285,
-2.61926222, 1.52929449, 0.7862013
],
[
-1.20878386, -0.26222935, -0.9076528, 0.03079577, -0.01467486,
-0.06949636, 0.05466342, 1.44880533
],
[
0.05611863, 0.15142779, 0.7802065, -1.2623471, 0.09119794,
-0.20110528, 0.17715968, -0.48476508
]
]
],
[
[
[
0.1549256, 0.94472402, -0.70033115, -1.05752802, -0.63035947,
-1.35643113, -0.27211693, 2.33576941
],
[
0.81070906, -0.58353454, -0.3253817, 2.53953528, -1.40062141,
1.7728076, -0.59849483, 1.49650824
],
[
-0.00610052, -2.29434419, -1.77995121, -0.66354084, -0.70676774,
-0.81570011, -1.30821037, 0.40997007
]
],
[
[
-1.02013469, -0.74198806, -0.82677251, -0.00890179, -1.62196338,
-0.5095427, 1.26501179, 0.12931485
],
[
-1.14763546, 0.11011696, -0.23312508, 0.29730096, -0.49138394,
-0.27012363, -0.15987533, -1.84277928
],
[
-0.03816459, -0.73517877, -2.00476885, 0.47192496, -0.27395752,
0.99806124, 1.54439747, -1.02016675
]
],
[
[
-1.27831209, -0.6961385, -0.73713994, -1.97954738, 0.39108652,
-0.46152538, 1.8255372, 2.18119025
],
[
0.56322283, -1.59858179, 1.54127491, -0.57665956, -1.0098567,
0.93239671, 0.25231698, -0.7346009
],
[
0.41614994, -1.20103085, 0.4330301, -1.23348403, -0.46117213,
-0.3780126, 0.35449561, -0.60129249
]
]
]
];
const depthRadius = 1;
const bias = 1;
const alpha = 1;
const beta = 0.75;
const expected = [
[
[
[
0.88732064, -0.98597342, -0.00569269, 0.09561057, 0.42255375,
0.30286378, -1.17104781, 0.44769961
],
[
-0.22329885, 0.19271846, 0.41454071, -0.50674957, 0.14660946,
0.1591837, -0.83707076, 1.19177234
],
[
-0.26728818, -0.3847312, -0.72818488, 0.09040837, 0.24023688,
-0.11545581, -1.09341288, 0.33930668
]
],
[
[
0.10079086, -0.38184536, 0.60918945, -0.7267822, 0.13867335,
0.03526202, 0.17270499, -0.2705338
],
[
-0.38344458, -0.15589149, -0.68160093, -0.27644777, 0.79392856,
-0.14384332, 0.67121017, -0.23130262
],
[
0.31069142, -0.39895257, 0.11755499, 0.39481708, -0.5234766,
0.2511853, 0.40955079, 0.3492966
]
],
[
[
0.32660595, 0.7240563, -0.18117335, -0.2649861, 0.67781603,
-1.46250272, 0.8465963, -0.05466701
],
[
-0.71582067, 0.20831716, -0.50778204, 0.07256755, -0.00893679,
-0.03798783, -0.18604305, 0.75747406
],
[
-0.00540833, -0.07677216, 0.41930205, -0.69235319, 0.20631291,
-0.11946303, 0.19601521, -0.21237698
]
]
],
[
[
[
0.0800111, 0.60922205, -0.31155977, -0.46448132, -0.15912701,
-0.72455585, -0.5727275, 0.71780092
],
[
0.50568235, -0.31544152, -0.40618286, 0.97909468, -1.15286613,
0.8145386, -0.77758539, 0.93794745
],
[
-0.00535599, -1.99269259, -1.15343952, -0.31053686, 0.01680636,
0.10109296, -0.66026396, 0.35474917
]
],
[
[
-0.74113333, -0.20625943, -0.4339568, 0.21517368, -0.5734458,
-0.23481363, 0.53855389, 0.05860626
],
[
-0.61435795, 0.29290834, -0.19639145, 0.20930134, -0.08880179,
0.02209887, 0.21427482, -0.51696646
],
[
0.13036536, -0.19079237, -1.43941545, 0.42789665, -0.29732707,
0.52354813, 0.78893, -0.59992862
]
],
[
[
-0.328383, 0.15830949, 0.13110149, -0.492423, 0.46827313,
-0.58950633, 0.56422544, 1.44929576
],
[
0.46141064, -0.80682266, 0.92562175, -0.28897452, -0.30567497,
0.50646484, 0.16439518, -0.38878182
],
[
0.41004074, -0.38593128, 0.42881966, -0.22443436, -0.24573228,
-0.2941249, 0.31119603, -0.17903978
]
]
]
];
const t = tf.tensor(input);
const dy = tf.tensor(dyVals);
const gradients = tf.grad(
t => tf.localResponseNormalization(
t as Tensor4D, depthRadius, bias, alpha, beta))(t, dy as Tensor4D);
expectArraysClose(await gradients.data(), flatten(expected));
});
}); | the_stack |
import Long from 'long';
import _m0 from 'protobufjs/minimal';
export const protobufPackage = 'opentelemetry.proto.common.v1';
/**
* AnyValue is used to represent any type of attribute value. AnyValue may contain a
* primitive value such as a string or integer or it may contain an arbitrary nested
* object containing arrays, key-value lists and primitives.
*/
export interface AnyValue {
stringValue: string | undefined;
boolValue: boolean | undefined;
intValue: number | undefined;
doubleValue: number | undefined;
arrayValue: ArrayValue | undefined;
kvlistValue: KeyValueList | undefined;
}
/**
* ArrayValue is a list of AnyValue messages. We need ArrayValue as a message
* since oneof in AnyValue does not allow repeated fields.
*/
export interface ArrayValue {
/** Array of values. The array may be empty (contain 0 elements). */
values: AnyValue[];
}
/**
* KeyValueList is a list of KeyValue messages. We need KeyValueList as a message
* since `oneof` in AnyValue does not allow repeated fields. Everywhere else where we need
* a list of KeyValue messages (e.g. in Span) we use `repeated KeyValue` directly to
* avoid unnecessary extra wrapping (which slows down the protocol). The 2 approaches
* are semantically equivalent.
*/
export interface KeyValueList {
/**
* A collection of key/value pairs of key-value pairs. The list may be empty (may
* contain 0 elements).
*/
values: KeyValue[];
}
/**
* KeyValue is a key-value pair that is used to store Span attributes, Link
* attributes, etc.
*/
export interface KeyValue {
key: string;
value: AnyValue | undefined;
}
/**
* StringKeyValue is a pair of key/value strings. This is the simpler (and faster) version
* of KeyValue that only supports string values.
*/
export interface StringKeyValue {
key: string;
value: string;
}
/**
* InstrumentationLibrary is a message representing the instrumentation library information
* such as the fully qualified name and version.
*/
export interface InstrumentationLibrary {
/** An empty instrumentation library name means the name is unknown. */
name: string;
version: string;
}
const baseAnyValue: object = {};
export const AnyValue = {
encode(message: AnyValue, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.stringValue !== undefined) {
writer.uint32(10).string(message.stringValue);
}
if (message.boolValue !== undefined) {
writer.uint32(16).bool(message.boolValue);
}
if (message.intValue !== undefined) {
writer.uint32(24).int64(message.intValue);
}
if (message.doubleValue !== undefined) {
writer.uint32(33).double(message.doubleValue);
}
if (message.arrayValue !== undefined) {
ArrayValue.encode(message.arrayValue, writer.uint32(42).fork()).ldelim();
}
if (message.kvlistValue !== undefined) {
KeyValueList.encode(message.kvlistValue, writer.uint32(50).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): AnyValue {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseAnyValue } as AnyValue;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.stringValue = reader.string();
break;
case 2:
message.boolValue = reader.bool();
break;
case 3:
message.intValue = longToNumber(reader.int64() as Long);
break;
case 4:
message.doubleValue = reader.double();
break;
case 5:
message.arrayValue = ArrayValue.decode(reader, reader.uint32());
break;
case 6:
message.kvlistValue = KeyValueList.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): AnyValue {
const message = { ...baseAnyValue } as AnyValue;
if (object.stringValue !== undefined && object.stringValue !== null) {
message.stringValue = String(object.stringValue);
} else {
message.stringValue = undefined;
}
if (object.boolValue !== undefined && object.boolValue !== null) {
message.boolValue = Boolean(object.boolValue);
} else {
message.boolValue = undefined;
}
if (object.intValue !== undefined && object.intValue !== null) {
message.intValue = Number(object.intValue);
} else {
message.intValue = undefined;
}
if (object.doubleValue !== undefined && object.doubleValue !== null) {
message.doubleValue = Number(object.doubleValue);
} else {
message.doubleValue = undefined;
}
if (object.arrayValue !== undefined && object.arrayValue !== null) {
message.arrayValue = ArrayValue.fromJSON(object.arrayValue);
} else {
message.arrayValue = undefined;
}
if (object.kvlistValue !== undefined && object.kvlistValue !== null) {
message.kvlistValue = KeyValueList.fromJSON(object.kvlistValue);
} else {
message.kvlistValue = undefined;
}
return message;
},
toJSON(message: AnyValue): unknown {
const obj: any = {};
message.stringValue !== undefined && (obj.stringValue = message.stringValue);
message.boolValue !== undefined && (obj.boolValue = message.boolValue);
message.intValue !== undefined && (obj.intValue = message.intValue);
message.doubleValue !== undefined && (obj.doubleValue = message.doubleValue);
message.arrayValue !== undefined &&
(obj.arrayValue = message.arrayValue ? ArrayValue.toJSON(message.arrayValue) : undefined);
message.kvlistValue !== undefined &&
(obj.kvlistValue = message.kvlistValue ? KeyValueList.toJSON(message.kvlistValue) : undefined);
return obj;
},
fromPartial(object: DeepPartial<AnyValue>): AnyValue {
const message = { ...baseAnyValue } as AnyValue;
if (object.stringValue !== undefined && object.stringValue !== null) {
message.stringValue = object.stringValue;
} else {
message.stringValue = undefined;
}
if (object.boolValue !== undefined && object.boolValue !== null) {
message.boolValue = object.boolValue;
} else {
message.boolValue = undefined;
}
if (object.intValue !== undefined && object.intValue !== null) {
message.intValue = object.intValue;
} else {
message.intValue = undefined;
}
if (object.doubleValue !== undefined && object.doubleValue !== null) {
message.doubleValue = object.doubleValue;
} else {
message.doubleValue = undefined;
}
if (object.arrayValue !== undefined && object.arrayValue !== null) {
message.arrayValue = ArrayValue.fromPartial(object.arrayValue);
} else {
message.arrayValue = undefined;
}
if (object.kvlistValue !== undefined && object.kvlistValue !== null) {
message.kvlistValue = KeyValueList.fromPartial(object.kvlistValue);
} else {
message.kvlistValue = undefined;
}
return message;
},
};
const baseArrayValue: object = {};
export const ArrayValue = {
encode(message: ArrayValue, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
for (const v of message.values) {
AnyValue.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): ArrayValue {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseArrayValue } as ArrayValue;
message.values = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.values.push(AnyValue.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ArrayValue {
const message = { ...baseArrayValue } as ArrayValue;
message.values = [];
if (object.values !== undefined && object.values !== null) {
for (const e of object.values) {
message.values.push(AnyValue.fromJSON(e));
}
}
return message;
},
toJSON(message: ArrayValue): unknown {
const obj: any = {};
if (message.values) {
obj.values = message.values.map((e) => (e ? AnyValue.toJSON(e) : undefined));
} else {
obj.values = [];
}
return obj;
},
fromPartial(object: DeepPartial<ArrayValue>): ArrayValue {
const message = { ...baseArrayValue } as ArrayValue;
message.values = [];
if (object.values !== undefined && object.values !== null) {
for (const e of object.values) {
message.values.push(AnyValue.fromPartial(e));
}
}
return message;
},
};
const baseKeyValueList: object = {};
export const KeyValueList = {
encode(message: KeyValueList, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
for (const v of message.values) {
KeyValue.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): KeyValueList {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseKeyValueList } as KeyValueList;
message.values = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.values.push(KeyValue.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): KeyValueList {
const message = { ...baseKeyValueList } as KeyValueList;
message.values = [];
if (object.values !== undefined && object.values !== null) {
for (const e of object.values) {
message.values.push(KeyValue.fromJSON(e));
}
}
return message;
},
toJSON(message: KeyValueList): unknown {
const obj: any = {};
if (message.values) {
obj.values = message.values.map((e) => (e ? KeyValue.toJSON(e) : undefined));
} else {
obj.values = [];
}
return obj;
},
fromPartial(object: DeepPartial<KeyValueList>): KeyValueList {
const message = { ...baseKeyValueList } as KeyValueList;
message.values = [];
if (object.values !== undefined && object.values !== null) {
for (const e of object.values) {
message.values.push(KeyValue.fromPartial(e));
}
}
return message;
},
};
const baseKeyValue: object = { key: '' };
export const KeyValue = {
encode(message: KeyValue, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.key !== '') {
writer.uint32(10).string(message.key);
}
if (message.value !== undefined) {
AnyValue.encode(message.value, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): KeyValue {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseKeyValue } as KeyValue;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = AnyValue.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): KeyValue {
const message = { ...baseKeyValue } as KeyValue;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = '';
}
if (object.value !== undefined && object.value !== null) {
message.value = AnyValue.fromJSON(object.value);
} else {
message.value = undefined;
}
return message;
},
toJSON(message: KeyValue): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined && (obj.value = message.value ? AnyValue.toJSON(message.value) : undefined);
return obj;
},
fromPartial(object: DeepPartial<KeyValue>): KeyValue {
const message = { ...baseKeyValue } as KeyValue;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = '';
}
if (object.value !== undefined && object.value !== null) {
message.value = AnyValue.fromPartial(object.value);
} else {
message.value = undefined;
}
return message;
},
};
const baseStringKeyValue: object = { key: '', value: '' };
export const StringKeyValue = {
encode(message: StringKeyValue, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.key !== '') {
writer.uint32(10).string(message.key);
}
if (message.value !== '') {
writer.uint32(18).string(message.value);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): StringKeyValue {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseStringKeyValue } as StringKeyValue;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): StringKeyValue {
const message = { ...baseStringKeyValue } as StringKeyValue;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = '';
}
if (object.value !== undefined && object.value !== null) {
message.value = String(object.value);
} else {
message.value = '';
}
return message;
},
toJSON(message: StringKeyValue): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined && (obj.value = message.value);
return obj;
},
fromPartial(object: DeepPartial<StringKeyValue>): StringKeyValue {
const message = { ...baseStringKeyValue } as StringKeyValue;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = '';
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
} else {
message.value = '';
}
return message;
},
};
const baseInstrumentationLibrary: object = { name: '', version: '' };
export const InstrumentationLibrary = {
encode(message: InstrumentationLibrary, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.name !== '') {
writer.uint32(10).string(message.name);
}
if (message.version !== '') {
writer.uint32(18).string(message.version);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): InstrumentationLibrary {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseInstrumentationLibrary } as InstrumentationLibrary;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.name = reader.string();
break;
case 2:
message.version = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): InstrumentationLibrary {
const message = { ...baseInstrumentationLibrary } as InstrumentationLibrary;
if (object.name !== undefined && object.name !== null) {
message.name = String(object.name);
} else {
message.name = '';
}
if (object.version !== undefined && object.version !== null) {
message.version = String(object.version);
} else {
message.version = '';
}
return message;
},
toJSON(message: InstrumentationLibrary): unknown {
const obj: any = {};
message.name !== undefined && (obj.name = message.name);
message.version !== undefined && (obj.version = message.version);
return obj;
},
fromPartial(object: DeepPartial<InstrumentationLibrary>): InstrumentationLibrary {
const message = { ...baseInstrumentationLibrary } as InstrumentationLibrary;
if (object.name !== undefined && object.name !== null) {
message.name = object.name;
} else {
message.name = '';
}
if (object.version !== undefined && object.version !== null) {
message.version = object.version;
} else {
message.version = '';
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
if (typeof global !== 'undefined') return global;
throw 'Unable to locate global object';
})();
type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error('Value is larger than Number.MAX_SAFE_INTEGER');
}
return long.toNumber();
}
if (_m0.util.Long !== Long) {
_m0.util.Long = Long as any;
_m0.configure();
} | the_stack |
import { INode, IConnector, Layout, Bounds } from './layout-base';
import { PointModel } from '../primitives/point-model';
import { Connector } from '../objects/connector';
import { LineDistribution, MatrixCellGroupObject } from '../interaction/line-distribution';
import { LayoutOrientation } from '../enum/enum';
/**
* Connects diagram objects with layout algorithm
*/
export class ComplexHierarchicalTree {
/**
* Constructor for the hierarchical tree layout module
*
* @private
*/
constructor() {
//constructs the layout module
}
/**
* To destroy the hierarchical tree module
*
* @returns {void}
* @private
*/
public destroy(): void {
/**
* Destroy method performed here
*/
}
/**
* Core method to return the component name.
*
* @returns {string} Core method to return the component name.
* @private
*/
protected getModuleName(): string {
/**
* Returns the module name of the layout
*
*/
return 'ComplexHierarchicalTree';
}
/**
* doLayout method\
*
* @returns { void } doLayout method .\
* @param {INode[]} nodes - provide the nodes value.
* @param {{}} nameTable - provide the nameTable value.
* @param {Layout} layout - provide the layout value.
* @param {PointModel} viewPort - provide the viewPort value.
* @param {LineDistribution} lineDistribution - provide the lineDistribution value.
* @private
*/
public doLayout(nodes: INode[], nameTable: {}, layout: Layout, viewPort: PointModel, lineDistribution: LineDistribution): void {
new HierarchicalLayoutUtil().doLayout(nodes, nameTable, layout, viewPort, lineDistribution);
}
public getLayoutNodesCollection(nodes: INode[]): INode[] {
const nodesCollection: INode[] = []; let node: INode;
const parentId: string = 'parentId';
const processId: string = 'processId';
for (let i: number = 0; i < nodes.length; i++) {
node = nodes[i];
if ((node.inEdges.length + node.outEdges.length > 0) && !node[parentId] && !node[processId]) {
nodesCollection.push(node);
}
}
return nodesCollection;
}
}
/**
* Utility that arranges the nodes in hierarchical structure
*/
class HierarchicalLayoutUtil {
private nameTable: Object = {};
/**
* Holds the collection vertices, that are equivalent to nodes to be arranged
*/
private vertices: Vertex[];
private crossReduction: CrossReduction = new CrossReduction();
/**
* The preferred vertical offset between edges exiting a vertex Default is 2.
*/
private previousEdgeOffset: number = 6;
/**
* The preferred horizontal distance between edges exiting a vertex Default is 5.
*/
private previousEdgeDistance: number = 5;
/**
* Holds the collection vertices, that are equivalent to nodes to be arranged
*/
private jettyPositions: object = {};
/**
* Internal cache of bottom-most value of Y for each rank
*/
private rankBottomY: number[] = null;
/**
* Internal cache of bottom-most value of X for each rank
*/
private limitX: number = null;
/**
* Internal cache of top-most values of Y for each rank
*/
private rankTopY: number[] = null;
/**
* The minimum parallelEdgeSpacing value is 12.
*/
private parallelEdgeSpacing: number = 10;
/**
* The minimum distance for an edge jetty from a vertex Default is 12.
*/
private minEdgeJetty: number = 12;
//Defines a vertex that is equivalent to a node object
private createVertex(node: INode, value: string, x: number, y: number, width: number, height: number): Vertex {
const geometry: Rect = { x: x, y: y, width: width, height: height };
const vertex: Vertex = {
value: value, geometry: geometry, name: value, vertex: true,
inEdges: node.inEdges.slice(), outEdges: node.outEdges.slice()
};
return vertex;
}
/**
* Initializes the edges collection of the vertices\
*
* @returns { IConnector[] } Initializes the edges collection of the vertices\
* @param {Vertex} node - provide the node value.
* @private
*/
public getEdges(node: Vertex): IConnector[] {
const edges: IConnector[] = [];
if (node) {
for (let i: number = 0; node.inEdges.length > 0 && i < node.inEdges.length; i++) {
edges.push(this.nameTable[node.inEdges[i]]);
}
for (let i: number = 0; node.outEdges.length > 0 && i < node.outEdges.length; i++) {
edges.push(this.nameTable[node.outEdges[i]]);
}
}
return edges;
}
//Finds the root nodes of the layout
private findRoots(vertices: {}): Vertex[] {
const roots: Vertex[] = [];
let best: Vertex = null;
let maxDiff: number = -100000;
for (const i of Object.keys(vertices)) {
const cell: Vertex = vertices[i];
const conns: IConnector[] = this.getEdges(cell);
let outEdges: number = 0;
let inEdges: number = 0;
for (let k: number = 0; k < conns.length; k++) {
const src: Vertex = this.getVisibleTerminal(conns[k], true);
if (src.name === cell.name) {
outEdges++;
} else {
inEdges++;
}
}
if (inEdges === 0 && outEdges > 0) {
roots.push(cell);
}
const diff: number = outEdges - inEdges;
if (diff > maxDiff) {
maxDiff = diff;
best = cell;
}
}
if (roots.length === 0 && best != null) {
roots.push(best);
}
return roots;
}
/**
* Returns the source/target vertex of the given connector \
*
* @returns { Vertex } Returns the source/target vertex of the given connector \
* @param {IConnector} edge - provide the node value.
* @param {boolean} source - provide the node value.
* @private
*/
public getVisibleTerminal(edge: IConnector, source: boolean): Vertex {
let terminalCache: INode = this.nameTable[edge.targetID];
if (source) {
terminalCache = this.nameTable[edge.sourceID];
}
for (let i: number = 0; i < this.vertices.length; i++) {
if (this.vertices[i].name === terminalCache.id) {
return this.vertices[i];
}
}
return null;
}
/**
* Traverses each sub tree, ensures there is no cycle in traversing \
*
* @returns { {} } Traverses each sub tree, ensures there is no cycle in traversing .\
* @param {Vertex} vertex - provide the vertex value.
* @param {boolean} directed - provide the directed value.
* @param {IConnector} edge - provide the edge value.
* @param {{}} currentComp - provide the currentComp value.
* @param {{}[]} hierarchyVertices - provide the hierarchyVertices value.
* @param {{}} filledVertices - provide the filledVertices value.
* @private
*/
public traverse(vertex: Vertex, directed: boolean, edge: IConnector, currentComp: {}, hierarchyVertices: {}[], filledVertices: {}): {} {
if (vertex != null) {
const vertexID: string = vertex.name;
if ((filledVertices == null ? true : filledVertices[vertexID] != null)) {
if (currentComp[vertexID] == null) {
currentComp[vertexID] = vertex;
}
if (filledVertices != null) {
delete filledVertices[vertexID];
}
const edges: IConnector[] = this.getEdges(vertex);
const edgeIsSource: boolean[] = [];
for (let i: number = 0; i < edges.length; i++) {
edgeIsSource[i] = this.getVisibleTerminal(edges[i], true) === vertex;
}
for (let i: number = 0; i < edges.length; i++) {
if (!directed || edgeIsSource[i]) {
const next: Vertex = this.getVisibleTerminal(edges[i], !edgeIsSource[i]);
let netCount: number = 1;
for (let j: number = 0; j < edges.length; j++) {
if (j === i) {
continue;
} else {
const isSource2: boolean = edgeIsSource[j];
const otherTerm: Vertex = this.getVisibleTerminal(edges[j], !isSource2);
if (otherTerm === next) {
if (isSource2) {
netCount++;
} else {
netCount--;
}
}
}
}
if (netCount >= 0) {
currentComp = this.traverse(next, directed, edges[i], currentComp, hierarchyVertices, filledVertices);
}
}
}
} else {
if (currentComp[vertexID] == null) {
// We've seen this vertex before, but not in the current component This component and the one it's in need to be merged
for (let i: number = 0; i < hierarchyVertices.length; i++) {
const comp: {} = hierarchyVertices[i];
if (comp[vertexID] != null) {
for (const key of Object.keys(comp)) {
currentComp[key] = comp[key];
}
// Remove the current component from the hierarchy set
hierarchyVertices.splice(i, 1);
return currentComp;
}
}
}
}
}
return currentComp;
}
//Returns the bounds of the given vertices
private getModelBounds(nodes: Vertex[]): Rect {
nodes = nodes.slice();
let rect: Rect = null; let rect1: Rect = null;
for (let i: number = 0; i < nodes.length; i++) {
rect = nodes[i].geometry;
if (rect1) {
const right: number = Math.max(rect1.x + rect1.width, rect.x + rect.width);
const bottom: number = Math.max(rect1.y + rect1.height, rect.y + rect.height);
rect1.x = Math.min(rect1.x, rect.x);
rect1.y = Math.min(rect1.y, rect.y);
rect1.width = right - rect1.x;
rect1.height = bottom - rect1.y;
} else {
rect1 = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
}
}
return rect1;
}
/* tslint:disable */
/**
* Initializes the layouting process \
*
* @returns { Vertex } Initializes the layouting process \
* @param {INode[]} nodes - provide the node value.
* @param {{}} nameTable - provide the nameTable value.
* @param {Layout} layoutProp - provide the layoutProp value.
* @param {PointModel} viewPort - provide the viewPort value.
* @param {LineDistribution} lineDistribution - provide the lineDistribution value.
* @private
*/
public doLayout(nodes: INode[], nameTable: {}, layoutProp: Layout, viewPort: PointModel, lineDistribution: LineDistribution): void {
this.nameTable = nameTable;
const canEnableRouting: boolean = layoutProp.enableRouting;
const layout: LayoutProp = {
horizontalSpacing: layoutProp.horizontalSpacing, verticalSpacing: layoutProp.verticalSpacing,
orientation: layoutProp.orientation, marginX: layoutProp.margin.left, marginY: layoutProp.margin.top,
enableLayoutRouting: canEnableRouting
};
let model: MultiParentModel;
if (lineDistribution) {
lineDistribution.edgeMapper = [];
}
const nodeWithMultiEdges: INode[] = [];
this.vertices = [];
const filledVertexSet: {} = {};
for (let i: number = 0; i < nodes.length; i++) {
const node: Vertex = this.createVertex(nodes[i], nodes[i].id, 0, 0, nodes[i].actualSize.width, nodes[i].actualSize.height);
this.vertices.push(node);
if ((nodes[i] as INode).inEdges.length > 0 || (nodes[i] as INode).outEdges.length > 0) {
nodeWithMultiEdges.push((nodes[i] as INode));
}
filledVertexSet[node.name] = node;
if (lineDistribution) {
const outEdges: string[] = nodes[i].outEdges.slice();
for (let j: number = 0; j < outEdges.length; j++) {
const outEdge: Connector = nameTable[outEdges[j]];
lineDistribution.setEdgeMapper({ key: outEdge, value: [] });
}
}
}
const hierarchyVertices: {}[] = [];
//let candidateRoots: Vertex[];
const candidateRoots: Vertex[] = this.findRoots(filledVertexSet);
for (let i: number = 0; i < candidateRoots.length; i++) {
const vertexSet: {} = {};
hierarchyVertices.push(vertexSet);
this.traverse(candidateRoots[i], true, null, vertexSet, hierarchyVertices, filledVertexSet);
}
let limit: Margin = { marginX: 0, marginY: 0 };
let tmp: Vertex[] = [];
let checkLinear: boolean = false;
let matrixModel: MatrixModelObject;
for (let i: number = 0; i < hierarchyVertices.length; i++) {
const vertexSet: {} = hierarchyVertices[i];
// eslint-disable-next-line
for (const key of Object.keys(vertexSet)) {
tmp.push(vertexSet[key]);
}
if ((layoutProp.arrangement === 'Linear' && i === hierarchyVertices.length - 1) || canEnableRouting) {
checkLinear = true;
}
model = new MultiParentModel(this, tmp, candidateRoots, layout);
this.cycleStage(model);
this.layeringStage(model);
if ((lineDistribution && layoutProp.connectionPointOrigin === 'DifferentPoint') || checkLinear) {
matrixModel = this.matrixModel({ model: model, matrix: [], rowOffset: [] });
lineDistribution.arrangeElements(matrixModel, layoutProp);
} else {
if (layoutProp.arrangement === 'Nonlinear') {
this.crossingStage(model);
limit = this.placementStage(model, limit.marginX, limit.marginY);
tmp = [];
}
}
}
const modelBounds: Rect = this.getModelBounds(this.vertices);
this.updateMargin(layoutProp, layout, modelBounds, viewPort);
for (let i: number = 0; i < this.vertices.length; i++) {
const clnode: Vertex = this.vertices[i];
if (clnode) {//Check what is node.source/node.target - && !clnode.source && !clnode.target) {
const dnode: INode = this.nameTable[clnode.name];
dnode.offsetX = 0;
dnode.offsetY = 0;
//initialize layout
const dx: number = (clnode.geometry.x - (dnode.offsetX - (dnode.actualSize.width / 2))) + layout.marginX;
const dy: number = (clnode.geometry.y - (dnode.offsetY - (dnode.actualSize.height / 2))) + layout.marginY;
let x: number = dx; let y: number = dy;
if (layout.orientation === 'BottomToTop') {
if (canEnableRouting) {
clnode.geometry.y = modelBounds.height - dy - dnode.actualSize.height / 2;
}
y = modelBounds.height - dy;
} else if (layout.orientation === 'RightToLeft') {
x = modelBounds.width - dx;
}
dnode.offsetX += x - dnode.offsetX;
dnode.offsetY += y - dnode.offsetY;
}
}
if (!checkLinear) {
for (let i: number = 0; i < this.vertices.length; i++) {
this.isNodeOverLap(this.nameTable[this.vertices[i].name], layoutProp);
}
}
if ((lineDistribution && layoutProp.connectionPointOrigin === 'DifferentPoint') || canEnableRouting) {
lineDistribution.updateLayout(viewPort, modelBounds, layoutProp, layout, nodeWithMultiEdges, nameTable);
}
if (canEnableRouting) {
const vertices: object = {};
let matrixrow1: MatrixCellGroupObject[];
for (let p: number = 0; p < matrixModel.matrix.length; p++) {
matrixrow1 = matrixModel.matrix[p].value;
for (let q: number = 0; q < matrixrow1.length; q++) {
const matrixCell: MatrixCellGroupObject = matrixrow1[q];
for (let r: number = 0; r < (matrixCell.cells as MatrixCellGroupObject[]).length; r++) {
const cell: IVertex = matrixCell.cells[r];
const type: string = this.getType(cell.type);
if (type === 'internalVertex') {
const internalVertex: IVertex = cell;
vertices[internalVertex.id] = internalVertex;
}
}
}
}
this.updateRankValuess(model);
for (let i: number = 0, a: string[] = Object.keys(vertices); i < a.length; i++) {
const key: string = a[i];
this.setVertexLocationValue(vertices[key], layoutProp.orientation, modelBounds);
}
this.localEdgeProcessing(model, vertices);
this.assignRankOffset(model);
this.updateEdgeSetXYValue(model);
const edges: IEdge[] = this.getValues(model.edgeMapper);
for (let i: number = 0; i < edges.length; i++) {
if ((edges[i]).x.length > 0) {
for (let j: number = 0; j < (edges[i]).x.length; j++) {
if (layoutProp.orientation !== 'RightToLeft' && layoutProp.orientation !== 'LeftToRight') {
(edges[i]).x[j] = (edges[i]).x[j] + layout.marginX;
} else if (layoutProp.orientation === 'LeftToRight') {
(edges[i]).x[j] = (edges[i]).x[j] + layoutProp.verticalSpacing / 2;
} else {
(edges[i]).x[j] = (edges[i]).x[j] + layoutProp.verticalSpacing / 2;
}
}
}
this.setEdgePosition(edges[i], model, layout);
}
for (let p: number = 0; p < this.vertices.length; p++) {
const clnode: Vertex = this.vertices[p];
if (clnode.outEdges.length > 1) {
this.updateMultiOutEdgesPoints(clnode);
}
}
}
}
private setEdgeXY(ranks: IVertex[][], node: IVertex, spacing: number, layer: number): void {
if (ranks && node.source.id) {
let targetValue: number;
let sourceValue: number;
for (let i: number = 0; i < ranks.length; i++) {
for (let k: number = 0; k < ranks[i].length; k++) {
if (ranks[i][k].id === node.target.id || ranks[i][k].id === node.source.id) {
if (ranks[i][k].id === node.target.id && targetValue === undefined) {
targetValue = i;
}
if (ranks[i][k].id === node.source.id && sourceValue === undefined) {
sourceValue = i;
}
}
}
}
let rankOffsetValue: number;
for (let m: number = targetValue; m <= sourceValue; m++) {
if (rankOffsetValue === undefined) {
rankOffsetValue = this[m + '_RankOffset'];
}
if (rankOffsetValue !== undefined && rankOffsetValue < this[m + '_RankOffset']) {
rankOffsetValue = this[m + '_RankOffset'];
}
}
if (this['edges'] === undefined) {
this['edges'] = {};
}
this['edges'][(node).ids[0]] = { x: node.x, y: 0 };
const value: number = this.resetOffsetXValue(rankOffsetValue, spacing / 10);
node.x[layer - node.minRank - 1] = value;
for (let k: number = 0; k < (node).edges.length; k++) {
(node).edges[k]['levelSkip'] = true;
}
}
}
private resetOffsetXValue(value: number, spacing: number): number {
for (let i: number = 0, a: string[] = Object.keys(this['edges']); i < a.length; i++) {
const key: string = a[i];
const length: number[] = this['edges'][key].x;
for (let j: number = 0; j < length.length; j++) {
let offsetValue: number;
if (this['edges'][key].x[j] === value) {
offsetValue = value + spacing;
offsetValue = this.resetOffsetXValue(offsetValue, spacing);
return offsetValue;
}
}
}
return value;
}
private setEdgePosition(cell: IEdge, model: MultiParentModel, layout: LayoutProp): void {
// For parallel edges we need to seperate out the points a
// little
let offsetX: number = 0;
// Only set the edge control points once
if (cell.temp[0] !== 101207) {
if (cell.maxRank === undefined) {
cell.maxRank = -1;
}
if (cell.minRank === undefined) {
cell.minRank = -1;
}
let maxRank: number = cell.maxRank;
let minRank: number = cell.minRank;
if (maxRank === minRank) {
maxRank = cell.source.maxRank;
minRank = cell.target.minRank;
}
let parallelEdgeCount: number = 0;
const jettys: object = this.jettyPositions[cell.ids[0]];
if (cell.isReversed === undefined) {
cell.isReversed = false;
} else {
cell.isReversed = true;
}
const source: Vertex = cell.isReversed ? cell.target.cell : cell.source.cell;
let layoutReversed: boolean = false;
if (model.layout.orientation === 'TopToBottom' || model.layout.orientation === 'LeftToRight') {
if (model.layout.orientation === 'TopToBottom') {
layoutReversed = false;
}
if (model.layout.orientation === 'LeftToRight') {
if (!cell.isReversed) {
layoutReversed = false;
} else {
layoutReversed = false;
}
}
} else {
if (!cell.isReversed) {
layoutReversed = true;
}
}
for (let i: number = 0; i < cell.edges.length; i++) {
const realEdge: IConnector = cell.edges[i];
const realSource: Vertex = this.getVisibleTerminal(realEdge, true);
//List oldPoints = graph.getPoints(realEdge);
const newPoints: PointModel[] = [];
// Single length reversed edges end up with the jettys in the wrong
// places. Since single length edges only have jettys, not segment
// control points, we just say the edge isn't reversed in this section
let reversed: boolean = cell.isReversed;
// if(cell.isReversed===undefined){
// reversed = false
// }else{
// reversed =cell.isReversed
// }
if (realSource !== source) {
// The real edges include all core model edges and these can go
// in both directions. If the source of the hierarchical model edge
// isn't the source of the specific real edge in this iteration
// treat if as reversed
reversed = !reversed;
}
// First jetty of edge
if (jettys != null) {
const arrayOffset: number = reversed ? 2 : 0;
let y: number = reversed ?
(layoutReversed ? this.rankBottomY[minRank] : this.rankTopY[minRank]) :
(layoutReversed ? this.rankTopY[maxRank] : this.rankBottomY[maxRank]);
let jetty: number = jettys[parallelEdgeCount * 4 + 1 + arrayOffset];
if (reversed !== layoutReversed) {
jetty = -jetty;
}
if (layout.orientation === 'TopToBottom' || layout.orientation === 'BottomToTop') {
y += jetty;
}
const x: number = jettys[parallelEdgeCount * 4 + arrayOffset];
if (layout.orientation === 'TopToBottom' || layout.orientation === 'BottomToTop') {
newPoints.push(this.getPointvalue(x, y + layout.marginY));
} else {
if (layout.orientation === 'LeftToRight') {
newPoints.push(this.getPointvalue(y + jetty, x + layout.marginY));
} else {
newPoints.push(this.getPointvalue(y, x + layout.marginY));
}
}
}
let loopStart: number = cell.x.length - 1;
let loopLimit: number = -1;
let loopDelta: number = -1;
let currentRank: number = cell.maxRank - 1;
if (reversed) {
loopStart = 0;
loopLimit = cell.x.length;
loopDelta = 1;
currentRank = cell.minRank + 1;
}
// Reversed edges need the points inserted in
// reverse order
for (let j: number = loopStart; (cell.maxRank !== cell.minRank) && j !== loopLimit; j += loopDelta) {
// The horizontal position in a vertical layout
const positionX: number = cell.x[j] + offsetX;
// This cell.x determines the deviated points of the connectors and jetty positions
//determine the src and targetgeo points .
// Work out the vertical positions in a vertical layout
// in the edge buffer channels above and below this rank
let topChannelY: number = (this.rankTopY[currentRank] + this.rankBottomY[currentRank + 1]) / 2.0;
let bottomChannelY: number = (this.rankTopY[currentRank - 1] + this.rankBottomY[currentRank]) / 2.0;
if (reversed) {
const tmp: number = topChannelY;
topChannelY = bottomChannelY;
bottomChannelY = tmp;
}
if (layout.orientation === 'TopToBottom' || layout.orientation === 'BottomToTop') {
newPoints.push(this.getPointvalue(positionX, topChannelY + layout.marginY));
newPoints.push(this.getPointvalue(positionX, bottomChannelY + layout.marginY));
} else {
newPoints.push(this.getPointvalue(topChannelY, positionX + layout.marginY));
newPoints.push(this.getPointvalue(bottomChannelY, positionX + layout.marginY));
}
this.limitX = Math.max(this.limitX, positionX);
currentRank += loopDelta;
}
// Second jetty of edge
if (jettys != null) {
const arrayOffset: number = reversed ? 2 : 0;
const rankY: number = reversed ?
(layoutReversed ? this.rankTopY[maxRank] : this.rankBottomY[maxRank]) :
(layoutReversed ? this.rankBottomY[minRank] : this.rankTopY[minRank]);
let jetty: number = jettys[parallelEdgeCount * 4 + 3 - arrayOffset];
if (reversed !== layoutReversed) {
jetty = -jetty;
}
const y: number = rankY - jetty;
const x: number = jettys[parallelEdgeCount * 4 + 2 - arrayOffset];
if (layout.orientation === 'TopToBottom' || layout.orientation === 'BottomToTop') {
newPoints.push(this.getPointvalue(x, y + layout.marginY));
} else {
newPoints.push(this.getPointvalue(y, x + layout.marginY));
}
}
this.setEdgePoints(realEdge, newPoints, model);
// Increase offset so next edge is drawn next to
// this one
if (offsetX === 0.0) {
offsetX = this.parallelEdgeSpacing;
} else if (offsetX > 0) {
offsetX = -offsetX;
} else {
offsetX = -offsetX + this.parallelEdgeSpacing;
}
parallelEdgeCount++;
}
cell.temp[0] = 101207;
}
}
/* tslint:enable */
// eslint-disable-next-line
private getPointvalue(x: number, y: number): object {
return { 'x': Number(x) || 0, 'y': Number(y) || 0 };
}
private updateEdgeSetXYValue(model: MultiParentModel): void {
if (model.layout.enableLayoutRouting) {
let isHorizontal: boolean = false;
if (model.layout.orientation === 'LeftToRight' || model.layout.orientation === 'RightToLeft') {
isHorizontal = true;
}
for (let i: number = 0; i < model.ranks.length; i++) {
const rank: IVertex[] = model.ranks[i];
for (let k: number = 0; k < rank.length; k++) {
const cell: IVertex = rank[k];
if ((cell).edges && (cell).edges.length > 0) {
const spacing: number = model.layout.horizontalSpacing > 0 ? (model.layout.horizontalSpacing / 2) : 15;
let check: boolean = true;
if (!(cell.minRank === i - 1 || cell.maxRank === i - 1)) {
check = false;
}
if (check) {
this.setXY(cell, i, undefined, isHorizontal ? true : false, model.ranks, spacing);
}
}
}
}
}
}
private getPreviousLayerConnectedCells(layer: number, cell: IEdge): IVertex[] {
if (cell.previousLayerConnectedCells == null) {
cell.previousLayerConnectedCells = [];
cell.previousLayerConnectedCells[0] = [];
for (let i: number = 0; i < (cell as IVertex).connectsAsSource.length; i++) {
const edge: IEdge = (cell as IVertex).connectsAsSource[i];
if (edge.minRank === -1 || edge.minRank === layer - 1) {
// No dummy nodes in edge, add node of other side of edge
cell.previousLayerConnectedCells[0].push(edge.target);
} else {
// Edge spans at least two layers, add edge
cell.previousLayerConnectedCells[0].push(edge);
}
}
}
return cell.previousLayerConnectedCells[0];
}
private compare(a: WeightedCellSorter, b: WeightedCellSorter): number {
if (a != null && b != null) {
if (b.weightedValue > a.weightedValue) {
return -1;
} else if (b.weightedValue < a.weightedValue) {
return 1;
}
}
return 0;
}
/* tslint:disable */
// eslint-disable-next-line
private localEdgeProcessing(model: MultiParentModel, vertices: object): void {
// Iterate through each vertex, look at the edges connected in
// both directions.
for (let rankIndex: number = 0; rankIndex < model.ranks.length; rankIndex++) {
const rank: IVertex[] = model.ranks[rankIndex];
for (let cellIndex: number = 0; cellIndex < rank.length; cellIndex++) {
const cell: IVertex = rank[cellIndex];
if (this.crossReduction.isVertex(cell)) {
let currentCells: IVertex[] = this.getPreviousLayerConnectedCells(rankIndex, cell);
let currentRank: number = rankIndex - 1;
// Two loops, last connected cells, and next
for (let k: number = 0; k < 2; k++) {
if (currentRank > -1
&& currentRank < model.ranks.length
&& currentCells != null
&& currentCells.length > 0) {
const sortedCells: WeightedCellSorter[] = [];
for (let j: number = 0; j < currentCells.length; j++) {
const sorter: WeightedCellSorter = this.weightedCellSorter(
currentCells[j], this.getX(currentRank, currentCells[j]));
sortedCells.push(sorter);
}
sortedCells.sort(this.compare);
cell.width = vertices[cell.id].cell.geometry.width;
cell.height = vertices[cell.id].cell.geometry.height;
let leftLimit: number;
if (model.layout.orientation === 'TopToBottom' || model.layout.orientation === 'BottomToTop') {
cell.x[0] = vertices[cell.id].cell.geometry.x + vertices[cell.id].cell.geometry.width / 2;
leftLimit = cell.x[0] - cell.width / 2 + vertices[cell.id].cell.geometry.height / 2;
} else {
cell.x[0] = vertices[cell.id].cell.geometry.y;
leftLimit = cell.x[0];
}
let rightLimit: number = leftLimit + cell.width;
// Connected edge count starts at 1 to allow for buffer
// with edge of vertex
let connectedEdgeCount: number = 0;
let connectedEdgeGroupCount: number = 0;
const connectedEdges: IVertex[] = [];
// Calculate width requirements for all connected edges
for (let j: number = 0; j < sortedCells.length; j++) {
const innerCell: IVertex = sortedCells[j].cell;
let connections: IEdge[];
if (this.crossReduction.isVertex(innerCell)) {
// Get the connecting edge
if (k === 0) {
connections = cell.connectsAsSource;
} else {
connections = cell.connectsAsTarget;
}
for (let connIndex: number = 0; connIndex < connections.length; connIndex++) {
if (connections[connIndex].source === innerCell
|| connections[connIndex].target === innerCell) {
connectedEdgeCount += connections[connIndex].edges
.length;
connectedEdgeGroupCount++;
connectedEdges.push(connections[connIndex]);
}
}
} else {
connectedEdgeCount += innerCell.edges.length;
// eslint-disable-next-line
connectedEdgeGroupCount++;
connectedEdges.push(innerCell);
}
}
const requiredWidth: number = (connectedEdgeCount + 1)
* this.previousEdgeDistance;
// Add a buffer on the edges of the vertex if the edge count allows
if (cell.width > requiredWidth
+ (2 * this.previousEdgeDistance)) {
leftLimit += this.previousEdgeDistance;
rightLimit -= this.previousEdgeDistance;
}
const availableWidth: number = rightLimit - leftLimit;
const edgeSpacing: number = availableWidth / connectedEdgeCount;
let currentX: number = leftLimit + edgeSpacing / 2.0;
let currentYOffset: number = this.minEdgeJetty - this.previousEdgeOffset;
let maxYOffset: number = 0;
for (let j: number = 0; j < connectedEdges.length; j++) {
const numActualEdges: number = connectedEdges[j].edges
.length;
if (this.jettyPositions === undefined) {
this.jettyPositions = {};
}
let pos: object = this.jettyPositions[connectedEdges[j].ids[0]];
if (pos == null) {
pos = [];
this.jettyPositions[(connectedEdges[j] as IVertex).ids[0]] = pos;
}
if (j < connectedEdgeCount / 2) {
currentYOffset += this.previousEdgeOffset;
} else if (j > connectedEdgeCount / 2) {
currentYOffset -= this.previousEdgeOffset;
}
// Ignore the case if equals, this means the second of 2
// jettys with the same y (even number of edges)
for (let m: number = 0; m < numActualEdges; m++) {
pos[m * 4 + k * 2] = currentX;
currentX += edgeSpacing;
pos[m * 4 + k * 2 + 1] = currentYOffset;
}
maxYOffset = Math.max(maxYOffset, currentYOffset);
}
}
currentCells = this.getNextLayerConnectedCells(rankIndex, cell);
currentRank = rankIndex + 1;
}
}
}
}
}
/* tslint:enable */
private updateMultiOutEdgesPoints(clnode: Vertex): void {
for (let i: number = 0; i < clnode.outEdges.length / 2; i++) {
const connector1: Connector = this.nameTable[clnode.outEdges[i]];
const connector2: Connector = this.nameTable[clnode.outEdges[clnode.outEdges.length - (i + 1)]];
const geometry: string = 'geometry';
connector2[geometry].points[0].y = connector1[geometry].points[0].y;
}
}
private getNextLayerConnectedCells(layer: number, cell: IEdge): IVertex[] {
if (cell.nextLayerConnectedCells == null) {
cell.nextLayerConnectedCells = [];
cell.nextLayerConnectedCells[0] = [];
for (let i: number = 0; i < (cell as IVertex).connectsAsTarget.length; i++) {
const edge: IEdge = (cell as IVertex).connectsAsTarget[i];
if (edge.maxRank === -1 || edge.maxRank === layer + 1) {
// Either edge is not in any rank or
// no dummy nodes in edge, add node of other side of edge
cell.nextLayerConnectedCells[0].push(edge.source);
} else {
// Edge spans at least two layers, add edge
cell.nextLayerConnectedCells[0].push(edge);
}
}
}
return cell.nextLayerConnectedCells[0];
}
private getX(layer: number, cell: IVertex): number {
if (this.crossReduction.isVertex(cell)) {
return cell.x[0];
} else if (!this.crossReduction.isVertex(cell)) {
return cell.x[layer - cell.minRank - 1] || cell.temp[layer - cell.minRank - 1];
}
return 0.0;
}
private getGeometry(edge: IConnector): Geometry {
const geometry: string = 'geometry';
return edge[geometry];
}
private setEdgePoints(edge: IConnector, points: PointModel[], model: MultiParentModel): void {
if (edge != null) {
const geometryValue: string = 'geometry';
const geometry: Geometry = this.getGeometry(edge);
if (points != null) {
for (let i: number = 0; i < points.length; i++) {
// eslint-disable-next-line
points[i].x = points[i].x;
// eslint-disable-next-line
points[i].y = points[i].y;
}
}
(geometry as Geometry).points = points;
edge[geometryValue] = geometry;
}
}
private assignRankOffset(model: MultiParentModel): void {
if (model) {
for (let i: number = 0; i < model.ranks.length; i++) {
this.rankCoordinatesAssigment(i, model);
}
}
}
private rankCoordinatesAssigment(rankValue: number, model: MultiParentModel): void {
const rank: IVertex[] = model.ranks[rankValue];
const spacing: number = model.layout.horizontalSpacing;
let localOffset: number;
for (let i: number = 0; i < rank.length; i++) {
if (this[rankValue + '_' + 'RankOffset'] === undefined) {
this[rankValue + '_' + 'RankOffset'] = 0;
}
localOffset = rank[i].x[0];
if (this[rankValue + '_' + 'RankOffset'] < localOffset) {
this[rankValue + '_' + 'RankOffset'] = localOffset + rank[i].width / 2 + spacing;
}
}
}
private getType(type: string): string {
if (type === 'internalVertex') {
return 'internalVertex';
} else {
return 'internalEdge';
}
}
private updateRankValuess(model: MultiParentModel): void {
this.rankTopY = [];
this.rankBottomY = [];
for (let i: number = 0; i < model.ranks.length; i++) {
this.rankTopY[i] = Number.MAX_VALUE;
this.rankBottomY[i] = -Number.MAX_VALUE;
}
}
private setVertexLocationValue(cell: IVertex, orientation: LayoutOrientation, modelBounds: Rect): void {
const cellGeomtry: Rect = cell.cell.geometry;
let positionX: number;
let positionY: number;
if (orientation === 'TopToBottom' || orientation === 'BottomToTop') {
positionX = cellGeomtry.x;
positionY = cellGeomtry.y;
} else {
positionX = cellGeomtry.y;
positionY = cellGeomtry.x;
}
if (orientation === 'RightToLeft') {
// eslint-disable-next-line
positionX = cellGeomtry.y;
positionY = modelBounds.width - cellGeomtry.x - cellGeomtry.height;
this.rankBottomY[cell.minRank] = Math.max(this.rankBottomY[cell.minRank], positionY);
this.rankTopY[cell.minRank] = Math.min(this.rankTopY[cell.minRank], positionY + cellGeomtry.height);
} else {
this.rankTopY[cell.minRank] = Math.min(this.rankTopY[cell.minRank], positionY);
this.rankBottomY[cell.minRank] = Math.max(this.rankBottomY[cell.minRank], positionY + cellGeomtry.height);
}
}
private matrixModel(options: MatrixModelObject): MatrixModelObject {
// eslint-disable-next-line
options.model = options.model;
options.matrix = options.matrix || [];
options.rowOffset = options.rowOffset || [];
return options;
}
private calculateRectValue(dnode: INode): Rect {
const rect: Rect = { x: 0, y: 0, right: 0, bottom: 0, height: 0, width: 0 };
rect.x = dnode.offsetX - dnode.actualSize.width / 2;
rect.right = dnode.offsetX + dnode.actualSize.width / 2;
rect.y = dnode.offsetY - dnode.actualSize.height / 2;
rect.bottom = dnode.offsetY + dnode.actualSize.height / 2;
return rect;
}
private isNodeOverLap(dnode: INode, layoutProp: Layout): void {
let nodeRect: Rect = { x: 0, y: 0, right: 0, bottom: 0, height: 0, width: 0 };
for (let i: number = 0; i < this.vertices.length; i++) {
let rect: Rect = { x: 0, y: 0, width: 0, height: 0 };
//let tempnode1: INode;
const tempnode1: INode = this.nameTable[this.vertices[i].value];
if (dnode.id !== tempnode1.id && tempnode1.offsetX !== 0 && tempnode1.offsetY !== 0) {
nodeRect = this.calculateRectValue(dnode);
rect = this.calculateRectValue(tempnode1);
if (this.isIntersect(rect, nodeRect, layoutProp)) {
if (layoutProp.orientation === 'TopToBottom' || layoutProp.orientation === 'BottomToTop') {
dnode.offsetX += layoutProp.horizontalSpacing;
} else {
dnode.offsetY += layoutProp.verticalSpacing;
}
this.isNodeOverLap(dnode, layoutProp);
}
}
}
}
private isIntersect(rect: Rect, nodeRect: Rect, layoutProp: Layout): boolean {
if (!(Math.floor(rect.right + layoutProp.horizontalSpacing) <= Math.floor(nodeRect.x) ||
Math.floor(rect.x - layoutProp.horizontalSpacing) >= Math.floor(nodeRect.right)
|| Math.floor(rect.y - layoutProp.verticalSpacing) >= Math.floor(nodeRect.bottom)
|| Math.floor(rect.bottom + layoutProp.verticalSpacing) <= Math.floor(nodeRect.y))) {
return true;
} else {
return false;
}
}
/* eslint-disable */
private updateMargin(layoutProp: Layout, layout: LayoutProp, modelBounds: Rect, viewPort: PointModel): void {
const viewPortBounds: Rect = { x: 0, y: 0, width: viewPort.x, height: viewPort.y };
//let layoutBounds: Rect;
let bounds: Bounds = {
x: modelBounds.x, y: modelBounds.y,
right: modelBounds.x + modelBounds.width,
bottom: modelBounds.y + modelBounds.height
};
const layoutBounds: Rect = layoutProp.bounds ? layoutProp.bounds : viewPortBounds;
if (layout.orientation === 'TopToBottom' || layout.orientation === 'BottomToTop') {
switch (layoutProp.horizontalAlignment) {
case 'Auto':
case 'Left':
layout.marginX = (layoutBounds.x - bounds.x) + layoutProp.margin.left;
break;
case 'Right':
layout.marginX = layoutBounds.x + layoutBounds.width - layoutProp.margin.right - bounds.right;
break;
case 'Center':
layout.marginX = layoutBounds.x + layoutBounds.width / 2 - (bounds.x + bounds.right) / 2;
break;
}
switch (layoutProp.verticalAlignment) {
case 'Top':
//const top: number;
const top: number = layoutBounds.y + layoutProp.margin.top;
layout.marginY = layout.orientation === 'TopToBottom' ? top : - top;
break;
case 'Bottom':
//const bottom: number;
const bottom: number = layoutBounds.y + layoutBounds.height - layoutProp.margin.bottom;
layout.marginY = layout.orientation === 'TopToBottom' ? bottom - bounds.bottom : -(bottom - bounds.bottom);
break;
case 'Auto':
case 'Center':
//const center: number;
const center: number = layoutBounds.y + layoutBounds.height / 2;
layout.marginY = layout.orientation === 'TopToBottom' ?
center - (bounds.y + bounds.bottom) / 2 : -center + (bounds.y + bounds.bottom) / 2;
break;
}
} else {
switch (layoutProp.horizontalAlignment) {
case 'Auto':
case 'Left':
//let left: number;
const left: number = layoutBounds.x + layoutProp.margin.left;
layout.marginX = layout.orientation === 'LeftToRight' ? left : - left;
break;
case 'Right':
let right: number;
right = layoutBounds.x + layoutBounds.width - layoutProp.margin.right;
layout.marginX = layout.orientation === 'LeftToRight' ? right - bounds.right : bounds.right - right;
break;
case 'Center':
let center: number;
center = layoutBounds.width / 2 + layoutBounds.x;
layout.marginX = layout.orientation === 'LeftToRight' ?
center - (bounds.y + bounds.bottom) / 2 : -center + (bounds.x + bounds.right) / 2;
break;
}
switch (layoutProp.verticalAlignment) {
case 'Top':
layout.marginY = layoutBounds.y + layoutProp.margin.top - bounds.x;
break;
case 'Auto':
case 'Center':
layout.marginY = layoutBounds.y + layoutBounds.height / 2 - (bounds.y + bounds.bottom) / 2;
break;
case 'Bottom':
layout.marginY = layoutBounds.y + layoutBounds.height - layoutProp.margin.bottom - bounds.bottom;
break;
}
}
}
/* eslint-enable */
//Handles positioning the nodes
private placementStage(model: MultiParentModel, marginX: number, marginY: number): Margin {
const placementStage: PlacementStage = this.coordinateAssignment(marginX, marginY, parent, model);
placementStage.model = model;
placementStage.widestRankValue = null;
this.placementStageExecute(placementStage);
return {
marginX: placementStage.marginX + model.layout.horizontalSpacing,
marginY: placementStage.marginY + model.layout.verticalSpacing
};
}
//Initializes the layout properties for positioning
private coordinateAssignment(marginX: number, marginY: number, parent: {}, model: MultiParentModel): PlacementStage {
const plalementChange: PlacementStage = {};
if (model.layout.orientation === 'TopToBottom' || model.layout.orientation === 'BottomToTop') {
plalementChange.horizontalSpacing = model.layout.horizontalSpacing;
plalementChange.verticalSpacing = model.layout.verticalSpacing;
} else {
plalementChange.horizontalSpacing = model.layout.verticalSpacing;
plalementChange.verticalSpacing = model.layout.horizontalSpacing;
}
plalementChange.orientation = 'north';
//Removed the conditions here. So check here in case of any issue
plalementChange.marginX = plalementChange.marginX = marginX;
plalementChange.marginY = plalementChange.marginY = marginY;
return plalementChange;
}
//Calculate the largest size of the node either height or width depends upon the layoutorientation
private calculateWidestRank(plalementChange: PlacementStage, graph: {}, model: MultiParentModel): void {
let isHorizontal: boolean = false;
if (plalementChange.model.layout.orientation === 'LeftToRight' || plalementChange.model.layout.orientation === 'RightToLeft') {
isHorizontal = true;
}
let offset: number = -plalementChange.verticalSpacing;
let lastRankMaxCellSize: number = 0.0;
plalementChange.rankSizes = [];
plalementChange.rankOffset = [];
for (let rankValue: number = model.maxRank; rankValue >= 0; rankValue--) {
let maxCellSize: number = 0.0;
const rank: (IVertex | IEdge)[] = model.ranks[rankValue];
let localOffset: number = isHorizontal ? plalementChange.marginY : plalementChange.marginX;
for (let i: number = 0; i < rank.length; i++) {
const node: IVertex | IEdge = rank[i];
if (this.crossReduction.isVertex(node)) {
const vertex: IVertex = node as IVertex;
if (vertex.cell && (vertex.cell.inEdges || vertex.cell.outEdges)) {
const obj: INode = this.nameTable[vertex.cell.name];
vertex.width = obj.actualSize.width;
vertex.height = obj.actualSize.height;
maxCellSize = Math.max(maxCellSize, (isHorizontal ? vertex.width : vertex.height));
}
} else {
if (node as IEdge) {
const edge: IEdge = node as IEdge;
let numEdges: number = 1;
if (edge.edges != null) {
numEdges = edge.edges.length;
}
node.width = (numEdges - 1) * 10;
}
}
if (isHorizontal) {
if (!node.height) {
node.height = 0;
}
}
// Set the initial x-value as being the best result so far
localOffset += (isHorizontal ? node.height : node.width) / 2.0;
this.setXY(node, rankValue, localOffset, isHorizontal ? true : false);
this.setTempVariable(node, rankValue, localOffset);
localOffset += ((isHorizontal ? node.height : node.width) / 2.0) + plalementChange.horizontalSpacing;
if (localOffset > plalementChange.widestRankValue) {
plalementChange.widestRankValue = localOffset;
plalementChange.widestRank = rankValue;
}
plalementChange.rankSizes[rankValue] = localOffset;
}
plalementChange.rankOffset[rankValue] = offset;
const distanceToNextRank: number = maxCellSize / 2.0 + lastRankMaxCellSize / 2.0 + plalementChange.verticalSpacing;
lastRankMaxCellSize = maxCellSize;
if (plalementChange.orientation === 'north' || plalementChange.orientation === 'west') {
offset += distanceToNextRank;
} else {
offset -= distanceToNextRank;
}
for (let i: number = 0; i < rank.length; i++) {
const cell: IVertex = rank[i];
this.setXY(cell, rankValue, offset, isHorizontal ? false : true);
}
}
}
/**
* Sets the temp position of the node on the layer \
*
* @returns { void } Sets the temp position of the node on the layer \
* @param {IVertex} node - provide the nodes value.
* @param {number} layer - provide the layer value.
* @param {number} value - provide the value value.
* @private
*/
public setTempVariable(node: IVertex, layer: number, value: number): void {
if (this.crossReduction.isVertex(node)) {
node.temp[0] = value;
} else {
node.temp[layer - node.minRank - 1] = value;
}
}
// eslint-disable-next-line valid-jsdoc
/**
* setXY method \
*
* @returns { void } setXY method .\
* @param {IVertex} node - provide the source value.
* @param {number} layer - provide the target value.
* @param {number} value - provide the layoutOrientation value.
* @param {boolean} isY - provide the layoutOrientation value.
* @param {IVertex[][]} ranks - provide the layoutOrientation value.
* @param {number} spacing - provide the layoutOrientation value.
*
* @private
*/
public setXY(node: IVertex, layer: number, value: number, isY: boolean, ranks?: IVertex[][], spacing?: number): void {
if (node && node.cell) {
if (node.cell.inEdges || node.cell.outEdges) {
if (isY) {
node.y[0] = value;
} else {
node.x[0] = value;
}
} else {
if (isY) {
node.y[layer - node.minRank - 1] = value;
} else {
node.x[layer - node.minRank - 1] = value;
}
}
} else {
this.setEdgeXY(ranks, node, spacing, layer);
}
}
//Sets geometry position of the layout node on the layout model
private rankCoordinates(stage: PlacementStage, rankValue: number, graph: {}, model: MultiParentModel): void {
let isHorizontal: boolean = false;
if (stage.model.layout.orientation === 'LeftToRight' || stage.model.layout.orientation === 'RightToLeft') {
isHorizontal = true;
}
const rank: (IVertex | IEdge)[] = model.ranks[rankValue];
let maxOffset: number = 0.0;
let localOffset: number = (isHorizontal ? stage.marginY : stage.marginX) + (stage.widestRankValue - stage.rankSizes[rankValue]) / 2;
for (let i: number = 0; i < rank.length; i++) {
const node: IVertex = rank[i];
if (this.crossReduction.isVertex(node)) {
const obj: INode = this.nameTable[node.cell.name];
node.width = obj.actualSize.width;
node.height = obj.actualSize.height;
maxOffset = Math.max(maxOffset, node.height);
} else {
const edge: IEdge = node as IEdge;
let numEdges: number = 1;
if (edge.edges != null) {
numEdges = edge.edges.length;
}
if (isHorizontal) {
node.height = (numEdges - 1) * 10;
} else {
node.width = (numEdges - 1) * 10;
}
}
const size: number = (isHorizontal ? node.height : node.width) / 2.0;
localOffset += size;
this.setXY(node, rankValue, localOffset, isHorizontal ? true : false);
this.setTempVariable(node, rankValue, localOffset);
localOffset += (size + stage.horizontalSpacing);
}
}
//sets the layout in an initial positioning.it will arange all the ranks as much as possible
private initialCoords(plalementChange: PlacementStage, facade: {}, model: MultiParentModel): void {
this.calculateWidestRank(plalementChange, facade, model);
// Reverse sweep direction each time from widest rank
for (let i: number = plalementChange.widestRank; i >= 0; i--) {
if (i < model.maxRank) {
this.rankCoordinates(plalementChange, i, facade, model);
}
}
for (let i: number = plalementChange.widestRank + 1; i <= model.maxRank; i++) {
if (i > 0) {
this.rankCoordinates(plalementChange, i, facade, model);
}
}
}
/**
* Checks whether the given node is an ancestor \
*
* @returns { boolean } Checks whether the given node is an ancestor \
* @param {IVertex} node - provide the nodes value.
* @param {IVertex} otherNode - provide the layer value.
* @private
*/
public isAncestor(node: IVertex, otherNode: IVertex): boolean {
// Firstly, the hash code of this node needs to be shorter than the other node
if (otherNode != null && node.hashCode != null && otherNode.hashCode != null
&& node.hashCode.length < otherNode.hashCode.length) {
if (node.hashCode === otherNode.hashCode) {
return true;
}
if (node.hashCode == null || node.hashCode == null) {
return false;
}
for (let i: number = 0; i < node.hashCode.length; i++) {
if (node.hashCode[i] !== otherNode.hashCode[i]) {
return false;
}
}
return true;
}
return false;
}
//initializes the sorter object
private weightedCellSorter(cell: IVertex, weightedValue: number): WeightedCellSorter {
const weightedCellSorter: WeightedCellSorter = {};
weightedCellSorter.cell = cell ? cell : null;
weightedCellSorter.weightedValue = weightedValue ? weightedValue : 0;
weightedCellSorter.visited = false;
weightedCellSorter.rankIndex = null;
return weightedCellSorter;
}
//Performs one node positioning in both directions
private minNode(plalementChange: PlacementStage, model: MultiParentModel): void {
const nodeList: WeightedCellSorter[] = [];
const map: VertexMapper = { map: {} };
const rank: IVertex[][] = [];
for (let i: number = 0; i <= model.maxRank; i++) {
rank[i] = model.ranks[i];
for (let j: number = 0; j < rank[i].length; j++) {
const node: IVertex = rank[i][j];
const nodeWrapper: WeightedCellSorter = this.weightedCellSorter(node, i);
nodeWrapper.rankIndex = j;
nodeWrapper.visited = true;
nodeList.push(nodeWrapper);
model.setDictionaryForSorter(map, node, nodeWrapper, true);
}
}
const maxTries: number = nodeList.length * 10;
let count: number = 0;
const tolerance: number = 1;
while (nodeList.length > 0 && count <= maxTries) {
const cellWrapper: WeightedCellSorter = nodeList.shift();
const cell: IVertex = cellWrapper.cell;
const rankValue: number = cellWrapper.weightedValue;
const rankIndex: number = cellWrapper.rankIndex;
const nextLayerConnectedCells: IVertex[] = this.crossReduction.getConnectedCellsOnLayer(cell, rankValue);
const previousLayerConnectedCells: IVertex[] = this.crossReduction.getConnectedCellsOnLayer(cell, rankValue, true);
const nextConnectedCount: number = nextLayerConnectedCells.length;
const prevConnectedCount: number = previousLayerConnectedCells.length;
const medianNextLevel: number = this.medianXValue(plalementChange, nextLayerConnectedCells, rankValue + 1);
const medianPreviousLevel: number = this.medianXValue(plalementChange, previousLayerConnectedCells, rankValue - 1);
const numConnectedNeighbours: number = nextConnectedCount + prevConnectedCount;
const currentPosition: number = this.crossReduction.getTempVariable(cell, rankValue);
let cellMedian: number = currentPosition;
if (numConnectedNeighbours > 0) {
cellMedian = (medianNextLevel * nextConnectedCount + medianPreviousLevel * prevConnectedCount) / numConnectedNeighbours;
}
if (nextConnectedCount === 1 && prevConnectedCount === 1) {
cellMedian = (medianPreviousLevel * prevConnectedCount) / prevConnectedCount;
} else if (nextConnectedCount === 1) {
cellMedian = (medianNextLevel * nextConnectedCount) / nextConnectedCount;
}
let positionChanged: boolean = false;
let tempValue: number = undefined;
if (cellMedian < currentPosition - tolerance) {
if (rankIndex === 0) {
tempValue = cellMedian;
positionChanged = true;
} else {
const leftCell: IVertex = rank[rankValue][rankIndex - 1];
let leftLimit: number = this.crossReduction.getTempVariable(leftCell, rankValue);
leftLimit = leftLimit + leftCell.width / 2 + plalementChange.intraCellSpacing + cell.width / 2;
if (leftLimit < cellMedian) {
tempValue = cellMedian;
positionChanged = true;
} else if (leftLimit < this.crossReduction.getTempVariable(cell, rankValue) - tolerance) {
tempValue = leftLimit;
positionChanged = true;
}
}
} else if (cellMedian > currentPosition + tolerance) {
const rankSize: number = rank[rankValue].length;
if (rankIndex === rankSize - 1) {
tempValue = cellMedian;
positionChanged = true;
} else {
const rightCell: IVertex = rank[rankValue][rankIndex + 1];
let rightLimit: number = this.crossReduction.getTempVariable(rightCell, rankValue);
rightLimit = rightLimit - rightCell.width / 2 - plalementChange.intraCellSpacing - cell.width / 2;
if (rightLimit > cellMedian) {
tempValue = cellMedian;
positionChanged = true;
} else if (rightLimit > this.crossReduction.getTempVariable(cell, rankValue) + tolerance) {
tempValue = rightLimit;
positionChanged = true;
}
}
}
if (positionChanged) {
this.setTempVariable(cell, rankValue, tempValue);
// Add connected nodes to map and list
this.updateNodeList(nodeList, map, nextLayerConnectedCells, model);
this.updateNodeList(nodeList, map, previousLayerConnectedCells, model);
}
if (this.crossReduction.isVertex(cellWrapper.cell)) {
cellWrapper.visited = false;
}
count++;
}
}
//Updates the ndoes collection
private updateNodeList(nodeList: WeightedCellSorter[], map: VertexMapper, collection: IVertex[], model: MultiParentModel): void {
for (let i: number = 0; i < collection.length; i++) {
const connectedCell: IVertex = collection[i];
const connectedCellWrapper: WeightedCellSorter = model.getDictionaryForSorter(map, connectedCell);
if (connectedCellWrapper != null) {
if (connectedCellWrapper.visited === false) {
connectedCellWrapper.visited = true;
nodeList.push(connectedCellWrapper);
}
}
}
}
//Calculates the node position of the connected cell on the specified rank
private medianXValue(plalementChange: PlacementStage, connectedCells: IVertex[], rankValue: number): number {
if (connectedCells.length === 0) {
return 0;
}
const medianValues: number[] = [];
for (let i: number = 0; i < connectedCells.length; i++) {
medianValues[i] = this.crossReduction.getTempVariable(connectedCells[i], rankValue);
}
medianValues.sort((a: number, b: number) => {
return a - b;
});
if (connectedCells.length % 2 === 1) {
return medianValues[Math.floor(connectedCells.length / 2)];
} else {
const medianPoint: number = connectedCells.length / 2;
const leftMedian: number = medianValues[medianPoint - 1];
const rightMedian: number = medianValues[medianPoint];
return ((leftMedian + rightMedian) / 2);
}
}
//Updates the geometry of the vertices
private placementStageExecute(plalementChange: PlacementStage): void {
let isHorizontal: boolean = false;
if (plalementChange.model.layout.orientation === 'LeftToRight' || plalementChange.model.layout.orientation === 'RightToLeft') {
isHorizontal = true;
}
plalementChange.jettyPositions = {};
const model: MultiParentModel = plalementChange.model;
// eslint-disable-next-line
isHorizontal ? plalementChange.currentYDelta = 0.0 : plalementChange.currentXDelta = 0.0;
this.initialCoords(plalementChange, { model: model }, model);
this.minNode(plalementChange, model);
let bestOffsetDelta: number = 100000000.0;
if (!plalementChange.maxIterations) {
plalementChange.maxIterations = 8;
}
for (let i: number = 0; i < plalementChange.maxIterations; i++) {
// if the total offset is less for the current positioning,
//there are less heavily angled edges and so the current positioning is used
if ((isHorizontal ? plalementChange.currentYDelta : plalementChange.currentXDelta) < bestOffsetDelta) {
for (let j: number = 0; j < model.ranks.length; j++) {
const rank: IVertex[] = model.ranks[j];
for (let k: number = 0; k < rank.length; k++) {
const cell: IVertex = rank[k];
this.setXY(cell, j, this.crossReduction.getTempVariable(cell, j), isHorizontal ? true : false);
}
}
bestOffsetDelta = isHorizontal ? plalementChange.currentYDelta : plalementChange.currentXDelta;
}
// eslint-disable-next-line
isHorizontal ? plalementChange.currentYDelta = 0 : plalementChange.currentXDelta = 0;
}
this.setCellLocations(plalementChange, model);
}
//sets the cell position in the after the layout operation
private setCellLocations(plalementChange: PlacementStage, model: MultiParentModel): void {
const vertices: IVertex[] = this.getValues(model.vertexMapper);
for (let i: number = 0; i < vertices.length; i++) {
this.setVertexLocation(plalementChange, vertices[i]);
}
}
//used to specify the geometrical position of the layout model cell
private garphModelsetVertexLocation(plalementChange: PlacementStage, cell: Vertex, x: number, y: number): Rect {
//let model: MultiParentModel = plalementChange.model;
const geometry: Rect = cell.geometry;
let result: Rect = null;
if (geometry != null) {
result = { x: x, y: y, width: geometry.width, height: geometry.height };
if (geometry.x !== x || geometry.y !== y) {
cell.geometry = result;
}
}
return result;
}
//set the position of the specified node
private setVertexLocation(plalementChange: PlacementStage, cell: IVertex): void {
let isHorizontal: boolean = false;
if (plalementChange.model.layout.orientation === 'LeftToRight' || plalementChange.model.layout.orientation === 'RightToLeft') {
isHorizontal = true;
}
const realCell: Vertex = cell.cell;
const positionX: number = cell.x[0] - cell.width / 2;
const positionY: number = cell.y[0] - cell.height / 2;
this.garphModelsetVertexLocation(plalementChange, realCell, positionX, positionY);
if (isHorizontal) {
if (!plalementChange.marginY) {
plalementChange.marginY = 0;
}
plalementChange.marginY = Math.max(plalementChange.marginY, positionY + cell.height);
} else {
if (!plalementChange.marginX) {
plalementChange.marginX = 0;
}
plalementChange.marginX = Math.max(plalementChange.marginX, positionX + cell.width);
}
}
/**
* get the specific value from the key value pair \
*
* @returns { {}[] } get the specific value from the key value pair \
* @param {VertexMapper} mapper - provide the mapper value.
* @private
*/
private getValues(mapper: VertexMapper): {}[] {
const list: {}[] = [];
if (mapper.map) {
for (const key of Object.keys(mapper.map)) {
list.push(mapper.map[key]);
}
}
return list;
}
/**
*Checks and reduces the crosses in between line segments \
*
* @returns { void } Checks and reduces the crosses in between line segments.\
* @param {End} model - provide the model value.
*
* @private
*/
private crossingStage(model: MultiParentModel): void {
this.crossReduction.execute(model);
}
//Initializes the ranks of the vertices
private layeringStage(model: MultiParentModel): void {
this.initialRank(model);
this.fixRanks(model);
}
//determine the initial rank for the each vertex on the relevent direction
private initialRank(model: MultiParentModel): void {
const startNodes: IVertex[] = model.startNodes;
const internalNodes: IVertex[] = model.getDictionaryValues(model.vertexMapper);
const startNodesCopy: IVertex[] = startNodes.slice();
while (startNodes.length > 0) {
const internalNode: IVertex = startNodes[0];
const layerDeterminingEdges: IEdge[] = internalNode.connectsAsTarget;
const edgesToBeMarked: IEdge[] = internalNode.connectsAsSource;
let allEdgesScanned: boolean = true;
let minimumLayer: number = 100000000;
for (let i: number = 0; i < layerDeterminingEdges.length; i++) {
const internalEdge: IEdge = layerDeterminingEdges[i];
if (internalEdge.temp[0] === 5270620) {
// This edge has been scanned, get the layer of the node on the other end
const otherNode: IVertex = internalEdge.source;
minimumLayer = Math.min(minimumLayer, otherNode.temp[0] - 1);
} else {
allEdgesScanned = false;
break;
}
}
// If all edge have been scanned, assign the layer, mark all edges in the other direction and remove from the nodes list
if (allEdgesScanned) {
internalNode.temp[0] = minimumLayer;
if (!model.maxRank) { model.maxRank = 100000000; }
model.maxRank = Math.min(model.maxRank, minimumLayer);
if (edgesToBeMarked != null) {
for (let i: number = 0; i < edgesToBeMarked.length; i++) {
const internalEdge: IEdge = edgesToBeMarked[i];
internalEdge.temp[0] = 5270620;
// Add node on other end of edge to LinkedList of nodes to be analysed
const otherNode: IVertex = internalEdge.target;
// Only add node if it hasn't been assigned a layer
if (otherNode.temp[0] === -1) {
startNodes.push(otherNode);
// Mark this other node as neither being unassigned nor assigned
//so it isn't added to this list again, but it's layer isn't used in any calculation.
otherNode.temp[0] = -2;
}
}
}
startNodes.shift();
} else {
// Not all the edges have been scanned, get to the back of the class and put the dunces cap on
const removedCell: IVertex = startNodes.shift();
startNodes.push(internalNode);
if (removedCell === internalNode && startNodes.length === 1) {
// This is an error condition, we can't get out of this loop.
//It could happen for more than one node but that's a lot harder to detect. Log the error
break;
}
}
}
for (let i: number = 0; i < internalNodes.length; i++) {
internalNodes[i].temp[0] -= model.maxRank;
}
for (let i: number = 0; i < startNodesCopy.length; i++) {
const internalNode: IVertex = startNodesCopy[i];
let currentMaxLayer: number = 0;
const layerDeterminingEdges: IEdge[] = internalNode.connectsAsSource;
for (let j: number = 0; j < layerDeterminingEdges.length; j++) {
const internalEdge: IEdge = layerDeterminingEdges[j];
const otherNode: IVertex = internalEdge.target;
internalNode.temp[0] = Math.max(currentMaxLayer, otherNode.temp[0] + 1);
currentMaxLayer = internalNode.temp[0];
}
}
model.maxRank = 100000000 - model.maxRank;
}
//used to set the optimum value of each vertex on the layout
private fixRanks(model: MultiParentModel): void {
model.fixRanks();
}
//used to determine any cyclic stage have been created on the layout model
private cycleStage(model: MultiParentModel): void {
const seenNodes: {} = {};
model.startNodes = [];
const unseenNodesArray: IVertex[] = model.getDictionaryValues(model.vertexMapper);
const unseenNodes: IVertex[] = [];
for (let i: number = 0; i < unseenNodesArray.length; i++) {
unseenNodesArray[i].temp[0] = -1;
unseenNodes[unseenNodesArray[i].id] = unseenNodesArray[i];
}
let rootsArray: IVertex[] = null;
if (model.roots != null) {
const modelRoots: Vertex[] = model.roots;
rootsArray = [];
for (let i: number = 0; i < modelRoots.length; i++) {
rootsArray[i] = model.getDictionary(model.vertexMapper, modelRoots[i]);
if (rootsArray[i] != null) {
model.startNodes.push(rootsArray[i]);
}
}
}
model.visit('removeParentConnection', rootsArray, true, null, { seenNodes: seenNodes, unseenNodes: unseenNodes });
const seenNodesCopy: {} = model.clone(seenNodes, null, true);
model.visit('removeNodeConnection', unseenNodes, true, seenNodesCopy, { seenNodes: seenNodes, unseenNodes: unseenNodes });
}
/**
* removes the edge from the given collection \
*
* @returns { IEdge } removes the edge from the given collection .\
* @param {IEdge} obj - provide the angle value.
* @param { IEdge[]} array - provide the angle value.
* @private
*/
public remove(obj: IEdge, array: IEdge[]): IEdge {
const index: number = array.indexOf(obj);
if (index !== -1) {
array.splice(index, 1);
}
return obj;
}
/**
* Inverts the source and target of an edge \
*
* @returns { void } Inverts the source and target of an edge .\
* @param {IEdge} connectingEdge - provide the angle value.
* @param { number} layer - provide the angle value.
* @private
*/
public invert(connectingEdge: IEdge, layer: number): void {
const temp: IVertex = connectingEdge.source;
connectingEdge.source = connectingEdge.target;
connectingEdge.target = temp;
connectingEdge.isReversed = !connectingEdge.isReversed;
}
/**
* used to get the edges between the given source and target \
*
* @returns { IConnector[] } used to get the edges between the given source and target .\
* @param {Vertex} source - provide the angle value.
* @param { Vertex} target - provide the angle value.
* @param { boolean} directed - provide the angle value.
* @private
*/
public getEdgesBetween(source: Vertex, target: Vertex, directed: boolean): IConnector[] {
directed = (directed != null) ? directed : false;
const edges: IConnector[] = this.getEdges(source);
const result: IConnector[] = [];
for (let i: number = 0; i < edges.length; i++) {
const src: Vertex = this.getVisibleTerminal(edges[i], true);
const trg: Vertex = this.getVisibleTerminal(edges[i], false);
if ((src === source && trg === target) || (!directed && src === target && trg === source)) {
result.push(edges[i]);
}
}
return result;
}
}
/**
* Handles position the objects in a hierarchical tree structure
*/
class MultiParentModel {
/** @private */
public roots: Vertex[];
/** @private */
public vertexMapper: VertexMapper;
/** @private */
public edgeMapper: VertexMapper;
/** @private */
public layout: LayoutProp;
/** @private */
public maxRank: number;
private hierarchicalLayout: HierarchicalLayoutUtil;
private multiObjectIdentityCounter: number = 0;
/** @private */
public ranks: IVertex[][];
//used to count the no of times the parent have been used
private dfsCount: number = 0;
/** @private */
public startNodes: IVertex[];
private hierarchicalUtil: HierarchicalLayoutUtil = new HierarchicalLayoutUtil();
constructor(layout: HierarchicalLayoutUtil, vertices: Vertex[], roots: Vertex[], dlayout: LayoutProp) {
this.roots = roots;
this.vertexMapper = { map: {} };
const internalVertices: IVertex[] = [];
this.layout = dlayout;
this.maxRank = 100000000;
this.edgeMapper = {map: {}};
this.hierarchicalLayout = layout;
this.createInternalCells(layout, vertices, internalVertices, dlayout);
for (let i: number = 0; i < vertices.length; i++) {
const edges: IEdge[] = internalVertices[i].connectsAsSource;
for (let j: number = 0; j < edges.length; j++) {
const internalEdge: IEdge = edges[j];
const realEdges: IConnector[] = internalEdge.edges;
if (realEdges != null && realEdges.length > 0) {
const realEdge: IConnector = realEdges[0];
let targetCell: Vertex = layout.getVisibleTerminal(realEdge, false);
let internalTargetCell: IVertex = this.getDictionary(this.vertexMapper, targetCell);
if (internalVertices[i] === internalTargetCell) {
targetCell = layout.getVisibleTerminal(realEdge, true);
internalTargetCell = this.getDictionary(this.vertexMapper, targetCell);
}
if (internalTargetCell != null && internalVertices[i] !== internalTargetCell) {
internalEdge.target = internalTargetCell;
if (internalTargetCell.connectsAsTarget.length === 0) {
internalTargetCell.connectsAsTarget = [];
}
if (internalTargetCell.connectsAsTarget.indexOf(internalEdge) < 0) {
internalTargetCell.connectsAsTarget.push(internalEdge);
}
}
}
}
internalVertices[i].temp[0] = 1;
}
}
/* tslint:disable */
private resetEdge(edge: IConnector): IConnector {
const geometry: Geometry = { x: 0, y: 0, width: 0, height: 0, relative: true };
const geo: object = geometry;
edge['geometry'] = geo;
return edge;
}
// eslint-disable-next-line max-len
private createInternalCells(layout: HierarchicalLayoutUtil, vertices: Vertex[], internalVertices: IVertex[], dlayout: LayoutProp): void {
for (let i: number = 0; i < vertices.length; i++) {
internalVertices[i] = {
x: [], y: [], temp: [], cell: vertices[i],
id: vertices[i].name, connectsAsTarget: [], connectsAsSource: [], type: 'internalVertex'
};
this.setDictionary(this.vertexMapper, vertices[i], internalVertices[i]);
const conns: IConnector[] = layout.getEdges(vertices[i]);
internalVertices[i].connectsAsSource = [];
for (let j: number = 0; j < conns.length; j++) {
const cell: Vertex = layout.getVisibleTerminal(conns[j], false);
if (cell !== vertices[i]) {
const undirectedEdges: IConnector[] = layout.getEdgesBetween(vertices[i], cell, false);
const directedEdges: IConnector[] = layout.getEdgesBetween(vertices[i], cell, true);
if (undirectedEdges != null && undirectedEdges.length > 0 && directedEdges.length * 2 >= undirectedEdges.length) {
const internalEdge: IEdge = { x: [], y: [], temp: [], edges: undirectedEdges, ids: [] };
if (dlayout.enableLayoutRouting) {
for (let k: number = 0; k < undirectedEdges.length; k++) {
const edge: IConnector = undirectedEdges[k];
this.setDictionary(this.edgeMapper, undefined, internalEdge, edge.id);
// Resets all point on the edge and disables the edge style
// without deleting it from the cell style
this.resetEdge(edge);
}
}
internalEdge.source = internalVertices[i];
for (let m: number = 0; m < undirectedEdges.length; m++) {
internalEdge.ids.push(undirectedEdges[m].id);
}
internalEdge.source = internalVertices[i];
if (!internalVertices[i].connectsAsSource) {
internalVertices[i].connectsAsSource = [];
}
if (internalVertices[i].connectsAsSource.indexOf(internalEdge) < 0) {
internalVertices[i].connectsAsSource.push(internalEdge);
}
}
}
}
internalVertices[i].temp[0] = 0;
}
}
/* tslint:enable */
/**
* used to set the optimum value of each vertex on the layout \
*
* @returns { void } used to set the optimum value of each vertex on the layout .\
* @private
*/
public fixRanks(): void {
const rankList: IVertex[][] = [];
this.ranks = [];
for (let i: number = 0; i < this.maxRank + 1; i++) {
rankList[i] = [];
this.ranks[i] = rankList[i];
}
let rootsArray: IVertex[] = null;
if (this.roots != null) {
const oldRootsArray: Vertex[] = this.roots;
rootsArray = [];
for (let i: number = 0; i < oldRootsArray.length; i++) {
const cell: Vertex = oldRootsArray[i];
const internalNode: IVertex = this.getDictionary(this.vertexMapper, cell);
rootsArray[i] = internalNode;
}
}
this.visit('updateMinMaxRank', rootsArray, false, null, { seenNodes: null, unseenNodes: null, rankList: rankList });
}
//Updates the min/max rank of the layer
private updateMinMaxRank(layer: number, seen: number, data: TraverseData): void {
//let seenNodes: {} = data.seenNodes;
//let unseenNodes: {} = data.unseenNodes;
const parent: IVertex = data.parent;
const node: IVertex = data.root;
const edge: IEdge = data.edge;
const rankList: IVertex[][] = data.rankList;
if (!node.maxRank && node.maxRank !== 0) {
node.maxRank = -1;
}
if (!node.minRank && node.minRank !== 0) {
node.minRank = -1;
}
if (seen === 0 && node.maxRank < 0 && node.minRank < 0) {
rankList[node.temp[0]].push(node);
node.maxRank = node.temp[0];
node.minRank = node.temp[0];
node.temp[0] = rankList[node.maxRank].length - 1;
}
if (parent != null && edge != null) {
const parentToCellRankDifference: number = parent.maxRank - node.maxRank;
if (parentToCellRankDifference > 1) {
edge.maxRank = parent.maxRank;
edge.minRank = node.maxRank;
edge.temp = [];
edge.x = [];
edge.y = [];
for (let i: number = edge.minRank + 1; i < edge.maxRank; i++) {
rankList[i].push(edge);
this.hierarchicalUtil.setTempVariable(edge, i, rankList[i].length - 1);
}
}
}
}
//used to store the value of th given key on the object
private setDictionary(dic: VertexMapper, key: Vertex, value: IVertex, edgeId?: string): IVertex {
if (!edgeId) {
const id: string = key.name;
const previous: IVertex = dic.map[id];
dic.map[id] = value;
return previous;
} else {
const previous: IVertex = dic.map[edgeId];
dic.map[edgeId] = value;
return previous;
}
}
/**
* used to store the value of th given key on the objectt \
*
* @returns { IVertex } used to store the value of th given key on the object .\
* @param {VertexMapper} dic - provide the angle value.
* @param {IVertex} key - provide the angle value.
* @param {WeightedCellSorter} value - provide the angle value.
* @param {boolean} flag - provide the angle value.
* @private
*/
public setDictionaryForSorter(dic: VertexMapper, key: IVertex, value: WeightedCellSorter, flag: boolean): IVertex {
const id: string = key.id;
if (!id) {
//id = this._getDictionaryForSorter(dic, key);
}
const previous: IVertex = dic.map[id];
dic.map[id] = value;
return previous;
}
/**
* used to get the value of the given key \
*
* @returns { IVertex } used to get the value of the given key .\
* @param {VertexMapper} dic - provide the angle value.
* @param {IVertex} key - provide the angle value.
* @private
*/
public getDictionary(dic: VertexMapper, key: Vertex): IVertex {
if (!this.multiObjectIdentityCounter && this.multiObjectIdentityCounter !== 0) {
this.multiObjectIdentityCounter = 0;
}
const id: string = key.name;
if (!id) {
if (!key.layoutObjectId) {///####
key.layoutObjectId = 'graphHierarchyNode#' + this.multiObjectIdentityCounter++;
return key.layoutObjectId as IVertex;
} else { return dic.map[key.layoutObjectId]; }
}
return dic.map[id];
}
/**
* used to get the value of the given key \
*
* @returns { IVertex } used to get the value of the given key .\
* @param {VertexMapper} dic - provide the angle value.
* @param {IVertex} key - provide the angle value.
* @private
*/
public getDictionaryForSorter(dic: VertexMapper, key: IVertex): WeightedCellSorter {
if (!this.multiObjectIdentityCounter && this.multiObjectIdentityCounter !== 0) {
this.multiObjectIdentityCounter = 0;
}
const id: string = key.id;
if (!id) {
if (!key.layoutObjectId) {///####
key.layoutObjectId = 'graphHierarchyNode#' + this.multiObjectIdentityCounter++;
return key.layoutObjectId as WeightedCellSorter;
} else { return dic.map[key.layoutObjectId]; }
}
return dic.map[id];
}
/**
* used to get all the values of the dictionary object \
*
* @returns { IVertex[] } used to get all the values of the dictionary object .\
* @param {VertexMapper} dic - provide the angle value.
* @private
*/
public getDictionaryValues(dic: VertexMapper): IVertex[] {
const result: IVertex[] = [];
for (const key of Object.keys(dic.map)) {
result.push(dic.map[key]);
}
return result;
}
/**
* used to visit all the entries on the given dictionary with given function \
*
* @returns { void } used to visit all the entries on the given dictionary with given function .\
* @param {string} visitor - provide the visitor value.
* @param {IVertex[]} dfsRoots - provide the dfsRoots value.
* @param {boolean} trackAncestors - provide the trackAncestors value.
* @param {{}} seenNodes - provide the seenNodes value.
* @param {TraverseData} data - provide the data value.
* @private
*/
public visit(visitor: string, dfsRoots: IVertex[], trackAncestors: boolean, seenNodes: {}, data: TraverseData): void {
//let seenNodes1: {} = data.seenNodes;
//let unseenNodes1: {} = data.unseenNodes;
//let rankList: IVertex[][] = data.rankList;
// Run depth first search through on all roots
if (dfsRoots != null) {
for (let i: number = 0; i < dfsRoots.length; i++) {
const internalNode: IVertex = dfsRoots[i];
if (internalNode != null) {
if (seenNodes == null) {
seenNodes = new Object();
}
data.parent = null;
data.root = internalNode;
data.edge = null;
if (trackAncestors) {
// Set up hash code for root
internalNode.hashCode = [];
internalNode.hashCode[0] = this.dfsCount;
internalNode.hashCode[1] = i;
this.extendedDfs(visitor, seenNodes, i, 0, data);
} else {
this.depthFirstSearch(visitor, seenNodes, 0, data);
}
}
}
this.dfsCount++;
}
}
//used to perform the depth fisrt search on the layout model
private depthFirstSearch(visitor: string, seen: {}, layer: number, data: TraverseData): void {
//let seenNodes1: {} = data.seenNodes;
//let unseenNodes1: {} = data.unseenNodes;
//let rankList: IVertex[][] = data.rankList;
//let parent: IVertex = data.parent;
const root: IVertex = data.root;
//let edge: IEdge = data.edge;
if (root != null) {
const rootId: string = root.id;
if (seen[rootId] == null) {
seen[rootId] = root;
this.updateConnectionRank(visitor, layer, 0, data);
// Copy the connects as source list so that visitors can change the original for edge direction inversions
const outgoingEdges: IEdge[] = root.connectsAsSource.slice();
for (let i: number = 0; i < outgoingEdges.length; i++) {
const internalEdge: IEdge = outgoingEdges[i];
const targetNode: IVertex = internalEdge.target;
// Root check is O(|roots|)
data.parent = root;
data.root = targetNode;
data.edge = internalEdge;
this.depthFirstSearch(visitor, seen, layer + 1, data);
}
} else {
this.updateConnectionRank(visitor, layer, 1, data);
}
}
}
//Updates the rank of the connection
private updateConnectionRank(visitor: string, layer: number, seen: number, traversedList: TraverseData): void {
const parent: IVertex = traversedList.parent;
const root: IVertex = traversedList.root;
const edge: IEdge = traversedList.edge;
if (visitor === 'removeParentConnection' || visitor === 'removeNodeConnection') {
const remove: boolean = visitor === 'removeNodeConnection' ? true : false;
this.removeConnectionEdge(parent, root, edge, layer, traversedList, remove);
}
if (visitor === 'updateMinMaxRank') {
this.updateMinMaxRank(layer, seen, traversedList);
}
}
//Removes the edge from the collection
private removeConnectionEdge(parent: IVertex, node: IVertex, edge: IEdge, layer: number, data: TraverseData, remove: boolean): void {
const seenNodes: {} = data.seenNodes;
const unseenNodes: {} = data.unseenNodes;
//let rankList: IVertex[][] = data.rankList;
if (this.hierarchicalUtil.isAncestor(node, parent)) {
this.hierarchicalUtil.invert(edge, 0);
this.hierarchicalUtil.remove(edge, parent.connectsAsSource);
if (remove) {
node.connectsAsSource.push(edge);
parent.connectsAsTarget.push(edge);
this.hierarchicalUtil.remove(edge, node.connectsAsTarget);
} else {
parent.connectsAsTarget.push(edge);
this.hierarchicalUtil.remove(edge, node.connectsAsTarget);
node.connectsAsSource.push(edge);
}
}
seenNodes[node.id] = node;
delete unseenNodes[node.id];
}
//the dfs extends the default version by keeping track of cells ancestors, but it should be only used when necessary
private extendedDfs(visitor: string, seen: {}, cHash: number, layer: number, data: TraverseData): void {
//let seenNodes: {} = data.seenNodes;
//let unseenNodes: {} = data.unseenNodes;
//let rankList: IVertex[][] = data.rankList;
const parent: IVertex = data.parent;
const root: IVertex = data.root;
const edge: IEdge = data.edge;
if (root != null) {
if (parent != null) {
if (root.hashCode == null ||
root.hashCode[0] !== parent.hashCode[0]) {
const hashCodeLength: number = parent.hashCode.length + 1;
root.hashCode = parent.hashCode.slice();
root.hashCode[hashCodeLength - 1] = cHash;
}
}
const rootId: string = root.id;
if (seen[rootId] == null) {
seen[rootId] = root;
this.updateConnectionRank(visitor, layer, 0, data);
const outgoingEdges: IEdge[] = root.connectsAsSource.slice();
for (let i: number = 0; i < outgoingEdges.length; i++) {
const internalEdge: IEdge = outgoingEdges[i];
const targetNode: IVertex = internalEdge.target;
data.parent = root;
data.root = targetNode;
data.edge = internalEdge;
this.extendedDfs(visitor, seen, i, layer + 1, data);
}
} else {
this.updateConnectionRank(visitor, layer, 1, data);
}
}
}
/**
* used to clone the specified object ignoring all fieldnames in the given array of transient fields \
*
* @returns { void } used to clone the specified object ignoring all fieldnames in the given array of transient fields .\
* @param {Object} obj - provide the source value.
* @param {string[]} transients - provide the target value.
* @param {boolean} shallow - provide the shallow value.
*
* @private
*/
public clone(obj: Object, transients: string[], shallow: boolean): Object {
shallow = (shallow != null) ? shallow : false;
if (obj != null && typeof (obj.constructor) === 'function') {
const clonedObj: Object = obj.constructor();
for (const i of Object.keys(obj)) {
if (i !== 'layoutObjectId' && (transients == null || transients.indexOf(i) < 0)) {
if (!shallow && typeof (obj[i]) === 'object') {
//not used
// _clone[i] = $.extend(true, {}, obj[i]);
} else {
clonedObj[i] = obj[i];
}
}
}
return clonedObj;
}
return null;
}
}
/**
* Defines how to reduce the crosses in between the line segments
*/
class CrossReduction {
/** @private */
public nestedBestRanks: IVertex[][];
/**
* used to calculate the number of edges crossing the layout model \
*
* @returns { number } used to calculate the number of edges crossing the layout model\
* @param {MultiParentModel} model - provide the model value.
*
* @private
*/
private calculateCrossings(model: MultiParentModel): number {
const numRanks: number = model.ranks.length;
let totalCrossings: number = 0;
for (let i: number = 1; i < numRanks; i++) {
totalCrossings += this.calculateRankCrossing(i, model);
}
return totalCrossings;
}
/**
* used to get the temp value specified for the node or connector. \
*
* @returns { boolean } used to get the temp value specified for the node or connector.\
* @param {IVertex} node - provide the node value.
* @param {IVertex} layer - provide the layer value.
*
* @private
*/
public getTempVariable(node: IVertex, layer: number): number {
if (node) {
if (this.isVertex(node)) {
return node.temp[0];
} else {
return node.temp[layer - node.minRank - 1];
}
}
return 0;
}
//used to specify the number of conenctors crossing between the specified rank and its below rank
private calculateRankCrossing(i: number, model: MultiParentModel): number {
let totalCrossings: number = 0;
const rank: IVertex[] = model.ranks[i];
const previousRank: IVertex[] = model.ranks[i - 1];
const tmpIndices: number[][] = [];
// Iterate over the top rank and fill in the connection information
for (let j: number = 0; j < rank.length; j++) {
const node: IVertex = rank[j];
const rankPosition: number = this.getTempVariable(node, i);
const connectedCells: IVertex[] = this.getConnectedCellsOnLayer(node, i, true);
///####
const nodeIndices: number[] = [];
for (let k: number = 0; k < connectedCells.length; k++) {
const connectedNode: IVertex = connectedCells[k];
const otherCellRankPosition: number = this.getTempVariable(connectedNode, i - 1);
nodeIndices.push(otherCellRankPosition);
}
nodeIndices.sort((x: number, y: number): number => { return x - y; });
tmpIndices[rankPosition] = nodeIndices;
}
let indices: number[] = [];
for (let j: number = 0; j < tmpIndices.length; j++) {
indices = indices.concat(tmpIndices[j]);
}
let firstIndex: number = 1;
while (firstIndex < previousRank.length) {
firstIndex <<= 1;
}
const treeSize: number = 2 * firstIndex - 1;
firstIndex -= 1;
const tree: number[] = [];
for (let j: number = 0; j < treeSize; ++j) {
tree[j] = 0;
}
for (let j: number = 0; j < indices.length; j++) {
const index: number = indices[j];
let treeIndex: number = index + firstIndex;
++tree[treeIndex];
while (treeIndex > 0) {
if (treeIndex % 2) {
totalCrossings += tree[treeIndex + 1];
}
treeIndex = (treeIndex - 1) >> 1;
++tree[treeIndex];
}
}
return totalCrossings;
}
/**
* Calculates and reduces the crosses between line segments
*
* @returns { void }Calculates and reduces the crosses between line segments.\
* @param {MultiParentModel} model - provide the target value.
* @private
*/
public execute(model: MultiParentModel): void {
// Stores initial ordering
this.nestedBestRanks = [];
for (let i: number = 0; i < model.ranks.length; i++) {
this.nestedBestRanks[i] = model.ranks[i].slice();
}
let iterationsWithoutImprovement: number = 0;
let currentBestCrossings: number = this.calculateCrossings(model);
for (let i: number = 0; i < 24 && iterationsWithoutImprovement < 2; i++) {
this.weightedMedian(i, model);
const candidateCrossings: number = this.calculateCrossings(model);
if (candidateCrossings < currentBestCrossings) {
currentBestCrossings = candidateCrossings;
iterationsWithoutImprovement = 0;
for (let j: number = 0; j < this.nestedBestRanks.length; j++) {
const rank: (IVertex | IEdge)[] = model.ranks[j];
for (let k: number = 0; k < rank.length; k++) {
const cell: IVertex | IEdge = rank[k];
const obj: IVertex = this.nestedBestRanks[j][cell.temp[0]];
let check: boolean = true;
if ((cell as IEdge).edges && obj && !(obj as IEdge).edges) {
check = false;
}
if (obj && check) {
this.nestedBestRanks[j][cell.temp[0]] = cell;
}
}
}
} else {
// Increase count of iterations
iterationsWithoutImprovement++;
// Restore the best values to the cells
for (let j: number = 0; j < this.nestedBestRanks.length; j++) {
const rank: IVertex[] = model.ranks[j];
for (let k: number = 0; k < rank.length; k++) {
const cell: IVertex = rank[k];
this.setTempVariable(cell, j, k);
}
}
}
if (currentBestCrossings === 0) {
break;
}
}
// Store the best rankings but in the model
const ranks: IVertex[][] = [];
const rankList: IVertex[][] = [];
for (let i: number = 0; i < model.maxRank + 1; i++) {
rankList[i] = [];
ranks[i] = rankList[i];
}
for (let i: number = 0; i < this.nestedBestRanks.length; i++) {
for (let j: number = 0; j < this.nestedBestRanks[i].length; j++) {
rankList[i].push(this.nestedBestRanks[i][j]);
}
}
model.ranks = ranks;
}
/**
* check whether the object is vertext or edge on the layout model. \
*
* @returns { boolean } check whether the object is vertext or edge on the layout model..\
* @param {IVertex} node - provide the iteration value.
*
* @private
*/
public isVertex(node: IVertex): boolean {
if (node && node.cell && (node.cell.inEdges || node.cell.outEdges)) {
return true;
}
return false;
}
/**
* used to move up or move down the node position on the adjacent ranks \
*
* @returns { void } used to move up or move down the node position on the adjacent ranks.\
* @param {number} iteration - provide the iteration value.
* @param {MultiParentModel} model - provide the model value.
*
* @private
*/
private weightedMedian(iteration: number, model: MultiParentModel): void {
// Reverse sweep direction each time through this method
const downwardSweep: boolean = (iteration % 2 === 0);
if (downwardSweep) {
for (let j: number = model.maxRank - 1; j >= 0; j--) {
this.medianRank(j, downwardSweep);
}
} else {
for (let j: number = 1; j < model.maxRank; j++) {
this.medianRank(j, downwardSweep);
}
}
}
/**
* used to get the node next(up) connected to the specified node or connector \
*
* @returns { void } calculates the rank elements on the specified rank.\
* @param {IVertex} cell - provide the cell value.
* @param {number} layer - provide the layer value.
* @param {boolean} isPrevious - provide the isPrevious value.
*
* @private
*/
public getConnectedCellsOnLayer(cell: IVertex, layer: number, isPrevious: boolean = false): IVertex[] {
let connectedlayer: string = 'nextLayerConnectedCells';
let connectedAs: string = 'connectsAsTarget';
if (isPrevious) {
connectedlayer = 'previousLayerConnectedCells';
connectedAs = 'connectsAsSource';
}
if (cell) {
if (this.isVertex(cell)) {
if (cell[connectedlayer] == null) {
cell[connectedlayer] = [];
cell[connectedlayer][0] = [];
for (let i: number = 0; i < cell[connectedAs].length; i++) {
const edge: IEdge = cell[connectedAs][i];
if (edge.maxRank === undefined) {
edge.maxRank = -1;
}
if (edge.maxRank === -1 || (isPrevious ? (edge.minRank === layer - 1) : (edge.maxRank === layer + 1))) {
// Either edge is not in any rank or no dummy nodes in edge, add node of other side of edge
cell[connectedlayer][0].push(isPrevious ? edge.target : edge.source);
} else {
// Edge spans at least two layers, add edge
cell[connectedlayer][0].push(edge);
}
}
}
return cell[connectedlayer][0];
} else {
if (cell[connectedlayer] == null) {
cell[connectedlayer] = [];
for (let i: number = 0; i < cell.temp.length; i++) {
cell[connectedlayer][i] = [];
if (i === (isPrevious ? 0 : (cell.temp.length - 1))) {
cell[connectedlayer][i].push(isPrevious ? cell.target : cell.source);
} else {
cell[connectedlayer][i].push(cell);
}
}
}
return cell[connectedlayer][layer - cell.minRank - 1];
}
}
return null;
}
/**
* calculates the rank elements on the specified rank \
*
* @returns { void } calculates the rank elements on the specified rank.\
* @param {IVertex[]} connectedCells - provide the cell value.
* @param {number} rankValue - provide the layer value.
*
* @private
*/
public medianValue(connectedCells: IVertex[], rankValue: number): number {
const medianValues: number[] = [];
let arrayCount: number = 0;
for (let i: number = 0; i < connectedCells.length; i++) {
const cell: IVertex = connectedCells[i];
medianValues[arrayCount++] = this.getTempVariable(cell, rankValue);
}
// sorts numerical order sort
medianValues.sort((a: number, b: number): number => { return a - b; });
if (arrayCount % 2 === 1) {
// For odd numbers of adjacent vertices return the median
return medianValues[Math.floor(arrayCount / 2)];
} else if (arrayCount === 2) {
return ((medianValues[0] + medianValues[1]) / 2.0);
} else {
const medianPoint: number = arrayCount / 2;
const leftMedian: number = medianValues[medianPoint - 1] - medianValues[0];
const rightMedian: number = medianValues[arrayCount - 1]
- medianValues[medianPoint];
return (medianValues[medianPoint - 1] * rightMedian + medianValues[medianPoint] * leftMedian) / (leftMedian + rightMedian);
}
}
/**
* get the temp value of the specified layer \
*
* @returns { void } getDirection method .\
* @param {IVertex} cell - provide the cell value.
* @param {layer} layer - provide the layer value.
* @param {LayoutOrientation} value - provide the value value.
*
* @private
*/
public setTempVariable(cell: IVertex, layer: number, value: number): void {
if (cell) {
cell.temp[0] = value;
}
}
/**
* used to minimize the node position on this rank and one of its adjacent ranks
*/
private medianRank(rankValue: number, downwardSweep: boolean): void {
const numCellsForRank: number = this.nestedBestRanks[rankValue].length;
const medianValues: SortedEntry[] = [];
const reservedPositions: boolean[] = [];
for (let i: number = 0; i < numCellsForRank; i++) {
const cell: IVertex = this.nestedBestRanks[rankValue][i];
const sorterEntry: SortedEntry = { medianValue: 0 };
sorterEntry.cell = cell;
// Flip whether or not equal medians are flipped on up and down sweeps
//TODO re-implement some kind of nudge medianValues[i].nudge = !downwardSweep;
let nextLevelConnectedCells: IVertex[];
if (downwardSweep) {
nextLevelConnectedCells = this.getConnectedCellsOnLayer(cell, rankValue);
} else { nextLevelConnectedCells = this.getConnectedCellsOnLayer(cell, rankValue, true); }
let nextRankValue: number;
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
downwardSweep ? nextRankValue = rankValue + 1 : nextRankValue = rankValue - 1;
if (nextLevelConnectedCells != null && nextLevelConnectedCells.length !== 0) {
sorterEntry.medianValue = this.medianValue(nextLevelConnectedCells, nextRankValue);
medianValues.push(sorterEntry);
} else {
// Nodes with no adjacent vertices are flagged in the reserved array to
//indicate they should be left in their current position.
reservedPositions[this.getTempVariable(cell, rankValue)] = true;
}
}
medianValues.sort(this.compare);
// Set the new position of each node within the rank using its temp variable
for (let i: number = 0; i < numCellsForRank; i++) {
if (reservedPositions[i] == null && medianValues.length > 0) {
const cell: IVertex = medianValues.shift().cell;
this.setTempVariable(cell, rankValue, i);
}
}
}
//compares two values, it sends the values to the compare function,
//and sorts the values according to the returned (negative, zero, positive) value
private compare(a: SortedEntry, b: SortedEntry): number {
if (a != null && b != null) {
if (b.medianValue > a.medianValue) {
return -1;
} else if (b.medianValue < a.medianValue) {
return 1;
}
}
return 0;
}
}
/**
* Each vertex means a node object in diagram
*/
export interface Vertex {
value: string;
geometry: Rect;
name: string;
vertex: boolean;
inEdges: string[];
outEdges: string[];
layoutObjectId?: string;
}
/** @private */
export interface MatrixModelObject {
model: MultiParentModel;
matrix: MatrixObject[];
rowOffset: number[];
}
/** @private */
export interface MatrixObject {
key: number;
value: MatrixCellGroupObject[];
}
interface Margin {
marginX: number;
marginY: number;
}
/**
* Defines the object to represent each placement stage
*/
interface PlacementStage {
marginX?: number;
marginY?: number;
horizontalSpacing?: number;
verticalSpacing?: number;
orientation?: string;
widestRankValue?: number;
model?: MultiParentModel;
jettyPositions?: {};
currentXDelta?: number;
currentYDelta?: number;
maxIterations?: number;
rankSizes?: number[];
rankOffset?: number[];
widestRank?: number;
intraCellSpacing?: number;
}
/**
* Defines the edge that is used to maintain the relationship between internal vertices
*
* @private
*/
export interface IEdge {
x?: number[];
y?: number[];
temp?: number[];
edges?: IConnector[];
ids?: string[];
source?: IVertex;
target?: IVertex;
maxRank?: number;
minRank?: number;
isReversed?: boolean;
previousLayerConnectedCells?: IVertex[][];
nextLayerConnectedCells?: IVertex[][];
width?: number;
height?: number;
}
/**
* Defines the internal vertices that are used in positioning the objects
*
* @private
*/
export interface IVertex {
x?: number[]; y?: number[];
temp?: number[];
cell?: Vertex;
edges?: IConnector[];
id?: string;
connectsAsTarget?: IEdge[];
connectsAsSource?: IEdge[];
hashCode?: number[];
maxRank?: number;
minRank?: number;
width?: number;
height?: number;
//For compilation - _getConnectedCellsOnLayer
source?: IVertex;
target?: IVertex;
layoutObjectId?: string;
ids?: string[];
type?: string;
identicalSibiling?: string[];
}
interface VertexMapper {
map: {};
}
/**
* Defines weighted cell sorter
*/
interface WeightedCellSorter {
cell?: IVertex;
weightedValue?: number;
visited?: boolean;
rankIndex?: number;
}
/**
* Defines sorted entries
*/
interface SortedEntry {
medianValue?: number;
cell?: IVertex;
}
/**
* Defines an object that is used to maintain data in traversing
*/
interface TraverseData {
seenNodes: {};
unseenNodes: {};
rankList?: IVertex[][];
parent?: IVertex;
root?: IVertex;
edge?: IEdge;
}
/**
* Defines the properties of layout
*
* @private
*/
export interface LayoutProp {
orientation?: string;
horizontalSpacing?: number;
verticalSpacing?: number;
marginX: number;
marginY: number;
enableLayoutRouting: boolean;
}
interface Rect {
x: number;
y: number;
width: number;
height: number;
right?: number;
bottom?: number;
left?: number;
}
/**
* Defines the geometry objects for the connectors
*
* @private
*/
interface Geometry {
x: number;
y: number;
width: number;
height: number;
relative: boolean;
points?: PointModel[];
} | the_stack |
import { encodeERC20AssetData } from '@0x/contracts-asset-proxy';
import { BlockchainTestsEnvironment, constants, expect, orderHashUtils, OrderStatus } from '@0x/contracts-test-utils';
import { BatchMatchedFillResults, FillResults, MatchedFillResults, Order, SignedOrder } from '@0x/types';
import { BigNumber } from '@0x/utils';
import { LogWithDecodedArgs, TransactionReceiptWithDecodedLogs } from 'ethereum-types';
import * as _ from 'lodash';
import { Maker } from '../framework/actors/maker';
import { BlockchainBalanceStore } from '../framework/balances/blockchain_balance_store';
import { LocalBalanceStore } from '../framework/balances/local_balance_store';
import { DeploymentManager } from '../framework/deployment_manager';
export interface FillEventArgs {
orderHash: string;
makerAddress: string;
takerAddress: string;
makerAssetFilledAmount: BigNumber;
takerAssetFilledAmount: BigNumber;
makerFeePaid: BigNumber;
takerFeePaid: BigNumber;
protocolFeePaid: BigNumber;
}
export interface MatchTransferAmounts {
// Assets being traded.
leftMakerAssetSoldByLeftMakerAmount: BigNumber; // leftMakerAssetBoughtByRightMakerAmount if omitted.
rightMakerAssetSoldByRightMakerAmount: BigNumber; // rightMakerAssetBoughtByLeftMakerAmount if omitted.
rightMakerAssetBoughtByLeftMakerAmount: BigNumber; // rightMakerAssetSoldByRightMakerAmount if omitted.
leftMakerAssetBoughtByRightMakerAmount: BigNumber; // leftMakerAssetSoldByLeftMakerAmount if omitted.
// Taker profit.
leftMakerAssetReceivedByTakerAmount: BigNumber; // 0 if omitted.
rightMakerAssetReceivedByTakerAmount: BigNumber; // 0 if omitted.
// Maker fees.
leftMakerFeeAssetPaidByLeftMakerAmount: BigNumber; // 0 if omitted.
rightMakerFeeAssetPaidByRightMakerAmount: BigNumber; // 0 if omitted.
// Taker fees.
leftTakerFeeAssetPaidByTakerAmount: BigNumber; // 0 if omitted.
rightTakerFeeAssetPaidByTakerAmount: BigNumber; // 0 if omitted.
// Protocol fees.
leftProtocolFeePaidByTakerInEthAmount: BigNumber; // 0 if omitted
leftProtocolFeePaidByTakerInWethAmount: BigNumber; // 0 if omitted
rightProtocolFeePaidByTakerInWethAmount: BigNumber; // 0 if omitted
rightProtocolFeePaidByTakerInEthAmount: BigNumber; // 0 if omitted
}
export interface MatchResults {
orders: MatchedOrders;
fills: FillEventArgs[];
}
export interface BatchMatchResults {
matches: MatchResults[];
filledAmounts: Array<[SignedOrder, BigNumber, string]>;
leftFilledResults: FillEventArgs[];
rightFilledResults: FillEventArgs[];
}
export interface BatchMatchedOrders {
leftOrders: SignedOrder[];
rightOrders: SignedOrder[];
leftOrdersTakerAssetFilledAmounts: BigNumber[];
rightOrdersTakerAssetFilledAmounts: BigNumber[];
}
export interface MatchedOrders {
leftOrder: SignedOrder;
rightOrder: SignedOrder;
leftOrderTakerAssetFilledAmount?: BigNumber;
rightOrderTakerAssetFilledAmount?: BigNumber;
}
export interface TestMatchOrdersArgs {
env: BlockchainTestsEnvironment;
matchOrderTester: MatchOrderTester;
leftOrder: Partial<Order>;
rightOrder: Partial<Order>;
makerLeft: Maker;
makerRight: Maker;
expectedTransferAmounts: Partial<MatchTransferAmounts>;
withMaximalFill: boolean;
matcherAddress: string;
}
/**
* Tests an order matching scenario with both eth and weth protocol fees.
*/
export async function testMatchOrdersAsync(args: TestMatchOrdersArgs): Promise<void> {
// Create orders to match.
const signedOrderLeft = await args.makerLeft.signOrderAsync(args.leftOrder);
const signedOrderRight = await args.makerRight.signOrderAsync(args.rightOrder);
await args.matchOrderTester.matchOrdersAndAssertEffectsAsync(
{
leftOrder: signedOrderLeft,
rightOrder: signedOrderRight,
},
{
...args.expectedTransferAmounts,
leftProtocolFeePaidByTakerInEthAmount: DeploymentManager.protocolFee,
rightProtocolFeePaidByTakerInEthAmount: DeploymentManager.protocolFee,
leftProtocolFeePaidByTakerInWethAmount: constants.ZERO_AMOUNT,
rightProtocolFeePaidByTakerInWethAmount: constants.ZERO_AMOUNT,
},
args.matcherAddress,
DeploymentManager.protocolFee.times(2),
args.withMaximalFill,
);
await args.env.blockchainLifecycle.revertAsync();
await args.env.blockchainLifecycle.startAsync();
await args.matchOrderTester.matchOrdersAndAssertEffectsAsync(
{
leftOrder: signedOrderLeft,
rightOrder: signedOrderRight,
},
{
...args.expectedTransferAmounts,
leftProtocolFeePaidByTakerInEthAmount: constants.ZERO_AMOUNT,
rightProtocolFeePaidByTakerInEthAmount: constants.ZERO_AMOUNT,
leftProtocolFeePaidByTakerInWethAmount: DeploymentManager.protocolFee,
rightProtocolFeePaidByTakerInWethAmount: DeploymentManager.protocolFee,
},
args.matcherAddress,
constants.ZERO_AMOUNT,
args.withMaximalFill,
);
}
export class MatchOrderTester {
/**
* Constructs new MatchOrderTester.
*/
constructor(
protected readonly _deployment: DeploymentManager,
protected readonly _blockchainBalanceStore: BlockchainBalanceStore,
) {}
/**
* Performs batch order matching on a set of complementary orders and asserts results.
* @param orders The list of orders and filled states
* @param takerAddress Address of taker (the address who matched the two orders)
* @param value The amount of value that should be sent in the contract call.
* @param matchPairs An array of left and right indices that will be used to perform
* the expected simulation.
* @param expectedTransferAmounts Expected amounts transferred as a result of each round of
* order matching. Omitted fields are either set to 0 or their
* complementary field.
* @param withMaximalFill A boolean that indicates whether the "maximal fill" order matching
* strategy should be used.
* @return Results of `batchMatchOrders()`.
*/
public async batchMatchOrdersAndAssertEffectsAsync(
orders: BatchMatchedOrders,
takerAddress: string,
value: BigNumber,
matchPairs: Array<[number, number]>,
expectedTransferAmounts: Array<Partial<MatchTransferAmounts>>,
withMaximalFill: boolean,
): Promise<BatchMatchResults> {
// Ensure that the provided input is valid.
expect(matchPairs.length).to.be.eq(expectedTransferAmounts.length);
expect(orders.leftOrders.length).to.be.eq(orders.leftOrdersTakerAssetFilledAmounts.length);
expect(orders.rightOrders.length).to.be.eq(orders.rightOrdersTakerAssetFilledAmounts.length);
// Ensure that the exchange is in the expected state.
await this._assertBatchOrderStatesAsync(orders);
// Update the blockchain balance store and create a new local balance store
// with the same initial balances.
await this._blockchainBalanceStore.updateBalancesAsync();
const localBalanceStore = LocalBalanceStore.create(this._blockchainBalanceStore);
// Execute `batchMatchOrders()`
let actualBatchMatchResults;
let transactionReceipt;
if (withMaximalFill) {
const tx = this._deployment.exchange.batchMatchOrdersWithMaximalFill(
orders.leftOrders,
orders.rightOrders,
orders.leftOrders.map(order => order.signature),
orders.rightOrders.map(order => order.signature),
);
actualBatchMatchResults = await tx.callAsync({
from: takerAddress,
gasPrice: DeploymentManager.gasPrice,
value,
});
transactionReceipt = await tx.awaitTransactionSuccessAsync({
from: takerAddress,
gasPrice: DeploymentManager.gasPrice,
value,
});
} else {
const tx = this._deployment.exchange.batchMatchOrders(
orders.leftOrders,
orders.rightOrders,
orders.leftOrders.map(order => order.signature),
orders.rightOrders.map(order => order.signature),
);
actualBatchMatchResults = await tx.callAsync({
from: takerAddress,
gasPrice: DeploymentManager.gasPrice,
value,
});
transactionReceipt = await tx.awaitTransactionSuccessAsync({
from: takerAddress,
gasPrice: DeploymentManager.gasPrice,
value,
});
}
// Burn the gas used to execute the transaction in the local balance store.
localBalanceStore.burnGas(takerAddress, DeploymentManager.gasPrice.times(transactionReceipt.gasUsed));
// Simulate the batch order match.
const expectedBatchMatchResults = await this._simulateBatchMatchOrdersAsync(
orders,
takerAddress,
matchPairs,
expectedTransferAmounts,
localBalanceStore,
);
const expectedResults = convertToBatchMatchResults(expectedBatchMatchResults);
expect(actualBatchMatchResults).to.be.eql(expectedResults);
// Validate the simulation against reality.
await this._assertBatchMatchResultsAsync(expectedBatchMatchResults, transactionReceipt, localBalanceStore);
return expectedBatchMatchResults;
}
/**
* Matches two complementary orders and asserts results.
* @param orders The matched orders and filled states.
* @param expectedTransferAmounts Expected amounts transferred as a result of order matching.
* Omitted fields are either set to 0 or their complementary
* field.
* @param takerAddress Address of taker (the address who matched the two orders)
* @param value The amount of value that should be sent in the contract call.
* @param withMaximalFill A boolean that indicates whether the "maximal fill" order matching
* strategy should be used.
* @return Results of `matchOrders()`.
*/
public async matchOrdersAndAssertEffectsAsync(
orders: MatchedOrders,
expectedTransferAmounts: Partial<MatchTransferAmounts>,
takerAddress: string,
value: BigNumber,
withMaximalFill: boolean,
): Promise<MatchResults> {
await this._assertInitialOrderStatesAsync(orders);
// Update the blockchain balance store and create a new local balance store
// with the same initial balances.
await this._blockchainBalanceStore.updateBalancesAsync();
const localBalanceStore = LocalBalanceStore.create(this._blockchainBalanceStore);
// Execute `matchOrders()`
let actualMatchResults;
let transactionReceipt;
if (withMaximalFill) {
const tx = this._deployment.exchange.matchOrdersWithMaximalFill(
orders.leftOrder,
orders.rightOrder,
orders.leftOrder.signature,
orders.rightOrder.signature,
);
actualMatchResults = await tx.callAsync({
from: takerAddress,
gasPrice: DeploymentManager.gasPrice,
value,
});
transactionReceipt = await tx.awaitTransactionSuccessAsync({
from: takerAddress,
gasPrice: DeploymentManager.gasPrice,
value,
});
} else {
const tx = this._deployment.exchange.matchOrders(
orders.leftOrder,
orders.rightOrder,
orders.leftOrder.signature,
orders.rightOrder.signature,
);
actualMatchResults = await tx.callAsync({
from: takerAddress,
gasPrice: DeploymentManager.gasPrice,
value,
});
transactionReceipt = await tx.awaitTransactionSuccessAsync({
from: takerAddress,
gasPrice: DeploymentManager.gasPrice,
value,
});
}
localBalanceStore.burnGas(takerAddress, DeploymentManager.gasPrice.times(transactionReceipt.gasUsed));
// Simulate the fill.
const expectedMatchResults = this._simulateMatchOrders(
orders,
takerAddress,
toFullMatchTransferAmounts(expectedTransferAmounts),
localBalanceStore,
);
const expectedResults = convertToMatchResults(expectedMatchResults);
expect(actualMatchResults).to.be.eql(expectedResults);
// Validate the simulation against reality.
await this._assertMatchResultsAsync(expectedMatchResults, transactionReceipt, localBalanceStore);
return expectedMatchResults;
}
/**
* Simulates matching two orders by transferring amounts defined in
* `transferAmounts` and returns the results.
* @param orders The orders being matched and their filled states.
* @param takerAddress Address of taker (the address who matched the two orders)
* @param transferAmounts Amounts to transfer during the simulation.
* @param localBalanceStore The balance store to use for the simulation.
* @return The new account balances and fill events that occurred during the match.
*/
protected _simulateMatchOrders(
orders: MatchedOrders,
takerAddress: string,
transferAmounts: MatchTransferAmounts,
localBalanceStore: LocalBalanceStore,
): MatchResults {
// prettier-ignore
const matchResults = {
orders: {
leftOrder: orders.leftOrder,
leftOrderTakerAssetFilledAmount:
(orders.leftOrderTakerAssetFilledAmount || constants.ZERO_AMOUNT).plus(
transferAmounts.rightMakerAssetBoughtByLeftMakerAmount,
),
rightOrder: orders.rightOrder,
rightOrderTakerAssetFilledAmount:
(orders.rightOrderTakerAssetFilledAmount || constants.ZERO_AMOUNT).plus(
transferAmounts.leftMakerAssetBoughtByRightMakerAmount,
),
},
fills: simulateFillEvents(orders, takerAddress, transferAmounts),
};
// Right maker asset -> left maker
localBalanceStore.transferAsset(
orders.rightOrder.makerAddress,
orders.leftOrder.makerAddress,
transferAmounts.rightMakerAssetBoughtByLeftMakerAmount,
orders.rightOrder.makerAssetData,
);
if (orders.leftOrder.makerAddress !== orders.leftOrder.feeRecipientAddress) {
// Left maker fees
localBalanceStore.transferAsset(
orders.leftOrder.makerAddress,
orders.leftOrder.feeRecipientAddress,
transferAmounts.leftMakerFeeAssetPaidByLeftMakerAmount,
orders.leftOrder.makerFeeAssetData,
);
}
// Left maker asset -> right maker
localBalanceStore.transferAsset(
orders.leftOrder.makerAddress,
orders.rightOrder.makerAddress,
transferAmounts.leftMakerAssetBoughtByRightMakerAmount,
orders.leftOrder.makerAssetData,
);
if (orders.rightOrder.makerAddress !== orders.rightOrder.feeRecipientAddress) {
// Right maker fees
localBalanceStore.transferAsset(
orders.rightOrder.makerAddress,
orders.rightOrder.feeRecipientAddress,
transferAmounts.rightMakerFeeAssetPaidByRightMakerAmount,
orders.rightOrder.makerFeeAssetData,
);
}
// Left taker profit
localBalanceStore.transferAsset(
orders.leftOrder.makerAddress,
takerAddress,
transferAmounts.leftMakerAssetReceivedByTakerAmount,
orders.leftOrder.makerAssetData,
);
// Right taker profit
localBalanceStore.transferAsset(
orders.rightOrder.makerAddress,
takerAddress,
transferAmounts.rightMakerAssetReceivedByTakerAmount,
orders.rightOrder.makerAssetData,
);
// Left taker fees
localBalanceStore.transferAsset(
takerAddress,
orders.leftOrder.feeRecipientAddress,
transferAmounts.leftTakerFeeAssetPaidByTakerAmount,
orders.leftOrder.takerFeeAssetData,
);
// Right taker fees
localBalanceStore.transferAsset(
takerAddress,
orders.rightOrder.feeRecipientAddress,
transferAmounts.rightTakerFeeAssetPaidByTakerAmount,
orders.rightOrder.takerFeeAssetData,
);
// Protocol Fee
const wethAssetData = encodeERC20AssetData(this._deployment.tokens.weth.address);
localBalanceStore.sendEth(
takerAddress,
this._deployment.staking.stakingProxy.address,
transferAmounts.leftProtocolFeePaidByTakerInEthAmount,
);
localBalanceStore.sendEth(
takerAddress,
this._deployment.staking.stakingProxy.address,
transferAmounts.rightProtocolFeePaidByTakerInEthAmount,
);
localBalanceStore.transferAsset(
takerAddress,
this._deployment.staking.stakingProxy.address,
transferAmounts.leftProtocolFeePaidByTakerInWethAmount,
wethAssetData,
);
localBalanceStore.transferAsset(
takerAddress,
this._deployment.staking.stakingProxy.address,
transferAmounts.rightProtocolFeePaidByTakerInWethAmount,
wethAssetData,
);
return matchResults;
}
/**
* Simulates matching a batch of orders by transferring amounts defined in
* `transferAmounts` and returns the results.
* @param orders The orders being batch matched and their filled states.
* @param takerAddress Address of taker (the address who matched the two orders)
* @param matchPairs The pairs of orders that are expected to be matched.
* @param transferAmounts Amounts to transfer during the simulation.
* @param localBalanceStore The balance store to use for the simulation.
* @return The new account balances and fill events that occurred during the match.
*/
protected async _simulateBatchMatchOrdersAsync(
orders: BatchMatchedOrders,
takerAddress: string,
matchPairs: Array<[number, number]>,
transferAmounts: Array<Partial<MatchTransferAmounts>>,
localBalanceStore: LocalBalanceStore,
): Promise<BatchMatchResults> {
// Initialize variables
let leftIdx = 0;
let rightIdx = 0;
let lastLeftIdx = -1;
let lastRightIdx = -1;
let matchedOrders: MatchedOrders;
const batchMatchResults: BatchMatchResults = {
matches: [],
filledAmounts: [],
leftFilledResults: [],
rightFilledResults: [],
};
// Loop over all of the matched pairs from the round
for (let i = 0; i < matchPairs.length; i++) {
leftIdx = matchPairs[i][0];
rightIdx = matchPairs[i][1];
// Construct a matched order out of the current left and right orders
matchedOrders = {
leftOrder: orders.leftOrders[leftIdx],
rightOrder: orders.rightOrders[rightIdx],
leftOrderTakerAssetFilledAmount: orders.leftOrdersTakerAssetFilledAmounts[leftIdx],
rightOrderTakerAssetFilledAmount: orders.rightOrdersTakerAssetFilledAmounts[rightIdx],
};
// If there has been a match recorded and one or both of the side indices have not changed,
// replace the side's taker asset filled amount
if (batchMatchResults.matches.length > 0) {
if (lastLeftIdx === leftIdx) {
matchedOrders.leftOrderTakerAssetFilledAmount = getLastMatch(
batchMatchResults,
).orders.leftOrderTakerAssetFilledAmount;
} else {
batchMatchResults.filledAmounts.push([
orders.leftOrders[lastLeftIdx],
getLastMatch(batchMatchResults).orders.leftOrderTakerAssetFilledAmount || constants.ZERO_AMOUNT,
'left',
]);
}
if (lastRightIdx === rightIdx) {
matchedOrders.rightOrderTakerAssetFilledAmount = getLastMatch(
batchMatchResults,
).orders.rightOrderTakerAssetFilledAmount;
} else {
batchMatchResults.filledAmounts.push([
orders.rightOrders[lastRightIdx],
getLastMatch(batchMatchResults).orders.rightOrderTakerAssetFilledAmount ||
constants.ZERO_AMOUNT,
'right',
]);
}
}
// Add the latest match to the batch match results
batchMatchResults.matches.push(
this._simulateMatchOrders(
matchedOrders,
takerAddress,
toFullMatchTransferAmounts(transferAmounts[i]),
localBalanceStore,
),
);
// Update the left and right fill results
if (lastLeftIdx === leftIdx) {
addFillResults(batchMatchResults.leftFilledResults[leftIdx], getLastMatch(batchMatchResults).fills[0]);
} else {
batchMatchResults.leftFilledResults.push({ ...getLastMatch(batchMatchResults).fills[0] });
}
if (lastRightIdx === rightIdx) {
addFillResults(
batchMatchResults.rightFilledResults[rightIdx],
getLastMatch(batchMatchResults).fills[1],
);
} else {
batchMatchResults.rightFilledResults.push({ ...getLastMatch(batchMatchResults).fills[1] });
}
lastLeftIdx = leftIdx;
lastRightIdx = rightIdx;
}
for (let i = leftIdx + 1; i < orders.leftOrders.length; i++) {
batchMatchResults.leftFilledResults.push(emptyFillEventArgs());
}
for (let i = rightIdx + 1; i < orders.rightOrders.length; i++) {
batchMatchResults.rightFilledResults.push(emptyFillEventArgs());
}
// The two orders indexed by lastLeftIdx and lastRightIdx were potentially
// filled; however, the TakerAssetFilledAmounts that pertain to these orders
// will not have been added to batchMatchResults, so we need to write them
// here.
batchMatchResults.filledAmounts.push([
orders.leftOrders[lastLeftIdx],
getLastMatch(batchMatchResults).orders.leftOrderTakerAssetFilledAmount || constants.ZERO_AMOUNT,
'left',
]);
batchMatchResults.filledAmounts.push([
orders.rightOrders[lastRightIdx],
getLastMatch(batchMatchResults).orders.rightOrderTakerAssetFilledAmount || constants.ZERO_AMOUNT,
'right',
]);
// Return the batch match results
return batchMatchResults;
}
/**
* Checks that the results of `simulateBatchMatchOrders()` agrees with reality.
* @param batchMatchResults The results of a `simulateBatchMatchOrders()`.
* @param transactionReceipt The transaction receipt of a call to `matchOrders()`.
* @param localBalanceStore The balance store to use during the simulation.
*/
protected async _assertBatchMatchResultsAsync(
batchMatchResults: BatchMatchResults,
transactionReceipt: TransactionReceiptWithDecodedLogs,
localBalanceStore: LocalBalanceStore,
): Promise<void> {
// Ensure that the batchMatchResults contain at least one match
expect(batchMatchResults.matches.length).to.be.gt(0);
// Check the fill events.
assertFillEvents(
batchMatchResults.matches.map(match => match.fills).reduce((total, fills) => total.concat(fills)),
transactionReceipt,
);
// Update the blockchain balance store balances.
await this._blockchainBalanceStore.updateBalancesAsync();
// Ensure that the actual and expected token balances are equivalent.
localBalanceStore.assertEquals(this._blockchainBalanceStore);
// Check the Exchange state.
await this._assertPostBatchExchangeStateAsync(batchMatchResults);
}
/**
* Checks that the results of `simulateMatchOrders()` agrees with reality.
* @param matchResults The results of a `simulateMatchOrders()`.
* @param transactionReceipt The transaction receipt of a call to `matchOrders()`.
* @param localBalanceStore The balance store to use during the simulation.
*/
protected async _assertMatchResultsAsync(
matchResults: MatchResults,
transactionReceipt: TransactionReceiptWithDecodedLogs,
localBalanceStore: LocalBalanceStore,
): Promise<void> {
// Check the fill events.
assertFillEvents(matchResults.fills, transactionReceipt);
// Update the blockchain balance store balances.
await this._blockchainBalanceStore.updateBalancesAsync();
// Check the token balances.
localBalanceStore.assertEquals(this._blockchainBalanceStore);
// Check the Exchange state.
await this._assertPostExchangeStateAsync(matchResults);
}
/**
* Asserts the initial exchange state for batch matched orders.
* @param orders Batch matched orders with intial filled amounts.
*/
private async _assertBatchOrderStatesAsync(orders: BatchMatchedOrders): Promise<void> {
for (let i = 0; i < orders.leftOrders.length; i++) {
await this._assertOrderFilledAmountAsync(
orders.leftOrders[i],
orders.leftOrdersTakerAssetFilledAmounts[i],
'left',
);
}
for (let i = 0; i < orders.rightOrders.length; i++) {
await this._assertOrderFilledAmountAsync(
orders.rightOrders[i],
orders.rightOrdersTakerAssetFilledAmounts[i],
'right',
);
}
}
/**
* Asserts the initial exchange state for matched orders.
* @param orders Matched orders with intial filled amounts.
*/
private async _assertInitialOrderStatesAsync(orders: MatchedOrders): Promise<void> {
const pairs = [
[orders.leftOrder, orders.leftOrderTakerAssetFilledAmount || constants.ZERO_AMOUNT],
[orders.rightOrder, orders.rightOrderTakerAssetFilledAmount || constants.ZERO_AMOUNT],
] as Array<[SignedOrder, BigNumber]>;
await Promise.all(
pairs.map(async ([order, expectedFilledAmount]) => {
const side = order === orders.leftOrder ? 'left' : 'right';
await this._assertOrderFilledAmountAsync(order, expectedFilledAmount, side);
}),
);
}
/**
* Asserts the exchange state after a call to `batchMatchOrders()`.
* @param batchMatchResults Results from a call to `simulateBatchMatchOrders()`.
*/
private async _assertPostBatchExchangeStateAsync(batchMatchResults: BatchMatchResults): Promise<void> {
await this._assertTriplesExchangeStateAsync(batchMatchResults.filledAmounts);
}
/**
* Asserts the exchange state after a call to `matchOrders()`.
* @param matchResults Results from a call to `simulateMatchOrders()`.
*/
private async _assertPostExchangeStateAsync(matchResults: MatchResults): Promise<void> {
const triples = [
[matchResults.orders.leftOrder, matchResults.orders.leftOrderTakerAssetFilledAmount, 'left'],
[matchResults.orders.rightOrder, matchResults.orders.rightOrderTakerAssetFilledAmount, 'right'],
] as Array<[SignedOrder, BigNumber, string]>;
await this._assertTriplesExchangeStateAsync(triples);
}
/**
* Asserts the exchange state represented by provided sequence of triples.
* @param triples The sequence of triples to verifiy. Each triple consists
* of an `order`, a `takerAssetFilledAmount`, and a `side`,
* which will be used to determine if the exchange's state
* is valid.
*/
private async _assertTriplesExchangeStateAsync(triples: Array<[SignedOrder, BigNumber, string]>): Promise<void> {
await Promise.all(
triples.map(async ([order, expectedFilledAmount, side]) => {
expect(['left', 'right']).to.include(side);
await this._assertOrderFilledAmountAsync(order, expectedFilledAmount, side);
}),
);
}
/**
* Asserts that the provided order's fill amount and order status
* are the expected values.
* @param order The order to verify for a correct state.
* @param expectedFilledAmount The amount that the order should
* have been filled.
* @param side The side that the provided order should be matched on.
*/
private async _assertOrderFilledAmountAsync(
order: SignedOrder,
expectedFilledAmount: BigNumber,
side: string,
): Promise<void> {
const orderInfo = await this._deployment.exchange.getOrderInfo(order).callAsync();
// Check filled amount of order.
const actualFilledAmount = orderInfo.orderTakerAssetFilledAmount;
expect(actualFilledAmount, `${side} order final filled amount`).to.be.bignumber.equal(expectedFilledAmount);
// Check status of order.
const expectedStatus = expectedFilledAmount.isGreaterThanOrEqualTo(order.takerAssetAmount)
? OrderStatus.FullyFilled
: OrderStatus.Fillable;
const actualStatus = orderInfo.orderStatus;
expect(actualStatus, `${side} order final status`).to.equal(expectedStatus);
}
}
/**
* Converts a `Partial<MatchTransferAmounts>` to a `MatchTransferAmounts` by
* filling in missing fields with zero.
*/
function toFullMatchTransferAmounts(partial: Partial<MatchTransferAmounts>): MatchTransferAmounts {
// prettier-ignore
return {
leftMakerAssetSoldByLeftMakerAmount:
partial.leftMakerAssetSoldByLeftMakerAmount ||
partial.leftMakerAssetBoughtByRightMakerAmount ||
constants.ZERO_AMOUNT,
rightMakerAssetSoldByRightMakerAmount:
partial.rightMakerAssetSoldByRightMakerAmount ||
partial.rightMakerAssetBoughtByLeftMakerAmount ||
constants.ZERO_AMOUNT,
rightMakerAssetBoughtByLeftMakerAmount:
partial.rightMakerAssetBoughtByLeftMakerAmount ||
partial.rightMakerAssetSoldByRightMakerAmount ||
constants.ZERO_AMOUNT,
leftMakerAssetBoughtByRightMakerAmount: partial.leftMakerAssetBoughtByRightMakerAmount ||
partial.leftMakerAssetSoldByLeftMakerAmount ||
constants.ZERO_AMOUNT,
leftMakerFeeAssetPaidByLeftMakerAmount:
partial.leftMakerFeeAssetPaidByLeftMakerAmount || constants.ZERO_AMOUNT,
rightMakerFeeAssetPaidByRightMakerAmount:
partial.rightMakerFeeAssetPaidByRightMakerAmount || constants.ZERO_AMOUNT,
leftMakerAssetReceivedByTakerAmount:
partial.leftMakerAssetReceivedByTakerAmount || constants.ZERO_AMOUNT,
rightMakerAssetReceivedByTakerAmount:
partial.rightMakerAssetReceivedByTakerAmount || constants.ZERO_AMOUNT,
leftTakerFeeAssetPaidByTakerAmount:
partial.leftTakerFeeAssetPaidByTakerAmount || constants.ZERO_AMOUNT,
rightTakerFeeAssetPaidByTakerAmount:
partial.rightTakerFeeAssetPaidByTakerAmount || constants.ZERO_AMOUNT,
leftProtocolFeePaidByTakerInEthAmount:
partial.leftProtocolFeePaidByTakerInEthAmount || constants.ZERO_AMOUNT,
leftProtocolFeePaidByTakerInWethAmount:
partial.leftProtocolFeePaidByTakerInWethAmount || constants.ZERO_AMOUNT,
rightProtocolFeePaidByTakerInEthAmount:
partial.rightProtocolFeePaidByTakerInEthAmount || constants.ZERO_AMOUNT,
rightProtocolFeePaidByTakerInWethAmount:
partial.rightProtocolFeePaidByTakerInWethAmount || constants.ZERO_AMOUNT,
};
}
/**
* Checks values from the logs produced by Exchange.matchOrders against
* the expected transfer amounts.
* @param orders The matched orders.
* @param transactionReceipt Transaction receipt and logs produced by Exchange.matchOrders.
*/
function assertFillEvents(expectedFills: FillEventArgs[], transactionReceipt: TransactionReceiptWithDecodedLogs): void {
// Extract the actual `Fill` events.
const actualFills = extractFillEventsfromReceipt(transactionReceipt);
expect(actualFills.length, 'wrong number of Fill events').to.be.equal(expectedFills.length);
// Validate event arguments.
const fillPairs = _.zip(expectedFills, actualFills) as Array<[FillEventArgs, FillEventArgs]>;
for (const [expected, actual] of fillPairs) {
const side = expected === expectedFills[0] ? 'Left' : 'Right';
expect(actual.orderHash, `${side} order Fill event orderHash`).to.equal(expected.orderHash);
expect(actual.makerAddress, `${side} order Fill event makerAddress`).to.equal(expected.makerAddress);
expect(actual.takerAddress, `${side} order Fill event takerAddress`).to.equal(expected.takerAddress);
expect(actual.makerAssetFilledAmount, `${side} order Fill event makerAssetFilledAmount`).to.bignumber.equal(
expected.makerAssetFilledAmount,
);
expect(actual.takerAssetFilledAmount, `${side} order Fill event takerAssetFilledAmount`).to.bignumber.equal(
expected.takerAssetFilledAmount,
);
expect(actual.makerFeePaid, `${side} order Fill event makerFeePaid`).to.bignumber.equal(expected.makerFeePaid);
expect(actual.takerFeePaid, `${side} order Fill event takerFeePaid`).to.bignumber.equal(expected.takerFeePaid);
}
}
/**
* Create a pair of `Fill` events for a simulated `matchOrder()`.
*/
function simulateFillEvents(
orders: MatchedOrders,
takerAddress: string,
transferAmounts: MatchTransferAmounts,
): [FillEventArgs, FillEventArgs] {
// prettier-ignore
return [
// Left order Fill
{
orderHash: orderHashUtils.getOrderHashHex(orders.leftOrder),
makerAddress: orders.leftOrder.makerAddress,
takerAddress,
makerAssetFilledAmount: transferAmounts.leftMakerAssetSoldByLeftMakerAmount,
takerAssetFilledAmount: transferAmounts.rightMakerAssetBoughtByLeftMakerAmount,
makerFeePaid: transferAmounts.leftMakerFeeAssetPaidByLeftMakerAmount,
takerFeePaid: transferAmounts.leftTakerFeeAssetPaidByTakerAmount,
protocolFeePaid: transferAmounts.leftProtocolFeePaidByTakerInEthAmount.plus(
transferAmounts.leftProtocolFeePaidByTakerInWethAmount,
),
},
// Right order Fill
{
orderHash: orderHashUtils.getOrderHashHex(orders.rightOrder),
makerAddress: orders.rightOrder.makerAddress,
takerAddress,
makerAssetFilledAmount: transferAmounts.rightMakerAssetSoldByRightMakerAmount,
takerAssetFilledAmount: transferAmounts.leftMakerAssetBoughtByRightMakerAmount,
makerFeePaid: transferAmounts.rightMakerFeeAssetPaidByRightMakerAmount,
takerFeePaid: transferAmounts.rightTakerFeeAssetPaidByTakerAmount,
protocolFeePaid: transferAmounts.rightProtocolFeePaidByTakerInEthAmount.plus(
transferAmounts.rightProtocolFeePaidByTakerInWethAmount,
),
},
];
}
/**
* Extract `Fill` events from a transaction receipt.
*/
function extractFillEventsfromReceipt(receipt: TransactionReceiptWithDecodedLogs): FillEventArgs[] {
interface RawFillEventArgs {
orderHash: string;
makerAddress: string;
takerAddress: string;
makerAssetFilledAmount: string;
takerAssetFilledAmount: string;
makerFeePaid: string;
takerFeePaid: string;
protocolFeePaid: string;
}
const actualFills = (_.filter(receipt.logs, ['event', 'Fill']) as any) as Array<
LogWithDecodedArgs<RawFillEventArgs>
>;
// Convert RawFillEventArgs to FillEventArgs.
return actualFills.map(fill => ({
orderHash: fill.args.orderHash,
makerAddress: fill.args.makerAddress,
takerAddress: fill.args.takerAddress,
makerAssetFilledAmount: new BigNumber(fill.args.makerAssetFilledAmount),
takerAssetFilledAmount: new BigNumber(fill.args.takerAssetFilledAmount),
makerFeePaid: new BigNumber(fill.args.makerFeePaid),
takerFeePaid: new BigNumber(fill.args.takerFeePaid),
protocolFeePaid: new BigNumber(fill.args.protocolFeePaid),
}));
}
/**
* Gets the last match in a BatchMatchResults object.
* @param batchMatchResults The BatchMatchResults object.
* @return The last match of the results.
*/
function getLastMatch(batchMatchResults: BatchMatchResults): MatchResults {
return batchMatchResults.matches[batchMatchResults.matches.length - 1];
}
/**
* Add a new fill results object to a total fill results object destructively.
* @param total The total fill results that should be updated.
* @param fill The new fill results that should be used to accumulate.
*/
function addFillResults(total: FillEventArgs, fill: FillEventArgs): void {
// Ensure that the total and fill are compatibe fill events
expect(total.orderHash).to.be.eq(fill.orderHash);
expect(total.makerAddress).to.be.eq(fill.makerAddress);
expect(total.takerAddress).to.be.eq(fill.takerAddress);
// Add the fill results together
total.makerAssetFilledAmount = total.makerAssetFilledAmount.plus(fill.makerAssetFilledAmount);
total.takerAssetFilledAmount = total.takerAssetFilledAmount.plus(fill.takerAssetFilledAmount);
total.makerFeePaid = total.makerFeePaid.plus(fill.makerFeePaid);
total.takerFeePaid = total.takerFeePaid.plus(fill.takerFeePaid);
total.protocolFeePaid = total.protocolFeePaid.plus(fill.protocolFeePaid);
}
/**
* Converts a BatchMatchResults object to the associated value that correspondes to a value that could be
* returned by `batchMatchOrders` or `batchMatchOrdersWithMaximalFill`.
* @param results The results object to convert
* @return The associated object that can be compared to the return value of `batchMatchOrders`
*/
function convertToBatchMatchResults(results: BatchMatchResults): BatchMatchedFillResults {
// Initialize the results object
const batchMatchedFillResults: BatchMatchedFillResults = {
left: [],
right: [],
profitInLeftMakerAsset: constants.ZERO_AMOUNT,
profitInRightMakerAsset: constants.ZERO_AMOUNT,
};
for (const match of results.matches) {
const leftSpread = match.fills[0].makerAssetFilledAmount.minus(match.fills[1].takerAssetFilledAmount);
// If the left maker spread is positive for match, update the profitInLeftMakerAsset
if (leftSpread.isGreaterThan(constants.ZERO_AMOUNT)) {
batchMatchedFillResults.profitInLeftMakerAsset = batchMatchedFillResults.profitInLeftMakerAsset.plus(
leftSpread,
);
}
const rightSpread = match.fills[1].makerAssetFilledAmount.minus(match.fills[0].takerAssetFilledAmount);
// If the right maker spread is positive for match, update the profitInRightMakerAsset
if (rightSpread.isGreaterThan(constants.ZERO_AMOUNT)) {
batchMatchedFillResults.profitInRightMakerAsset = batchMatchedFillResults.profitInRightMakerAsset.plus(
rightSpread,
);
}
}
for (const fill of results.leftFilledResults) {
batchMatchedFillResults.left.push(convertToFillResults(fill));
}
for (const fill of results.rightFilledResults) {
batchMatchedFillResults.right.push(convertToFillResults(fill));
}
return batchMatchedFillResults;
}
/**
* Converts a MatchResults object to the associated value that correspondes to a value that could be
* returned by `matchOrders` or `matchOrdersWithMaximalFill`.
* @param results The results object to convert
* @return The associated object that can be compared to the return value of `matchOrders`
*/
function convertToMatchResults(result: MatchResults): MatchedFillResults {
// If the left spread is negative, set it to zero
let profitInLeftMakerAsset = result.fills[0].makerAssetFilledAmount.minus(result.fills[1].takerAssetFilledAmount);
if (profitInLeftMakerAsset.isLessThanOrEqualTo(constants.ZERO_AMOUNT)) {
profitInLeftMakerAsset = constants.ZERO_AMOUNT;
}
// If the right spread is negative, set it to zero
let profitInRightMakerAsset = result.fills[1].makerAssetFilledAmount.minus(result.fills[0].takerAssetFilledAmount);
if (profitInRightMakerAsset.isLessThanOrEqualTo(constants.ZERO_AMOUNT)) {
profitInRightMakerAsset = constants.ZERO_AMOUNT;
}
const matchedFillResults: MatchedFillResults = {
left: {
makerAssetFilledAmount: result.fills[0].makerAssetFilledAmount,
takerAssetFilledAmount: result.fills[0].takerAssetFilledAmount,
makerFeePaid: result.fills[0].makerFeePaid,
takerFeePaid: result.fills[0].takerFeePaid,
protocolFeePaid: result.fills[0].protocolFeePaid,
},
right: {
makerAssetFilledAmount: result.fills[1].makerAssetFilledAmount,
takerAssetFilledAmount: result.fills[1].takerAssetFilledAmount,
makerFeePaid: result.fills[1].makerFeePaid,
takerFeePaid: result.fills[1].takerFeePaid,
protocolFeePaid: result.fills[1].protocolFeePaid,
},
profitInLeftMakerAsset,
profitInRightMakerAsset,
};
return matchedFillResults;
}
/**
* Converts a fill event args object to the associated FillResults object.
* @param result The result to be converted to a FillResults object.
* @return The converted value.
*/
function convertToFillResults(result: FillEventArgs): FillResults {
const fillResults: FillResults = {
makerAssetFilledAmount: result.makerAssetFilledAmount,
takerAssetFilledAmount: result.takerAssetFilledAmount,
makerFeePaid: result.makerFeePaid,
takerFeePaid: result.takerFeePaid,
protocolFeePaid: result.protocolFeePaid,
};
return fillResults;
}
/**
* Creates an empty FillEventArgs object.
* @return The empty FillEventArgs object.
*/
function emptyFillEventArgs(): FillEventArgs {
const empty: FillEventArgs = {
orderHash: '',
makerAddress: '',
takerAddress: '',
makerAssetFilledAmount: constants.ZERO_AMOUNT,
takerAssetFilledAmount: constants.ZERO_AMOUNT,
makerFeePaid: constants.ZERO_AMOUNT,
takerFeePaid: constants.ZERO_AMOUNT,
protocolFeePaid: constants.ZERO_AMOUNT,
};
return empty;
}
// tslint:disable-line:max-file-line-count | the_stack |
import {BaseLayout, BaseLayoutOptions} from './BaseLayout';
import {LayoutInfo, Rect, Size} from '@react-stately/virtualizer';
export interface GalleryLayoutOptions extends BaseLayoutOptions {
// /**
// * The card size in the grid.
// */
// cardSize?: 'S' | 'M' | 'L',
/**
* The the default row height. Note this must be larger than the min item height.
* @default 208
*/
idealRowHeight?: number,
/**
* The spacing between items.
* @default 18 x 18
*/
itemSpacing?: Size,
/**
* The vertical padding for an item.
* @default 114
*/
itemPadding?: number,
/**
* Minimum size for a item in the grid.
* @default 136 x 136
*/
minItemSize?: Size,
/**
* Target for adding extra weight to elements during linear partitioning. Anything with an aspect ratio smaler than this value
* will be targeted.
* @type {number}
*/
threshold?: number,
/**
* The margin around the grid view between the edges and the items.
* @default 24
*/
margin?: number // TODO: Perhaps should accept Responsive<DimensionValue>
}
// TODO: copied from V2, update this with the proper spectrum values
// Should these be affected by Scale as well?
const DEFAULT_OPTIONS = {
S: {
idealRowHeight: 112,
minItemSize: new Size(96, 96),
itemSpacing: new Size(8, 16),
// TODO: will need to update as well
itemPadding: 24,
dropSpacing: 50,
margin: 8
},
L: {
idealRowHeight: 208,
minItemSize: new Size(136, 136),
itemSpacing: new Size(18, 18),
// TODO: updated to work with new v3 cards (there is additional space required for the descriptions if there is a description)
itemPadding: 114,
dropSpacing: 100,
margin: 24
}
};
export class GalleryLayout<T> extends BaseLayout<T> {
protected idealRowHeight: number;
protected margin: number;
protected itemSpacing: Size;
itemPadding: number;
protected minItemSize: Size;
protected threshold: number;
constructor(options: GalleryLayoutOptions = {}) {
super(options);
// TODO: restore cardSize option when we support different size cards
let cardSize = 'L';
this.idealRowHeight = options.idealRowHeight || DEFAULT_OPTIONS[cardSize].idealRowHeight;
this.itemSpacing = options.itemSpacing || DEFAULT_OPTIONS[cardSize].itemSpacing;
this.itemPadding = options.itemPadding != null ? options.itemPadding : DEFAULT_OPTIONS[cardSize].itemPadding;
this.minItemSize = options.minItemSize || DEFAULT_OPTIONS[cardSize].minItemSize;
this.threshold = options.threshold || 1;
this.margin = options.margin != null ? options.margin : DEFAULT_OPTIONS[cardSize].margin;
}
get layoutType() {
return 'gallery';
}
/**
* Takes a row of widths and if there are any widths smaller than the min-width, leech width starting from
* the widest in the row until it can't give anymore, then move to the second widest and so forth.
* Do this until all assets meet the min-width.
* */
_distributeWidths(widths) {
// create a copy of the widths array and sort it largest to smallest
let sortedWidths = widths.concat().sort((a, b) => a[1] > b[1] ? -1 : 1);
for (let width of widths) {
// for each width, if it's smaller than the min width
if (width[1] < this.minItemSize.width) {
// then figure out how much smaller
let delta = this.minItemSize.width - width[1];
for (let item of sortedWidths) {
// go from the largest width in the row to the smallest
// if the width is greater than the min width
if (widths[item[0]][1] > this.minItemSize.width) {
// subtract the delta from the width, if it's still greater than the min width
// then we have finished, subtract the delta permanently from that width
if (widths[item[0]][1] - delta > this.minItemSize.width) {
widths[item[0]][1] -= delta;
delta = 0;
break;
} else {
// otherwise, we take as much as we can from the current width and then move on to
// the next largest and take some width from it
let maxChange = widths[item[0]][1] - this.minItemSize.width;
delta -= maxChange;
widths[item[0]][1] -= maxChange;
}
}
}
if (delta > 0) {
return false;
}
// force the width to be the min width that we just rebalanced for
width[1] = this.minItemSize.width;
}
}
return true;
}
buildCollection() {
let visibleWidth = this.virtualizer.visibleRect.width;
let visibleHeight = this.virtualizer.visibleRect.height;
let y = this.margin;
let availableWidth = visibleWidth - this.margin * 2;
// Compute aspect ratios for all of the items, and the total width if all items were on in a single row.
let ratios = [];
let totalWidth = 0;
let minRatio = this.minItemSize.width / this.minItemSize.height;
let maxRatio = availableWidth / this.minItemSize.height;
for (let node of this.collection) {
let ratio = node.props.width / node.props.height;
if (ratio < minRatio) {
ratio = minRatio;
} else if (ratio > maxRatio && ratio !== minRatio) {
ratio = maxRatio;
}
let itemWidth = ratio * this.minItemSize.height;
ratios.push(ratio);
totalWidth += itemWidth;
}
totalWidth += this.itemSpacing.width * (this.collection.size - 1);
// Determine how many rows we'll need, and partition the items into rows
// using the aspect ratios as weights.
let rows = Math.max(1, Math.ceil(totalWidth / availableWidth));
// if the available width can't hold two items, then every item will get its own row
// this leads to a faster run through linear partition and more dependable output for small row widths
if (availableWidth <= (this.minItemSize.width * 2) + (this.itemPadding * 2)) {
rows = this.collection.size;
}
let weightedRatios = ratios.map(ratio => ratio < this.threshold ? ratio + (0.5 * (1 / ratio)) : ratio);
let partition = linearPartition(weightedRatios, rows);
let index = 0;
for (let row of partition) {
// Compute the total weight for this row
let totalWeight = 0;
for (let j = index; j < index + row.length; j++) {
totalWeight += ratios[j];
}
// Determine the row height based on the total available width and weight of this row.
let bestRowHeight = (availableWidth - (row.length - 1) * this.itemSpacing.width) / totalWeight;
// if this is the last row and the row height is >2x the ideal row height, then cap to the ideal height
// probably doing this because if the last row has one extremely tall image, then the row becomes huge
// though that can happen anywhere if a row has lots of tall images... so i'm not sure why this one matters
if (row === partition[partition.length - 1] && bestRowHeight > this.idealRowHeight * 2) {
bestRowHeight = this.idealRowHeight;
}
let itemHeight = Math.round(bestRowHeight) + this.itemPadding;
let x = this.margin;
// if any items are going to end up too small, add a bit of width to them and subtract it from wider objects
let widths = [];
for (let j = index; j < index + row.length; j++) {
let width = Math.round(bestRowHeight * ratios[j]);
widths.push([j - index, width]);
}
this._distributeWidths(widths);
// Create items for this row.
for (let j = index; j < index + row.length; j++) {
let node = this.collection.rows[j];
let itemWidth = Math.max(widths[j - index][1], this.minItemSize.width);
let rect = new Rect(x, y, itemWidth, itemHeight);
let layoutInfo = new LayoutInfo(node.type, node.key, rect);
this.layoutInfos.set(node.key, layoutInfo);
x += itemWidth + this.itemSpacing.width;
}
y += itemHeight + this.itemSpacing.height;
index += row.length;
}
if (this.isLoading) {
let loaderY = y;
let loaderHeight = 60;
// If there aren't any items, make loader take all avaliable room and remove margin from y calculation
// so it doesn't scroll
if (this.collection.size === 0) {
loaderY = 0;
loaderHeight = visibleHeight || 60;
}
let rect = new Rect(0, loaderY, visibleWidth, loaderHeight);
let loader = new LayoutInfo('loader', 'loader', rect);
this.layoutInfos.set('loader', loader);
y = loader.rect.maxY;
}
if (this.collection.size === 0 && !this.isLoading) {
let rect = new Rect(0, 0, visibleWidth, visibleHeight);
let placeholder = new LayoutInfo('placeholder', 'placeholder', rect);
this.layoutInfos.set('placeholder', placeholder);
y = placeholder.rect.maxY;
}
this.contentSize = new Size(visibleWidth, y);
}
}
// https://www8.cs.umu.se/kurser/TDBA77/VT06/algorithms/BOOK/BOOK2/NODE45.HTM
function linearPartition(seq, k) {
let n = seq.length;
if (k <= 0) {
return [];
}
if (k >= n) {
return seq.map(x => [x]);
}
if (n === 1) {
return [seq];
}
let table = Array(n).fill(0).map(() => Array(k).fill(0));
let solution = Array(n - 1).fill(0).map(() => Array(k - 1).fill(0));
for (let i = 0; i < n; i++) {
table[i][0] = seq[i] + (i > 0 ? table[i - 1][0] : 0);
}
for (let i = 0; i < k; i++) {
table[0][i] = seq[0];
}
for (let i = 1; i < n; i++) {
for (let j = 1; j < k; j++) {
let currentMin = 0;
let minX = Infinity;
for (let x = 0; x < i; x++) {
let c1 = table[x][j - 1];
let c2 = table[i][0] - table[x][0];
let cost = Math.max(c1, c2);
if (!x || cost < currentMin) {
currentMin = cost;
minX = x;
}
}
table[i][j] = currentMin;
solution[i - 1][j - 1] = minX;
}
}
n = n - 1;
k = k - 2;
let result = [];
while (k >= 0) {
if (n >= 1) {
let row = [];
for (let i = solution[n - 1][k] + 1; i < n + 1; i++) {
row.push(seq[i]);
}
result.unshift(row);
n = solution[n - 1][k];
}
k--;
}
let row = [];
for (let i = 0; i < n + 1; i++) {
row.push(seq[i]);
}
result.unshift(row);
return result;
} | the_stack |
import {
autoJoin,
chainCommands,
Command,
EditorState,
Fragment,
liftListItem,
liftTarget,
Node,
NodeRange,
NodeSelection,
NodeType,
ReplaceAroundStep,
ResolvedPos,
Schema,
Selection,
sinkListItem,
Slice,
TextSelection,
Transaction,
wrapInList as pmWrapInList,
} from '@bangle.dev/pm';
import {
compose,
extendDispatch,
filter,
findCutBefore,
findParentNode,
findParentNodeOfType,
findPositionOfNodeBefore,
flatten,
GapCursorSelection,
hasParentNodeOfType,
hasVisibleContent,
isEmptySelectionAtStart,
isFirstChildOfParent,
isNodeEmpty,
isRangeOfType,
safeInsert,
sanitiseSelectionMarksForWrapping,
validListParent,
validPos,
} from '@bangle.dev/utils';
import type { MoveDirection } from '@bangle.dev/pm-commands';
import { isNodeTodo, removeTodoCheckedAttr, setTodoCheckedAttr } from './todo';
import { liftFollowingList, liftSelectionList } from './transforms';
const maxIndentation = 4;
// Returns the number of nested lists that are ancestors of the given selection
const numberNestedLists = (
resolvedPos: ResolvedPos,
nodes: Schema['nodes'],
) => {
const { bulletList, orderedList } = nodes;
let count = 0;
for (let i = resolvedPos.depth - 1; i > 0; i--) {
const node = resolvedPos.node(i);
if (node.type === bulletList || node.type === orderedList) {
count += 1;
}
}
return count;
};
const isInsideList = (state: EditorState, listType: NodeType) => {
const { $from } = state.selection;
const parent = $from.node(-2);
const grandGrandParent = $from.node(-3);
return (
(parent && parent.type === listType) ||
(grandGrandParent && grandGrandParent.type === listType)
);
};
const canOutdent = (type?: NodeType) => (state: EditorState) => {
const { parent } = state.selection.$from;
let listItem = type;
if (!listItem) {
({ listItem } = state.schema.nodes);
}
const { paragraph } = state.schema.nodes;
if (state.selection instanceof GapCursorSelection) {
return parent.type === listItem;
}
return (
parent.type === paragraph && hasParentNodeOfType(listItem!)(state.selection)
);
};
/**
* Check if we can sink the list.
* @returns {boolean} - true if we can sink the list
* - false if we reach the max indentation level
*/
function canSink(initialIndentationLevel: number, state: EditorState) {
/*
- Keep going forward in document until indentation of the node is < than the initial
- If indentation is EVER > max indentation, return true and don't sink the list
*/
let currentIndentationLevel: number | null;
let currentPos = state.tr.selection.$to.pos;
do {
const resolvedPos = state.doc.resolve(currentPos);
currentIndentationLevel = numberNestedLists(
resolvedPos,
state.schema.nodes,
);
if (currentIndentationLevel > maxIndentation) {
// Cancel sink list.
// If current indentation less than the initial, it won't be
// larger than the max, and the loop will terminate at end of this iteration
return false;
}
currentPos++;
} while (currentIndentationLevel >= initialIndentationLevel);
return true;
}
export const isInsideListItem = (type: NodeType) => (state: EditorState) => {
const { $from } = state.selection;
let listItem = type;
if (!listItem) {
({ listItem } = state.schema.nodes);
}
const { paragraph } = state.schema.nodes;
if (state.selection instanceof GapCursorSelection) {
return $from.parent.type === listItem;
}
return (
hasParentNodeOfType(listItem)(state.selection) &&
$from.parent.type === paragraph
);
};
// Get the depth of the nearest ancestor list
const rootListDepth = (
type: NodeType,
pos: ResolvedPos,
nodes: Schema['nodes'],
) => {
let listItem = type;
const { bulletList, orderedList } = nodes;
let depth: number | null;
for (let i = pos.depth - 1; i > 0; i--) {
const node = pos.node(i);
if (node.type === bulletList || node.type === orderedList) {
depth = i;
}
if (
node.type !== bulletList &&
node.type !== orderedList &&
node.type !== listItem
) {
break;
}
}
return depth!;
};
function canToJoinToPreviousListItem(state: EditorState) {
const { $from } = state.selection;
const { bulletList, orderedList } = state.schema.nodes;
const $before = state.doc.resolve($from.pos - 1);
let nodeBefore = $before ? $before.nodeBefore : null;
if (state.selection instanceof GapCursorSelection) {
nodeBefore = $from.nodeBefore;
}
return (
!!nodeBefore && [bulletList, orderedList].indexOf(nodeBefore.type) > -1
);
}
/**
* ------------------
* Command Factories
* ------------------
*/
/**
*
* @param {Object} listType bulletList, orderedList,
* @param {Object} itemType 'listItem'
* @param {boolean} todo if true and the final result of toggle is a bulletList
* set `todoChecked` attr for each listItem.
*/
export function toggleList(
listType: NodeType,
itemType?: NodeType,
todo?: boolean,
): Command {
return (state, dispatch, view) => {
const { selection } = state;
const fromNode = selection.$from.node(selection.$from.depth - 2);
const endNode = selection.$to.node(selection.$to.depth - 2);
if (
!fromNode ||
fromNode.type.name !== listType.name ||
!endNode ||
endNode.type.name !== listType.name
) {
return toggleListCommand(listType, todo)(state, dispatch, view);
} else {
// If current ListType is the same as `listType` in arg,
// toggle the list to `p`.
const listItem = itemType ? itemType : state.schema.nodes.listItem;
const depth = rootListDepth(listItem, selection.$to, state.schema.nodes);
let liftFrom = selection.$to.pos;
// I am not fully sure the best solution,
// but if we donot handle the the nodeSelection of itemType
// an incorrect content error in thrown by liftFollowingList.
if (
selection instanceof NodeSelection &&
selection.node.type === listItem
) {
liftFrom =
selection.$from.pos + selection.node.firstChild!.content.size;
}
let baseTr = state.tr;
let tr = liftFollowingList(
listItem,
state,
liftFrom,
selection.$to.end(depth),
depth || 0,
baseTr,
);
tr = liftSelectionList(listItem, state, tr);
if (dispatch) {
dispatch(tr);
}
return true;
}
};
}
function toggleListCommand(listType: NodeType, todo: boolean = false): Command {
/**
* A function which will set todoChecked attribute
* in any of the nodes that have modified on the tr
*/
const setTodoListTr = (schema: Schema) => (tr: Transaction) => {
if (!tr.isGeneric) {
return tr;
}
// The following code gets a list of ranges that were changed
// From wrapDispatchForJoin: https://github.com/prosemirror/prosemirror-commands/blob/e5f8c303be55147086bfe4521cf7419e6effeb8f/src%2Fcommands.js#L495
// and https://discuss.prosemirror.net/t/finding-out-what-changed-in-a-transaction/2372
let ranges: number[] = [];
for (let i = 0; i < tr.mapping.maps.length; i++) {
let map = tr.mapping.maps[i];
for (let j = 0; j < ranges.length; j++) {
ranges[j] = map.map(ranges[j]);
}
map.forEach((_s, _e, from, to) => {
ranges.push(from, to);
});
}
const canBeTodo = (node: Node, parentNode: Node) =>
node.type === schema.nodes.listItem &&
parentNode.type === schema.nodes.bulletList;
for (let i = 0; i < ranges.length; i += 2) {
let from = ranges[i],
to = ranges[i + 1];
tr.doc.nodesBetween(from, to, (node, pos, parentNode) => {
if (pos >= from && pos < to && canBeTodo(node, parentNode)) {
setTodoCheckedAttr(tr, schema, node, pos);
}
});
}
return tr;
};
return function (state, dispatch, view) {
if (dispatch) {
dispatch(
state.tr.setSelection(
adjustSelectionInList(state.doc, state.selection),
),
);
}
if (!view) {
return false;
}
state = view.state;
const { $from, $to } = state.selection;
const isRangeOfSingleType = isRangeOfType(state.doc, $from, $to, listType);
if (isInsideList(state, listType) && isRangeOfSingleType) {
return liftListItems()(state, dispatch);
} else {
// Converts list type e.g. bulletList -> orderedList if needed
if (!isRangeOfSingleType) {
liftListItems()(state, dispatch);
state = view.state;
}
// Remove any invalid marks that are not supported
const tr = sanitiseSelectionMarksForWrapping(state, listType);
if (tr && dispatch) {
dispatch(tr);
state = view.state;
}
// Wraps selection in list
return wrapInList(listType)(
state,
todo ? extendDispatch(dispatch, setTodoListTr(state.schema)) : dispatch,
);
}
};
}
function wrapInList(nodeType: NodeType, attrs?: Node['attrs']): Command {
return autoJoin(
pmWrapInList(nodeType, attrs),
(before, after) => before.type === after.type && before.type === nodeType,
);
}
function liftListItems(): Command {
return function (state, dispatch) {
const { tr } = state;
const { $from, $to } = state.selection;
tr.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {
// Following condition will ensure that block types paragraph, heading, codeBlock, blockquote, panel are lifted.
// isTextblock is true for paragraph, heading, codeBlock.
if (node.isTextblock) {
const sel = new NodeSelection(tr.doc.resolve(tr.mapping.map(pos)));
const range = sel.$from.blockRange(sel.$to);
if (
!range ||
![state.schema.nodes.listItem].includes(sel.$from.parent.type)
) {
return false;
}
const target = range && liftTarget(range);
if (target === undefined || target === null) {
return false;
}
tr.lift(range, target);
}
return;
});
if (dispatch) {
dispatch(tr);
}
return true;
};
}
/**
* Sometimes a selection in the editor can be slightly offset, for example:
* it's possible for a selection to start or end at an empty node at the very end of
* a line. This isn't obvious by looking at the editor and it's likely not what the
* user intended - so we need to adjust the selection a bit in scenarios like that.
*/
function adjustSelectionInList(doc: Node, selection: Selection) {
let { $from, $to } = selection;
const isSameLine = $from.pos === $to.pos;
let startPos = $from.pos;
let endPos = $to.pos;
if (isSameLine && startPos === doc.nodeSize - 3) {
// Line is empty, don't do anything
return selection;
}
// Selection started at the very beginning of a line and therefor points to the previous line.
if ($from.nodeBefore && !isSameLine) {
startPos++;
let node = doc.nodeAt(startPos);
while (!node || (node && !node.isText)) {
startPos++;
node = doc.nodeAt(startPos);
}
}
if (endPos === startPos) {
return new TextSelection(doc.resolve(startPos));
}
return new TextSelection(doc.resolve(startPos), doc.resolve(endPos));
}
export function indentList(type: NodeType) {
const handleTodo = (schema: Schema) => (tr: Transaction) => {
if (!tr.isGeneric) {
return tr;
}
const range = tr.selection.$from.blockRange(
tr.selection.$to,
(node) =>
node.childCount > 0 && node.firstChild!.type === schema.nodes.listItem,
);
if (
!range ||
// we donot have an existing node to check if todo is needed or not
range.startIndex === 0
) {
return tr;
}
const isNodeBeforeATodo = isNodeTodo(
range.parent.child(range.startIndex - 1),
schema,
);
const { parent, startIndex, endIndex } = range;
let offset = 0;
for (let i = startIndex; i < endIndex; i++) {
const child = parent.child(i);
const pos = range.start + offset;
tr = isNodeBeforeATodo
? setTodoCheckedAttr(tr, schema, child, pos)
: removeTodoCheckedAttr(tr, schema, child, pos);
offset += child.nodeSize;
}
return tr;
};
return function indentListCommand(
state: EditorState,
dispatch?: (tr: Transaction) => void,
) {
let listItem = type;
if (!listItem) {
({ listItem } = state.schema.nodes);
}
if (isInsideListItem(listItem)(state)) {
// Record initial list indentation
const initialIndentationLevel = numberNestedLists(
state.selection.$from,
state.schema.nodes,
);
if (canSink(initialIndentationLevel, state)) {
sinkListItem(listItem)(
state,
extendDispatch(dispatch, handleTodo(state.schema)),
);
}
return true;
}
return false;
};
}
export function outdentList(type: NodeType): Command {
return function (state, dispatch, view) {
let listItem = type;
if (!listItem) {
({ listItem } = state.schema.nodes);
}
const { $from, $to } = state.selection;
if (!isInsideListItem(listItem)(state)) {
return false;
}
// if we're backspacing at the start of a list item, unindent it
// take the the range of nodes we might be lifting
// the predicate is for when you're backspacing a top level list item:
// we don't want to go up past the doc node, otherwise the range
// to clear will include everything
let range = $from.blockRange(
$to,
(node) => node.childCount > 0 && node.firstChild!.type === listItem,
);
if (!range) {
return false;
}
const isGreatGrandTodo = isNodeTodo(
state.selection.$from.node(-3),
state.schema,
);
// TODO this is not quite as lean as the indent approach of todo
// check if we need to set todoCheck attribute
if (dispatch && view) {
const grandParent = state.selection.$from.node(-2);
const grandParentPos = state.selection.$from.start(-2);
let tr = state.tr;
for (const { node, pos } of flatten(grandParent, false)) {
const absPos = pos + grandParentPos;
// -1 so that we cover the entire list item
if (
absPos >= state.selection.$from.before(-1) &&
absPos < state.selection.$to.after(-1)
) {
if (isGreatGrandTodo) {
setTodoCheckedAttr(tr, state.schema, node, absPos);
} else {
removeTodoCheckedAttr(tr, state.schema, node, absPos);
}
}
}
dispatch(tr);
state = view.state;
}
const composedCommand = compose(
mergeLists(listItem, range), // 2. Check if I need to merge nearest list
liftListItem, // 1. First lift list item
)(listItem);
return composedCommand(state, dispatch, view);
};
}
/**
* Merge closest bullet list blocks into one
*
* @param {NodeType} listItem
* @param {NodeRange} range
* @returns
*/
function mergeLists(
listItem: NodeType,
range: NodeRange,
): (command: Command) => Command {
return (command: Command) => {
return (state, dispatch, view) => {
const newDispatch = (tr: Transaction) => {
/* we now need to handle the case that we lifted a sublist out,
* and any listItems at the current level get shifted out to
* their own new list; e.g.:
*
* unorderedList
* listItem(A)
* listItem
* unorderedList
* listItem(B)
* listItem(C)
*
* becomes, after unindenting the first, top level listItem, A:
*
* content of A
* unorderedList
* listItem(B)
* unorderedList
* listItem(C)
*
* so, we try to merge these two lists if they're of the same type, to give:
*
* content of A
* unorderedList
* listItem(B)
* listItem(C)
*/
const $start = state.doc.resolve(range.start);
const $end = state.doc.resolve(range.end);
const $join = tr.doc.resolve(tr.mapping.map(range.end - 1));
if (
$join.nodeBefore &&
$join.nodeAfter &&
$join.nodeBefore.type === $join.nodeAfter.type
) {
if (
$end.nodeAfter &&
$end.nodeAfter.type === listItem &&
$end.parent.type === $start.parent.type
) {
tr.join($join.pos);
}
}
if (dispatch) {
dispatch(tr.scrollIntoView());
}
};
return command(state, newDispatch, view);
};
};
}
// Chaining runs each command until one of them returns true
export const backspaceKeyCommand =
(type: NodeType): Command =>
(state, dispatch, view) => {
return chainCommands(
// if we're at the start of a list item, we need to either backspace
// directly to an empty list item above, or outdent this node
filter(
[
isInsideListItem(type),
isEmptySelectionAtStart,
// list items might have multiple paragraphs; only do this at the first one
isFirstChildOfParent,
canOutdent(type),
],
chainCommands(deletePreviousEmptyListItem(type), outdentList(type)),
),
// if we're just inside a paragraph node (or gapcursor is shown) and backspace, then try to join
// the text to the previous list item, if one exists
filter(
[isEmptySelectionAtStart, canToJoinToPreviousListItem],
joinToPreviousListItem(type),
),
)(state, dispatch, view);
};
export function enterKeyCommand(type: NodeType): Command {
return (state, dispatch, view) => {
const { selection } = state;
if (selection.empty) {
const { $from } = selection;
let listItem = type;
if (!listItem) {
({ listItem } = state.schema.nodes);
}
const { codeBlock } = state.schema.nodes;
const node = $from.node($from.depth);
const wrapper = $from.node($from.depth - 1);
if (wrapper && wrapper.type === listItem) {
/** Check if the wrapper has any visible content */
const wrapperHasContent = hasVisibleContent(wrapper);
if (isNodeEmpty(node) && !wrapperHasContent) {
const grandParent = $from.node($from.depth - 3);
// To allow for cases where a non-todo item is nested inside a todo item
// pressing enter should convert that type into a todo listItem and outdent.
if (
isNodeTodo(grandParent, state.schema) &&
!isNodeTodo(wrapper, state.schema)
) {
return outdentList(state.schema.nodes.listItem)(
state,
dispatch,
view,
);
} else {
return outdentList(listItem)(state, dispatch, view);
}
} else if (!hasParentNodeOfType(codeBlock)(selection)) {
return splitListItem(listItem, (node) => {
if (!isNodeTodo(node, state.schema)) {
return node.attrs;
}
return {
...node.attrs,
todoChecked: false,
};
})(state, dispatch);
}
}
}
return false;
};
}
/***
* Implementation taken from PM and mk-2
* Splits the list items, specific implementation take from PM
*
* splitAttrs(node): attrs - if defined the new split item will get attrs returned by this.
* where node is the currently active node.
*/
function splitListItem(
itemType: NodeType,
splitAttrs?: (node: Node) => Node['attrs'],
): Command {
return function (state, dispatch) {
const ref = state.selection;
const $from = ref.$from;
const $to = ref.$to;
const node: Node | null = (ref as any).node;
if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to)) {
return false;
}
const grandParent = $from.node(-1);
if (grandParent.type !== itemType) {
return false;
}
/** --> The following line changed from the original PM implementation to allow list additions with multiple paragraphs */
if (
// @ts-ignore Fragment.content is missing in @types/prosemirror-model
grandParent.content.content.length <= 1 &&
$from.parent.content.size === 0 &&
!(grandParent.content.size === 0)
) {
// In an empty block. If this is a nested list, the wrapping
// list item should be split. Otherwise, bail out and let next
// command handle lifting.
if (
$from.depth === 2 ||
$from.node(-3).type !== itemType ||
$from.index(-2) !== $from.node(-2).childCount - 1
) {
return false;
}
if (dispatch) {
let wrap = Fragment.empty;
const keepItem = $from.index(-1) > 0;
// Build a fragment containing empty versions of the structure
// from the outer list item to the parent node of the cursor
for (
let d = $from.depth - (keepItem ? 1 : 2);
d >= $from.depth - 3;
d--
) {
wrap = Fragment.from($from.node(d).copy(wrap));
}
// Add a second list item with an empty default start node
wrap = wrap.append(Fragment.from(itemType.createAndFill()!));
const tr$1 = state.tr.replace(
$from.before(keepItem ? undefined : -1),
$from.after(-3),
new Slice(wrap, keepItem ? 3 : 2, 2),
);
tr$1.setSelection(
Selection.near(tr$1.doc.resolve($from.pos + (keepItem ? 3 : 2))),
);
dispatch(tr$1.scrollIntoView());
}
return true;
}
const nextType =
$to.pos === $from.end()
? grandParent.contentMatchAt(0).defaultType
: undefined;
const tr = state.tr.delete($from.pos, $to.pos);
const types = [
splitAttrs
? { type: itemType, attrs: splitAttrs(grandParent) }
: undefined,
nextType && { type: nextType },
];
if (dispatch) {
dispatch(tr.split($from.pos, 2, types as any).scrollIntoView());
}
return true;
};
}
function joinToPreviousListItem(type?: NodeType): Command {
return (state, dispatch) => {
let listItem = type;
if (!listItem) {
({ listItem } = state.schema.nodes);
}
const { $from } = state.selection;
const { paragraph, codeBlock, heading, bulletList, orderedList } =
state.schema.nodes;
const isGapCursorShown = state.selection instanceof GapCursorSelection;
const $cutPos = isGapCursorShown ? state.doc.resolve($from.pos + 1) : $from;
let $cut = findCutBefore($cutPos);
if (!$cut) {
return false;
}
// see if the containing node is a list
if (
$cut.nodeBefore &&
[bulletList, orderedList].indexOf($cut.nodeBefore.type) > -1
) {
// and the node after this is a paragraph / codeBlock / heading
if (
$cut.nodeAfter &&
[paragraph, codeBlock, heading].indexOf($cut.nodeAfter.type) > -1
) {
// find the nearest paragraph that precedes this node
let $lastNode = $cut.doc.resolve($cut.pos - 1);
while ($lastNode.parent.type !== paragraph) {
$lastNode = state.doc.resolve($lastNode.pos - 1);
}
let { tr } = state;
if (isGapCursorShown) {
const nodeBeforePos = findPositionOfNodeBefore(tr.selection);
if (typeof nodeBeforePos !== 'number') {
return false;
}
// append the paragraph / codeblock / heading to the list node
const list = $cut.nodeBefore.copy(
$cut.nodeBefore.content.append(
Fragment.from(listItem!.createChecked({}, $cut.nodeAfter)!),
),
);
tr.replaceWith(
nodeBeforePos,
$from.pos + $cut.nodeAfter.nodeSize,
list,
);
} else {
// take the text content of the paragraph and insert after the paragraph up until before the the cut
tr = tr.step(
new ReplaceAroundStep(
$lastNode.pos,
$cut.pos + $cut.nodeAfter.nodeSize,
$cut.pos + 1,
$cut.pos + $cut.nodeAfter.nodeSize - 1,
state.tr.doc.slice($lastNode.pos, $cut.pos),
0,
true,
),
);
}
// find out if there's now another list following and join them
// as in, [list, p, list] => [list with p, list], and we want [joined list]
let $postCut = tr.doc.resolve(
tr.mapping.map($cut.pos + $cut.nodeAfter.nodeSize),
);
if (
$postCut.nodeBefore &&
$postCut.nodeAfter &&
$postCut.nodeBefore.type === $postCut.nodeAfter.type &&
[bulletList, orderedList].indexOf($postCut.nodeBefore.type) > -1
) {
tr = tr.join($postCut.pos);
}
if (dispatch) {
dispatch(tr.scrollIntoView());
}
return true;
}
}
return false;
};
}
function deletePreviousEmptyListItem(type: NodeType): Command {
return (state, dispatch) => {
const { $from } = state.selection;
let listItem = type;
if (!listItem) {
({ listItem } = state.schema.nodes);
}
const $cut = findCutBefore($from);
if (!$cut || !$cut.nodeBefore || !($cut.nodeBefore.type === listItem)) {
return false;
}
const previousListItemEmpty =
$cut.nodeBefore.childCount === 1 &&
$cut.nodeBefore.firstChild!.nodeSize <= 2;
if (previousListItemEmpty) {
const { tr } = state;
if (dispatch) {
dispatch(
tr
.delete($cut.pos - $cut.nodeBefore.nodeSize, $from.pos)
.scrollIntoView(),
);
}
return true;
}
return false;
};
}
export function moveEdgeListItem(
type: NodeType,
dir: MoveDirection = 'UP',
): Command {
const isDown = dir === 'DOWN';
const isItemAtEdge = (state: EditorState) => {
const currentResolved = findParentNodeOfType(type)(state.selection);
if (!currentResolved) {
return false;
}
const currentNode = currentResolved.node;
const { $from } = state.selection;
const parent = $from.node(currentResolved.depth - 1);
const matchedChild = parent && parent[isDown ? 'lastChild' : 'firstChild'];
if (currentNode && matchedChild === currentNode) {
return true;
}
return false;
};
const command: Command = (state, dispatch, view) => {
let listItem = type;
if (!listItem) {
({ listItem } = state.schema.nodes);
}
if (!state.selection.empty) {
return false;
}
const grandParent = findParentNode((node) =>
validListParent(node.type, state.schema.nodes),
)(state.selection);
const parent = findParentNodeOfType(listItem)(state.selection);
if (!(grandParent && grandParent.node) || !(parent && parent.node)) {
return false;
}
// outdent if the not nested list item i.e. top level
if (state.selection.$from.depth === 3) {
return outdentList(listItem)(state, dispatch, view);
}
// If there is only one element, we need to delete the entire
// bulletList/orderedList so as not to leave any empty list behind.
let nodeToRemove = grandParent.node.childCount === 1 ? grandParent : parent;
let tr = state.tr.delete(
nodeToRemove.pos,
nodeToRemove.pos + nodeToRemove.node.nodeSize,
);
// - first // doing a (-1) will move us to end of 'first' hence allowing us to add an item
// - second // start(-3) will give 11 which is the start of this listItem,
// - third{<>}
let insertPos = state.selection.$from.before(-3);
// when going down move the position by the size of remaining content (after deletion)
if (isDown) {
let uncleNodePos = state.selection.$from.after(-3);
insertPos = uncleNodePos - nodeToRemove.node.nodeSize;
let uncle =
validPos(uncleNodePos, state.doc) && state.doc.nodeAt(uncleNodePos);
if (uncle && uncle.type === listItem) {
// Example
// - first
// - second
// - third{<>}
// - uncle
// {x} <== you want to go down here
insertPos += uncle.nodeSize;
}
}
let nodeToInsert = parent.node;
const newTr = safeInsert(nodeToInsert, insertPos)(tr);
// no change hence dont mutate anything
if (newTr === tr) {
return false;
}
if (dispatch) {
dispatch(newTr);
}
return true;
};
return filter([isItemAtEdge], command);
}
export function updateNodeAttrs(
type: NodeType,
cb: (attrs: Node['attrs']) => Node['attrs'],
): Command {
return (state, dispatch) => {
const { $from } = state.selection;
const current = $from.node(-1);
if (current && current.type === type) {
const { tr } = state;
const nodePos = $from.before(-1);
const newAttrs = cb(current.attrs);
if (newAttrs !== current.attrs) {
tr.setNodeMarkup(nodePos, undefined, cb(current.attrs));
dispatch && dispatch(tr);
return true;
}
}
return false;
};
}
export function queryNodeAttrs(type: NodeType) {
return (state: EditorState) => {
const { $from } = state.selection;
const current = $from.node(-1);
if (current && current.type === type) {
return current.attrs;
}
return false;
};
} | the_stack |
import {Storage} from '@google-cloud/storage';
/* eslint-disable-next-line node/no-extraneous-import */
import {Probot, Context} from 'probot';
import {logger} from 'gcf-utils';
import * as helper from './helper';
import {
CONFIG_FILE_NAME,
DEFAULT_CONFIGS,
LABEL_PRODUCT_BY_DEFAULT,
DriftRepo,
DriftApi,
Label,
Config,
} from './helper';
import schema from './config-schema.json';
import {Endpoints} from '@octokit/types';
import {
ConfigChecker,
getConfigWithDefault,
} from '@google-automations/bot-config-utils';
import {syncLabels} from '@google-automations/label-utils';
type IssueResponse = Endpoints['GET /repos/{owner}/{repo}/issues']['response'];
const storage = new Storage();
handler.getDriftFile = async (file: string) => {
const bucket = 'devrel-prod-settings';
const [contents] = await storage.bucket(bucket).file(file).download();
return contents.toString();
};
handler.getDriftRepos = async () => {
const jsonData = await handler.getDriftFile('public_repos.json');
if (!jsonData) {
logger.error(
new Error('public_repos.json downloaded from Cloud Storage was empty')
);
return null;
}
return JSON.parse(jsonData).repos as DriftRepo[];
};
handler.getDriftApis = async () => {
const jsonData = await handler.getDriftFile('apis.json');
if (!jsonData) {
logger.error(
new Error('apis.json downloaded from Cloud Storage was empty')
);
return null;
}
return JSON.parse(jsonData).apis as DriftApi[];
};
handler.addLabeltoRepoAndIssue = async function addLabeltoRepoAndIssue(
owner: string,
repo: string,
issueNumber: number,
issueTitle: string,
driftRepos: DriftRepo[],
context: Context<'pull_request'> | Context<'issues'> | Context<'installation'>
) {
const driftRepo = driftRepos.find(x => x.repo === `${owner}/${repo}`);
const res = await context.octokit.issues
.listLabelsOnIssue({
owner,
repo,
issue_number: issueNumber,
})
.catch(logger.error);
const labelsOnIssue = res ? res.data : undefined;
let wasNotAdded = true;
let autoDetectedLabel: string | undefined;
if (!driftRepo?.github_label) {
logger.info(
`There was no configured match for the repo ${repo}, trying to auto-detect the right label`
);
const apis = await handler.getDriftApis();
autoDetectedLabel = helper.autoDetectLabel(apis, issueTitle);
}
const githubLabel = driftRepo?.github_label || autoDetectedLabel;
if (githubLabel) {
if (labelsOnIssue) {
const foundAPIName = helper.labelExists(labelsOnIssue, githubLabel);
const cleanUpOtherLabels = labelsOnIssue.filter(
(element: Label) =>
element.name?.startsWith('api') &&
element.name !== foundAPIName?.name &&
element.name !== autoDetectedLabel
);
if (!foundAPIName) {
await context.octokit.issues
.addLabels({
owner,
repo,
issue_number: issueNumber,
labels: [githubLabel],
})
.catch(logger.error);
logger.info(
`Label added to ${owner}/${repo} for issue ${issueNumber} is ${githubLabel}`
);
wasNotAdded = false;
}
for (const dirtyLabel of cleanUpOtherLabels) {
await context.octokit.issues
.removeLabel({
owner,
repo,
issue_number: issueNumber,
name: dirtyLabel.name,
})
.catch(logger.error);
}
} else {
await context.octokit.issues
.addLabels({
owner,
repo,
issue_number: issueNumber,
labels: [githubLabel],
})
.catch(logger.error);
logger.info(
`Label added to ${owner}/${repo} for issue ${issueNumber} is ${githubLabel}`
);
wasNotAdded = false;
}
}
if (!wasNotAdded) {
if (driftRepo?.github_label) {
logger.metric('auto-label.label-added', {mode: 'repo-config'});
} else if (autoDetectedLabel) {
logger.metric('auto-label.label-added', {mode: 'autodetect'});
}
}
let foundSamplesTag: Label | undefined;
if (labelsOnIssue) {
foundSamplesTag = labelsOnIssue.find(e => e.name === 'samples');
}
const isSampleIssue =
repo.includes('samples') || issueTitle?.includes('sample');
if (!foundSamplesTag && isSampleIssue) {
await context.octokit.issues
.addLabels({
owner,
repo,
issue_number: issueNumber,
labels: ['samples'],
})
.catch(logger.error);
logger.info(
`Issue ${issueNumber} is in a samples repo but does not have a sample tag, adding it to the repo and issue`
);
logger.metric('auto-label.label-added', {mode: 'samples'});
wasNotAdded = false;
}
return wasNotAdded;
};
// Main job for PRs.
handler.autoLabelOnPR = async function autoLabelOnPR(
context: Context<'pull_request'>,
owner: string,
repo: string,
config: Config
) {
if (config?.enabled === false) {
logger.info(`Skipping for ${owner}/${repo}`);
return;
}
const pull_number = context.payload.pull_request.number;
if (config?.product) {
const driftRepos = await handler.getDriftRepos();
if (!driftRepos) {
return;
}
await handler.addLabeltoRepoAndIssue(
owner,
repo,
pull_number,
context.payload.pull_request.title,
driftRepos,
context
);
}
// Only need to fetch PR contents if config.path or config.language are configured.
if (!config?.path?.pullrequest && !config?.language?.pullrequest) {
return;
}
const filesChanged = await context.octokit.pulls.listFiles({
owner,
repo,
pull_number,
});
const labels = context.payload.pull_request.labels;
const new_labels = [];
// If user has turned on path labels by configuring {path: {pullrequest: false, }}
// By default, this feature is turned off
if (config.path?.pullrequest) {
logger.info(`Labeling path in PR #${pull_number} in ${owner}/${repo}...`);
const path_label = helper.getLabel(filesChanged.data, config.path, 'path');
if (path_label && !helper.labelExists(labels, path_label)) {
logger.info(
`Path label added to PR #${pull_number} in ${owner}/${repo} is ${path_label}`
);
new_labels.push(path_label);
}
}
// If user has turned on language labels by configuring {language: {pullrequest: false,}}
// By default, this feature is turned off
if (config.language?.pullrequest) {
logger.info(
`Labeling language in PR #${pull_number} in ${owner}/${repo}...`
);
const language_label = helper.getLabel(
filesChanged.data,
config.language,
'language'
);
if (language_label && !helper.labelExists(labels, language_label)) {
logger.info(
`Language label added to PR #${pull_number} in ${owner}/${repo} is ${language_label}`
);
new_labels.push(language_label);
}
}
// Update all labels gathered so far if any
if (new_labels.length) {
logger.info(
`Labels added to PR# ${pull_number} in ${owner}/${repo} are ${JSON.stringify(
new_labels
)}`
);
await context.octokit.issues.addLabels({
owner,
repo,
issue_number: pull_number,
labels: new_labels,
});
}
};
/**
* Function updating a stale label on pull request based on configuration values.
* Removes previous staleness label if exists
*/
async function updateStalenessLabel(
context: Context<'pull_request'> | Context<'issues'>,
owner: string,
repo: string,
config: Config
) {
// If user has turned on stale labels by configuring {staleness: {pullrequest: true, old: 60, extraold: 120}}
// By default, this feature is turned off
if (!config.staleness?.pullrequest) {
logger.info(`Staleness feature is disabled for ${owner}/${repo}...`);
return;
}
const old = config.staleness?.old || helper.DEFAULT_DAYS_TO_STALE;
const extraold =
config.staleness?.extraold || helper.DEFAULT_DAYS_TO_STALE * 2;
// Make sure that config is right and if not, set defaults
if (old > extraold || extraold > helper.MAX_DAYS || old <= 0) {
logger.info(
`The staleness config is wrong, old = ${old}, extraold = ${extraold}, bailing...`
);
return;
}
logger.info(
`Running staleness check for ${owner}/${repo}, config: old=${old}, extraold=${extraold}...`
);
for await (const response of context.octokit.paginate.iterator(
context.octokit.rest.issues.listForRepo,
{
owner: owner,
repo: repo,
}
)) {
if (!response || !response.data) {
logger.info(`No active PRs available in ${owner}/${repo}...`);
return;
}
for (const pull of response.data) {
// Skip all non-pull request issues
if (!pull.pull_request) {
continue;
}
logger.info(
`Checking staleness in PR #${pull.number} in ${owner}/${repo}...`
);
let label = null;
const staleLabel = helper.fetchLabelByPrefix(
pull.labels as Label[],
helper.STALE_PREFIX
);
if (helper.isExpiredByDays(pull.created_at, extraold)) {
label = `${helper.STALE_PREFIX} ${helper.EXTRAOLD_LABEL}`;
} else if (helper.isExpiredByDays(pull.created_at, old)) {
label = `${helper.STALE_PREFIX} ${helper.OLD_LABEL}`;
}
if (label && label !== staleLabel?.name) {
// We are going to update a label now, remove an old one if exists
if (staleLabel) {
logger.info(
`Deleting ${staleLabel} in ${owner}/${repo}/${pull.number}...`
);
context.octokit.issues.removeLabel({
owner,
repo,
issue_number: pull.number,
name: staleLabel.name,
});
}
logger.metric('auto-label.label-added', {
repo: `${owner}/${repo}/`,
number: pull.number,
label: label,
mode: 'staledetect',
});
logger.info(`Adding ${label} to ${owner}/${repo}/${pull.number}...`);
await context.octokit.issues.addLabels({
owner,
repo,
issue_number: pull.number,
labels: [label],
});
}
}
}
}
/**
* Function updating a T-shirt size label on pull request if configuration is enabled.
* Removes previous size label if exists
*/
async function updatePullRequestSizeLabel(
context: Context<'pull_request'>,
owner: string,
repo: string,
config: Config
) {
const pull_number = context.payload.pull_request.number;
// Update pull request size label if user has turned on config, product and
// pull request size labels feature by configuring {requestsize: {enabled: true,}}
// By default, this feature is turned off
if (
!config?.product ||
config?.enabled === false ||
!config?.requestsize?.enabled
) {
logger.info(
`Skipping pull request size calculations for PR#${pull_number} in ${owner}/${repo}`
);
return;
}
const filesChanged = await context.octokit.pulls.listFiles({
owner,
repo,
pull_number,
});
logger.info(
`Request size calculation in PR #${pull_number} in ${owner}/${repo}...`
);
let changes = 0;
filesChanged.data.forEach(item => {
changes += item.changes;
});
logger.info(
`Amount of changes in pull request ${pull_number} in ${owner}/${repo} is ${changes}`
);
const pr_size = `${helper.SIZE_PREFIX} ${helper.getPullRequestSize(changes)}`;
const size_label = helper.fetchLabelByPrefix(
context.payload.pull_request.labels,
helper.SIZE_PREFIX
);
if (pr_size !== size_label?.name) {
if (size_label) {
logger.info(
`Deleting ${size_label.name} in ${owner}/${repo}/${pull_number}...`
);
context.octokit.issues.removeLabel({
owner,
repo,
issue_number: pull_number,
name: size_label.name,
});
}
// Update the PR size label
logger.info(
`Request size label added to PR #${pull_number} in ${owner}/${repo}, label is "${pr_size}"`
);
await context.octokit.issues.addLabels({
owner,
repo,
issue_number: pull_number,
labels: [pr_size],
});
}
}
/**
* Main function, responds to label being added
*/
export function handler(app: Probot) {
// Nightly cron that backfills and corrects api labels
// eslint-disable-next-line @typescript-eslint/no-explicit-any
app.on('schedule.repository' as any, async context => {
const owner = context.payload.organization.login;
const repo = context.payload.repository.name;
const config = await getConfigWithDefault<Config>(
context.octokit,
owner,
repo,
CONFIG_FILE_NAME,
DEFAULT_CONFIGS,
{schema: schema}
);
if (!config?.product || config?.enabled === false) {
logger.info(`Skipping for ${owner}/${repo}`);
return;
}
// If the pull request size labeling enabled, update all labels in a repo
// We run it here since the scheduler runs once in a while, so we dont
// need to update labels on pull request change event
if (config?.requestsize?.enabled) {
await syncLabels(
context.octokit,
owner,
repo,
helper.PULL_REQUEST_SIZE_LABELS
);
}
// Update staleness labels on all pull requests in the repo
updateStalenessLabel(context, owner, repo, config);
logger.info(`running for org ${context.payload.cron_org}`);
if (context.payload.cron_org !== owner) {
logger.info(`skipping run for ${context.payload.cron_org}`);
return;
}
const driftRepos = await handler.getDriftRepos();
if (!driftRepos) {
return;
}
//all the issues in the repository
const issues = context.octokit.issues.listForRepo.endpoint.merge({
owner,
repo,
});
let labelWasNotAddedCount = 0;
//goes through issues in repository, adds labels as necessary
for await (const response of context.octokit.paginate.iterator(issues)) {
const issues = response.data as IssueResponse['data'];
for (const issue of issues) {
const wasNotAdded = await handler.addLabeltoRepoAndIssue(
owner,
repo,
issue.number,
issue.title,
driftRepos,
context
);
if (wasNotAdded) {
logger.info(
`label for ${issue.number} in ${owner}/${repo} was not added`
);
labelWasNotAddedCount++;
}
if (labelWasNotAddedCount > 5) {
logger.info(
`${
owner / repo
} has 5 issues where labels were not added; skipping the rest of this repo check.`
);
return;
}
}
}
});
// Labels issues with product labels.
// By default, this is turned on without user configuration.
app.on(['issues.opened', 'issues.reopened'], async context => {
const owner = context.payload.repository.owner.login;
const repo = context.payload.repository.name;
const config = await getConfigWithDefault<Config>(
context.octokit,
owner,
repo,
CONFIG_FILE_NAME,
DEFAULT_CONFIGS,
{schema: schema}
);
const issueNumber = context.payload.issue.number;
if (!config?.product || config?.enabled === false) {
logger.info(`Skipping for ${owner}/${repo}`);
return;
}
const driftRepos = await handler.getDriftRepos();
if (!driftRepos) {
return;
}
await handler.addLabeltoRepoAndIssue(
owner,
repo,
issueNumber,
context.payload.issue.title,
driftRepos,
context
);
});
// Labels pull requests with product, language, and/or path labels.
// By default, product labels are turned on and language/path labels are
// turned off.
app.on(['pull_request.opened', 'pull_request.synchronize'], async context => {
const owner = context.payload.repository.owner.login;
const repo = context.payload.repository.name;
// First check the config schema for PR.
const configChecker = new ConfigChecker<Config>(schema, CONFIG_FILE_NAME);
await configChecker.validateConfigChanges(
context.octokit,
owner,
repo,
context.payload.pull_request.head.sha,
context.payload.pull_request.number
);
const config = await getConfigWithDefault<Config>(
context.octokit,
owner,
repo,
CONFIG_FILE_NAME,
DEFAULT_CONFIGS,
{schema: schema}
);
await updatePullRequestSizeLabel(context, owner, repo, config);
// For the auto label main logic, synchronize event is irrelevant.
if (context.payload.action === 'synchronize') {
return;
}
await handler.autoLabelOnPR(context, owner, repo, config);
});
app.on(['installation.created'], async context => {
const repositories = context.payload.repositories;
const driftRepos = await handler.getDriftRepos();
if (!LABEL_PRODUCT_BY_DEFAULT) return;
if (!driftRepos) return;
if (!repositories) {
logger.info('repositories is undefined, exiting');
return;
}
for await (const repository of repositories) {
const [owner, repo] = repository.full_name.split('/');
const config = await getConfigWithDefault<Config>(
context.octokit,
owner,
repo,
CONFIG_FILE_NAME,
DEFAULT_CONFIGS,
{schema: schema}
);
if (!config?.product) {
break;
}
// goes through issues in repository, adds labels as necessary
for await (const response of context.octokit.paginate.iterator(
context.octokit.issues.listForRepo,
{
owner,
repo,
}
)) {
const issues = response.data;
// goes through each issue in each page
for (const issue of issues) {
await handler.addLabeltoRepoAndIssue(
owner,
repo,
issue.number,
issue.title,
driftRepos,
context
);
}
}
}
});
} | the_stack |
import { expect } from "chai";
import { latLngBounds, point } from "leaflet";
import {
AttributionControlDirective,
EXAMPLE_WMS_LAYER_NAMES,
EXAMPLE_WMS_LAYER_URL,
LatLngBoundsExpression,
LayerGroupProvider,
MapComponent,
MapProvider,
Point,
WmsLayerDirective,
WMSParams,
} from "./index";
import { randomNumber } from "./spec";
function hasAsChild(root: HTMLElement, child: HTMLElement): boolean {
"use strict";
const length: number = root.children.length;
for (let i: number = 0; i < length; i += 1) {
/* istanbul ignore else */
if (root.children.item(i) === child) {
return true;
}
}
return false;
}
describe("WMS-Layer Directive", () => {
let map: MapComponent;
let layer: WmsLayerDirective;
beforeEach(() => {
map = new MapComponent(
{nativeElement: document.createElement("div")},
new LayerGroupProvider(),
new MapProvider(),
);
(map as any)._size = point(100, 100);
(map as any)._pixelOrigin = point(50, 50);
layer = new WmsLayerDirective({ ref: map }, {} as any);
});
describe("[(display)]", () => {
it("should remove DOM container when not displaying", () => {
layer.display = false;
expect(hasAsChild(layer.getPane()!, (layer as any)._container)).to.equal(false);
});
it("should re-add DOM container when display is true again", () => {
layer.display = false;
layer.display = true;
expect(hasAsChild(layer.getPane()!, (layer as any)._container)).to.equal(true);
});
it("should remove EventListeners when not displaying", (done: Mocha.Done) => {
const moveEvents: Array<{fn: () => any}> = (map as any)._events.move;
const length: number = moveEvents.length;
/* tslint:disable:no-string-literal */
const originalEventListener: (event: Event) => void = layer.getEvents!()["move"];
/* tslint:enable */
layer.display = false;
for (let i: number = 0; i < length; i += 1) {
/* istanbul ignore if */
if (moveEvents[i] && moveEvents[i].fn === originalEventListener) {
return done(new Error("There is still an event on listener"));
}
}
done();
});
it("should re-add EventListeners when display is true again", (done: Mocha.Done) => {
const moveEvents: Array<{fn: () => any}> = (map as any)._events.move;
const length: number = moveEvents.length;
/* tslint:disable:no-string-literal */
const originalEventListener: (event: Event) => void = layer.getEvents!()["move"];
/* tslint:enable */
layer.display = false;
layer.display = true;
for (let i: number = 0; i < length; i += 1) {
if (moveEvents[i] && moveEvents[i].fn === originalEventListener) {
return done();
}
}
/* istanbul ignore next */
return done(new Error("There is no event on listener"));
});
it("should set to false by removing from map", (done: Mocha.Done) => {
layer.displayChange.subscribe((eventVal: boolean) => {
expect(eventVal).to.equal(false);
expect(layer.display).to.equal(false);
done();
});
map.removeLayer(layer);
});
it("should set to true when adding to map again", (done: Mocha.Done) => {
map.removeLayer(layer);
layer.displayChange.subscribe((eventVal: boolean) => {
expect(eventVal).to.equal(true);
expect(layer.display).to.equal(true);
done();
});
map.addLayer(layer);
});
});
describe("[(url)]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
layer.url = EXAMPLE_WMS_LAYER_URL;
expect(((layer as any)._url as string)).to.equal(EXAMPLE_WMS_LAYER_URL);
});
it("should be changed in Angular when changing in Angular", () => {
layer.url = EXAMPLE_WMS_LAYER_URL;
expect(layer.url).to.equal(EXAMPLE_WMS_LAYER_URL);
});
it("should be changed in Angular when changing in Leaflet", () => {
layer.setUrl(EXAMPLE_WMS_LAYER_URL);
expect(layer.url).to.equal(EXAMPLE_WMS_LAYER_URL);
});
it("should fire an event when changing in Angular", (done: Mocha.Done) => {
layer.urlChange.subscribe((eventVal: string) => {
expect(eventVal).to.equal(EXAMPLE_WMS_LAYER_URL);
return done();
});
layer.url = EXAMPLE_WMS_LAYER_URL;
});
it("should fire an event when changing in Leaflet", (done: Mocha.Done) => {
layer.url = EXAMPLE_WMS_LAYER_URL;
layer.urlChange.subscribe((eventVal: string) => {
expect(eventVal).to.equal(EXAMPLE_WMS_LAYER_URL + "?test");
return done();
});
layer.setUrl(EXAMPLE_WMS_LAYER_URL + "?test");
});
it("should not emit anything when changing into same url", (done: Mocha.Done) => {
layer.setUrl(EXAMPLE_WMS_LAYER_URL);
setTimeout(() => {
/* istanbul ignore next */
layer.urlChange.subscribe(() => {
return done(new Error("Event fired"));
});
layer.setUrl(EXAMPLE_WMS_LAYER_URL);
return done();
}, 0);
});
});
describe("[(opacity)]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const val: number = randomNumber();
layer.opacity = val;
expect(layer.options.opacity).to.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const val: number = randomNumber();
layer.opacity = val;
expect(layer.opacity).to.equal(val);
});
it("should be changed in Angular when changing in Leaflet", () => {
const val: number = randomNumber();
layer.setOpacity(val);
expect(layer.opacity).to.equal(val);
});
it("should fire an event when changing in Angular", (done: Mocha.Done) => {
const val: number = randomNumber();
layer.opacityChange.subscribe((eventVal: number) => {
expect(eventVal).to.equal(val);
return done();
});
layer.opacity = val;
});
it("should fire an event when changing in Leaflet", (done: Mocha.Done) => {
const val: number = randomNumber();
layer.opacityChange.subscribe((eventVal: number) => {
expect(eventVal).to.equal(val);
return done();
});
layer.setOpacity(val);
});
});
describe("[(zIndex)]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const val: number = randomNumber(255, 0, 0);
layer.zIndex = val;
expect(layer.options.zIndex).to.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const val: number = randomNumber(255, 0, 0);
layer.zIndex = val;
expect(layer.zIndex).to.equal(val);
});
it("should be changed in Angular when changing in Leaflet", () => {
const val: number = randomNumber(255, 0, 0);
layer.setZIndex(val);
expect(layer.zIndex).to.equal(val);
});
it("should fire an event when changing in Angular", (done: Mocha.Done) => {
const val: number = randomNumber(255, 0, 0);
layer.zIndexChange.subscribe((eventVal: number) => {
expect(eventVal).to.equal(val);
return done();
});
layer.zIndex = val;
});
it("should fire an event when changing in Leaflet", (done: Mocha.Done) => {
const val: number = randomNumber(255, 0, 0);
layer.zIndexChange.subscribe((eventVal: number) => {
expect(eventVal).to.equal(val);
return done();
});
layer.setZIndex(val);
});
});
describe("[(layers)]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
layer.layers = EXAMPLE_WMS_LAYER_NAMES;
expect(layer.wmsParams.layers).to.equal(EXAMPLE_WMS_LAYER_NAMES.join(","));
});
it("should be changed in Angular when changing in Angular", () => {
layer.layers = EXAMPLE_WMS_LAYER_NAMES;
expect(layer.layers).to.deep.equal(EXAMPLE_WMS_LAYER_NAMES);
});
it("should be changed in Angular when changing in Leaflet", () => {
layer.setParams({layers: EXAMPLE_WMS_LAYER_NAMES.join(",")});
expect(layer.layers).to.deep.equal(EXAMPLE_WMS_LAYER_NAMES);
});
it("should fire an event when changing in Angular", (done: Mocha.Done) => {
layer.layersChange.subscribe((eventVal: string[]) => {
expect(eventVal).to.deep.equal(EXAMPLE_WMS_LAYER_NAMES);
return done();
});
layer.layers = EXAMPLE_WMS_LAYER_NAMES;
});
it("should fire an event when changing in Leaflet", (done: Mocha.Done) => {
layer.layersChange.subscribe((eventVal: string[]) => {
expect(eventVal).to.deep.equal(EXAMPLE_WMS_LAYER_NAMES);
return done();
});
layer.setParams({layers: EXAMPLE_WMS_LAYER_NAMES.join(",")});
});
});
describe("[(styles)]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
layer.styles = EXAMPLE_WMS_LAYER_NAMES;
expect(layer.wmsParams.styles).to.equal(EXAMPLE_WMS_LAYER_NAMES.join(","));
});
it("should be changed in Angular when changing in Angular", () => {
layer.styles = EXAMPLE_WMS_LAYER_NAMES;
expect(layer.styles).to.deep.equal(EXAMPLE_WMS_LAYER_NAMES);
});
it("should be changed in Angular when changing in Leaflet", () => {
const params: WMSParams = Object.create(layer.wmsParams);
params.styles = EXAMPLE_WMS_LAYER_NAMES.join(",");
layer.setParams(params);
expect(layer.styles).to.deep.equal(EXAMPLE_WMS_LAYER_NAMES);
});
it("should fire an event when changing in Angular", (done: Mocha.Done) => {
layer.stylesChange.subscribe((eventVal: string[]) => {
expect(eventVal).to.deep.equal(EXAMPLE_WMS_LAYER_NAMES);
return done();
});
layer.styles = EXAMPLE_WMS_LAYER_NAMES;
});
it("should fire an event when changing in Leaflet", (done: Mocha.Done) => {
layer.stylesChange.subscribe((eventVal: string[]) => {
expect(eventVal).to.deep.equal(EXAMPLE_WMS_LAYER_NAMES);
return done();
});
const params: WMSParams = Object.create(layer.wmsParams);
params.styles = EXAMPLE_WMS_LAYER_NAMES.join(",");
layer.setParams(params);
});
});
describe("[(transparent)]", () => {
it("should be changed to false in Leaflet when changing in Angular to false", () => {
layer.transparent = false;
expect(layer.wmsParams.transparent).to.equal(false);
});
it("should be changed to true in Leaflet when changing in Angular to true", () => {
layer.wmsParams.transparent = false;
layer.transparent = true;
expect(layer.wmsParams.transparent).to.equal(true);
});
it("should be changed in Angular to false when changing in Angular to false", () => {
layer.transparent = false;
expect(layer.transparent).to.equal(false);
});
it("should be changed in Angular to true when changing in Angular to true", () => {
layer.transparent = true;
expect(layer.transparent).to.equal(true);
});
it("should be changed in Angular to false when changing in Leaflet to false", () => {
const params: WMSParams = Object.create(layer.wmsParams);
params.transparent = false;
layer.setParams(params);
expect(layer.transparent).to.equal(false);
});
it("should be changed in Angular to true when changing in Leaflet to true", () => {
const params: WMSParams = Object.create(layer.wmsParams);
params.transparent = true;
layer.setParams(params);
expect(layer.transparent).to.equal(true);
});
it("should fire an event when changing in Angular", (done: Mocha.Done) => {
layer.transparentChange.subscribe((eventVal: boolean) => {
expect(eventVal).to.equal(true);
return done();
});
layer.transparent = true;
});
it("should fire an event when changing in Leaflet", (done: Mocha.Done) => {
layer.layers = EXAMPLE_WMS_LAYER_NAMES;
layer.transparentChange.subscribe((eventVal: boolean) => {
expect(eventVal).to.equal(true);
return done();
});
const params: WMSParams = Object.create(layer.wmsParams);
params.transparent = true;
layer.setParams(params);
});
});
describe("[(format)]", () => {
const FORMAT: string = "image/png";
it("should be changed in Leaflet when changing in Angular", () => {
layer.format = FORMAT;
expect(layer.wmsParams.format).to.equal(FORMAT);
});
it("should be changed in Angular when changing in Angular", () => {
layer.format = FORMAT;
expect(layer.format).to.equal(FORMAT);
});
it("should be changed in Angular when changing in Leaflet", () => {
const params: WMSParams = Object.create(layer.wmsParams);
params.format = FORMAT;
layer.setParams(params);
expect(layer.format).to.equal(FORMAT);
});
it("should fire an event when changing in Angular", (done: Mocha.Done) => {
layer.formatChange.subscribe((eventVal: string) => {
expect(eventVal).to.equal(FORMAT);
return done();
});
layer.format = FORMAT;
});
it("should fire an event when changing in Leaflet", (done: Mocha.Done) => {
layer.formatChange.subscribe((eventVal: string) => {
expect(eventVal).to.equal(FORMAT);
return done();
});
const params: WMSParams = Object.create(layer.wmsParams);
params.format = FORMAT;
layer.setParams(params);
});
});
describe("[(version)]", () => {
const VERSION: string = "1.0.0";
it("should be changed in Leaflet when changing in Angular", () => {
layer.version = VERSION;
expect(layer.wmsParams.version).to.equal(VERSION);
});
it("should be changed in Angular when changing in Angular", () => {
layer.version = VERSION;
expect(layer.version).to.equal(VERSION);
});
it("should be changed in Angular when changing in Leaflet", () => {
const params: WMSParams = Object.create(layer.wmsParams);
params.version = VERSION;
layer.setParams(params);
expect(layer.version).to.equal(VERSION);
});
it("should fire an event when changing in Angular", (done: Mocha.Done) => {
layer.versionChange.subscribe((eventVal: string) => {
expect(eventVal).to.equal(VERSION);
return done();
});
layer.version = VERSION;
});
it("should fire an event when changing in Leaflet", (done: Mocha.Done) => {
layer.versionChange.subscribe((eventVal: string) => {
expect(eventVal).to.equal(VERSION);
return done();
});
const params: WMSParams = Object.create(layer.wmsParams);
params.version = VERSION;
layer.setParams(params);
});
});
// Events
describe("(add)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.addEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("add", testEvent);
});
});
describe("(remove)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.removeEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("remove", testEvent);
});
});
describe("(popupopen)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.popupopenEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("popupopen", testEvent);
});
});
describe("(popupclose)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.popupcloseEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("popupclose", testEvent);
});
});
describe("(tooltipopen)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.tooltipopenEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("tooltipopen", testEvent);
});
});
describe("(tooltipclose)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.tooltipcloseEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("tooltipclose", testEvent);
});
});
describe("(click)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.clickEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("click", testEvent);
});
});
describe("(dblclick)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.dblclickEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("dblclick", testEvent);
});
});
describe("(mousedown)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.mousedownEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("mousedown", testEvent);
});
});
describe("(mouseover)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.mouseoverEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("mouseover", testEvent);
});
});
describe("(mouseout)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.mouseoutEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("mouseout", testEvent);
});
});
describe("(contextmenu)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.contextmenuEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("contextmenu", testEvent);
});
});
describe("(loading)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.loadingEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("loading", testEvent);
});
});
describe("(tileunload)", () => {
beforeEach(() => {
layer.off("tileunload", (layer as any)._onTileRemove); // Hack to disable another listener
});
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.tileunloadEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("tileunload", testEvent);
});
});
describe("(tileloadstart)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.tileloadstartEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("tileloadstart", testEvent);
});
});
describe("(tileerror)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
layer.tileerrorEvent.subscribe((event: any) => {
expect(event.testHandle).to.equal(testEvent.testHandle);
return done();
});
layer.fire("tileerror", testEvent);
});
});
describe("(tileload)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { testHandle };
let called: boolean; // this event is called multiple times in the life-circle of leaflet
setTimeout(() => {
layer.tileloadEvent.subscribe((event: any) => {
/* istanbul ignore if */
if (called) {
return;
}
expect(event.testHandle).to.equal(testEvent.testHandle);
called = true;
return done();
});
layer.fire("tileload", testEvent);
}, 1);
});
});
describe("(load)", () => {
it("should fire event in Angular when firing event in Leaflet", (done: Mocha.Done) => {
const testHandle: any = {};
const testEvent: any = { target: layer, testHandle, type: "load" };
let called: boolean; // this event is called multiple times in the life-circle of leaflet
setTimeout(() => {
layer.loadEvent.subscribe((event: any) => {
/* istanbul ignore if */
if (called) {
return;
}
expect(event.testHandle).to.equal(testEvent.testHandle);
called = true;
return done();
});
layer.fire("load", testEvent);
}, 1);
});
});
// Inputs
describe("[tileSize]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const num: number = randomNumber(1000, 1, 0);
const val: Point = point(num, num);
layer.tileSize = val;
expect(layer.options.tileSize).to.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const num: number = randomNumber(1000, 1, 0);
const val: Point = point(num, num);
layer.tileSize = val;
expect(layer.tileSize).to.equal(val);
});
});
describe("[bounds]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const num: number = randomNumber(1000, 1, 0);
const val: LatLngBoundsExpression = latLngBounds([num, num], [num, num]);
layer.bounds = val;
expect(layer.options.bounds).to.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const num: number = randomNumber(1000, 1, 0);
const val: LatLngBoundsExpression = latLngBounds([num, num], [num, num]);
layer.bounds = val;
expect(layer.bounds).to.equal(val);
});
});
describe("[subdomains]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const val: string[] = ["a", "b", "c", "d"];
layer.subdomains = val;
expect(layer.options.subdomains).to.deep.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const val: string[] = ["a", "b", "c", "d"];
layer.subdomains = val;
expect(layer.subdomains).to.deep.equal(val);
});
it("should get an array of strings even if it has a string value", () => {
const val: string = "abcdefg";
layer.options.subdomains = val;
expect(layer.subdomains).to.deep.equal(val.split(""));
});
});
describe("[className]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const val: string = "test-class";
layer.className = val;
expect(layer.options.className).to.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const val: string = "test-class";
layer.className = val;
expect(layer.className).to.equal(val);
});
});
describe("[errorTileUrl]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const val: string = "http://test";
layer.errorTileUrl = val;
expect(layer.options.errorTileUrl).to.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const val: string = "http://test";
layer.errorTileUrl = val;
expect(layer.errorTileUrl).to.equal(val);
});
});
describe("[updateInterval]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const val: number = randomNumber(100, 1, 0);
layer.updateInterval = val;
expect(layer.options.updateInterval).to.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const val: number = randomNumber(100, 1, 0);
layer.updateInterval = val;
expect(layer.updateInterval).to.equal(val);
});
});
describe("[keepBuffer]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const val: number = randomNumber(100, 1, 0);
layer.keepBuffer = val;
expect(layer.options.keepBuffer).to.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const val: number = randomNumber(100, 1, 0);
layer.keepBuffer = val;
expect(layer.keepBuffer).to.equal(val);
});
});
describe("[maxZoom]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const val: number = randomNumber(20, 0, 0);
layer.maxZoom = val;
expect(layer.options.maxZoom).to.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const val: number = randomNumber(20, 0, 0);
layer.maxZoom = val;
expect(layer.maxZoom).to.equal(val);
});
});
describe("[minZoom]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const val: number = randomNumber(5, 0, 0);
layer.minZoom = val;
expect(layer.options.minZoom).to.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const val: number = randomNumber(5, 0, 0);
layer.minZoom = val;
expect(layer.minZoom).to.equal(val);
});
});
describe("[maxNativeZoom]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const val: number = randomNumber(100, 1, 0);
layer.maxNativeZoom = val;
expect(layer.options.maxNativeZoom).to.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const val: number = randomNumber(100, 1, 0);
layer.maxNativeZoom = val;
expect(layer.maxNativeZoom).to.equal(val);
});
});
describe("[minNativeZoom]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const val: number = Math.ceil(Math.random() * 5);
layer.minNativeZoom = val;
expect(layer.options.minNativeZoom).to.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const val: number = Math.ceil(Math.random() * 5);
layer.minNativeZoom = val;
expect(layer.minNativeZoom).to.equal(val);
});
});
describe("[zoomOffset]", () => {
it("should be changed in Leaflet when changing in Angular", () => {
const val: number = randomNumber(100, 1, 0);
layer.zoomOffset = val;
expect(layer.options.zoomOffset).to.equal(val);
});
it("should be changed in Angular when changing in Angular", () => {
const val: number = randomNumber(100, 1, 0);
layer.zoomOffset = val;
expect(layer.zoomOffset).to.equal(val);
});
});
describe("[tms]", () => {
it("should be changed to false in Leaflet when changing in Angular to false", () => {
layer.tms = false;
expect(layer.options.tms).to.equal(false);
});
it("should be changed to true in Leaflet when changing in Angular to true", () => {
layer.options.tms = false;
layer.tms = true;
expect(layer.options.tms).to.equal(true);
});
it("should be changed in Angular to false when changing in Angular to false", () => {
layer.tms = false;
expect(layer.tms).to.equal(false);
});
it("should be changed in Angular to true when changing in Angular to true", () => {
layer.tms = true;
expect(layer.tms).to.equal(true);
});
});
describe("[zoomReverse]", () => {
it("should be changed to false in Leaflet when changing in Angular to false", () => {
layer.zoomReverse = false;
expect(layer.options.zoomReverse).to.equal(false);
});
it("should be changed to true in Leaflet when changing in Angular to true", () => {
layer.options.zoomReverse = false;
layer.zoomReverse = true;
expect(layer.options.zoomReverse).to.equal(true);
});
it("should be changed in Angular to false when changing in Angular to false", () => {
layer.zoomReverse = false;
expect(layer.zoomReverse).to.equal(false);
});
it("should be changed in Angular to true when changing in Angular to true", () => {
layer.zoomReverse = true;
expect(layer.zoomReverse).to.equal(true);
});
});
describe("[detectRetina]", () => {
it("should be changed to false in Leaflet when changing in Angular to false", () => {
layer.detectRetina = false;
expect(layer.options.detectRetina).to.equal(false);
});
it("should be changed to true in Leaflet when changing in Angular to true", () => {
layer.options.detectRetina = false;
layer.detectRetina = true;
expect(layer.options.detectRetina).to.equal(true);
});
it("should be changed in Angular to false when changing in Angular to false", () => {
layer.detectRetina = false;
expect(layer.detectRetina).to.equal(false);
});
it("should be changed in Angular to true when changing in Angular to true", () => {
layer.detectRetina = true;
expect(layer.detectRetina).to.equal(true);
});
});
describe("[crossOrigin]", () => {
it("should be changed to false in Leaflet when changing in Angular to false", () => {
layer.crossOrigin = false;
expect(layer.options.crossOrigin).to.equal(false);
});
it("should be changed to true in Leaflet when changing in Angular to true", () => {
layer.options.crossOrigin = false;
layer.crossOrigin = true;
expect(layer.options.crossOrigin).to.equal(true);
});
it("should be changed in Angular to false when changing in Angular to false", () => {
layer.crossOrigin = false;
expect(layer.crossOrigin).to.equal(false);
});
it("should be changed in Angular to true when changing in Angular to true", () => {
layer.crossOrigin = true;
expect(layer.crossOrigin).to.equal(true);
});
});
describe("[updateWhenIdle]", () => {
it("should be changed to false in Leaflet when changing in Angular to false", () => {
layer.updateWhenIdle = false;
expect(layer.options.updateWhenIdle).to.equal(false);
});
it("should be changed to true in Leaflet when changing in Angular to true", () => {
layer.options.updateWhenIdle = false;
layer.updateWhenIdle = true;
expect(layer.options.updateWhenIdle).to.equal(true);
});
it("should be changed in Angular to false when changing in Angular to false", () => {
layer.updateWhenIdle = false;
expect(layer.updateWhenIdle).to.equal(false);
});
it("should be changed in Angular to true when changing in Angular to true", () => {
layer.updateWhenIdle = true;
expect(layer.updateWhenIdle).to.equal(true);
});
});
describe("[updateWhenZooming]", () => {
it("should be changed to false in Leaflet when changing in Angular to false", () => {
layer.updateWhenZooming = false;
expect(layer.options.updateWhenZooming).to.equal(false);
});
it("should be changed to true in Leaflet when changing in Angular to true", () => {
layer.options.updateWhenZooming = false;
layer.updateWhenZooming = true;
expect(layer.options.updateWhenZooming).to.equal(true);
});
it("should be changed in Angular to false when changing in Angular to false", () => {
layer.updateWhenZooming = false;
expect(layer.updateWhenZooming).to.equal(false);
});
it("should be changed in Angular to true when changing in Angular to true", () => {
layer.updateWhenZooming = true;
expect(layer.updateWhenZooming).to.equal(true);
});
});
describe("[noWrap]", () => {
it("should be changed to false in Leaflet when changing in Angular to false", () => {
layer.noWrap = false;
expect(layer.options.noWrap).to.equal(false);
});
it("should be changed to true in Leaflet when changing in Angular to true", () => {
layer.options.noWrap = false;
layer.noWrap = true;
expect(layer.options.noWrap).to.equal(true);
});
it("should be changed in Angular to false when changing in Angular to false", () => {
layer.noWrap = false;
expect(layer.noWrap).to.equal(false);
});
it("should be changed in Angular to true when changing in Angular to true", () => {
layer.noWrap = true;
expect(layer.noWrap).to.equal(true);
});
});
describe("[uppercase]", () => {
it("should be changed to false in Leaflet when changing in Angular to false", () => {
layer.uppercase = false;
expect(layer.options.uppercase).to.equal(false);
});
it("should be changed to true in Leaflet when changing in Angular to true", () => {
layer.options.uppercase = false;
layer.uppercase = true;
expect(layer.options.uppercase).to.equal(true);
});
it("should be changed in Angular to false when changing in Angular to false", () => {
layer.uppercase = false;
expect(layer.uppercase).to.equal(false);
});
it("should be changed in Angular to true when changing in Angular to true", () => {
layer.uppercase = true;
expect(layer.uppercase).to.equal(true);
});
});
describe("[attribution]", () => {
let attributionControl: AttributionControlDirective;
beforeEach(() => {
attributionControl = new AttributionControlDirective({ ref: map });
});
it("should be changed in Leaflet when changing in Angular", () => {
const val: string = "Test attribution";
layer.attribution = val;
expect(layer.options.attribution).to.equal(val);
expect(attributionControl.attributions).to.contain(val);
});
it("should be changed in Angular when changing in Angular", () => {
const val: string = "Test attribution";
layer.attribution = val;
expect(layer.attribution).to.equal(val);
expect(attributionControl.attributions).to.contain(val);
});
it("should remove old attribution when changing in Angular", () => {
const oldVal: string = "Old test attribution";
const newVal: string = "Test attribution";
layer.attribution = oldVal;
layer.attribution = newVal;
expect(attributionControl.attributions).to.contain(newVal);
expect(attributionControl.attributions).to.not.contain(oldVal);
});
});
describe("Destroying a WMS-Layer Directive", () => {
it("should remove WMS-Layer Directive from map on destroy", () => {
/* istanbul ignore if */
if (!map.hasLayer(layer)) {
throw new Error("The layer is not part of the map before destroying");
}
layer.ngOnDestroy();
/* istanbul ignore if */
if (map.hasLayer(layer)) {
throw new Error("The layer is still part of the map after destroying");
}
});
});
}); | the_stack |
import { IIterator } from '@lumino/algorithm';
import { Message } from '@lumino/messaging';
import { Layout } from './layout';
import { TabBar } from './tabbar';
import { Widget } from './widget';
/**
* A layout which provides a flexible docking arrangement.
*
* #### Notes
* The consumer of this layout is responsible for handling all signals
* from the generated tab bars and managing the visibility of widgets
* and tab bars as needed.
*/
export declare class DockLayout extends Layout {
/**
* Construct a new dock layout.
*
* @param options - The options for initializing the layout.
*/
constructor(options: DockLayout.IOptions);
/**
* Dispose of the resources held by the layout.
*
* #### Notes
* This will clear and dispose all widgets in the layout.
*/
dispose(): void;
/**
* The renderer used by the dock layout.
*/
readonly renderer: DockLayout.IRenderer;
/**
* Get the inter-element spacing for the dock layout.
*/
/**
* Set the inter-element spacing for the dock layout.
*/
spacing: number;
/**
* Whether the dock layout is empty.
*/
readonly isEmpty: boolean;
/**
* Create an iterator over all widgets in the layout.
*
* @returns A new iterator over the widgets in the layout.
*
* #### Notes
* This iterator includes the generated tab bars.
*/
iter(): IIterator<Widget>;
/**
* Create an iterator over the user widgets in the layout.
*
* @returns A new iterator over the user widgets in the layout.
*
* #### Notes
* This iterator does not include the generated tab bars.
*/
widgets(): IIterator<Widget>;
/**
* Create an iterator over the selected widgets in the layout.
*
* @returns A new iterator over the selected user widgets.
*
* #### Notes
* This iterator yields the widgets corresponding to the current tab
* of each tab bar in the layout.
*/
selectedWidgets(): IIterator<Widget>;
/**
* Create an iterator over the tab bars in the layout.
*
* @returns A new iterator over the tab bars in the layout.
*
* #### Notes
* This iterator does not include the user widgets.
*/
tabBars(): IIterator<TabBar<Widget>>;
/**
* Create an iterator over the handles in the layout.
*
* @returns A new iterator over the handles in the layout.
*/
handles(): IIterator<HTMLDivElement>;
/**
* Move a handle to the given offset position.
*
* @param handle - The handle to move.
*
* @param offsetX - The desired offset X position of the handle.
*
* @param offsetY - The desired offset Y position of the handle.
*
* #### Notes
* If the given handle is not contained in the layout, this is no-op.
*
* The handle will be moved as close as possible to the desired
* position without violating any of the layout constraints.
*
* Only one of the coordinates is used depending on the orientation
* of the handle. This method accepts both coordinates to make it
* easy to invoke from a mouse move event without needing to know
* the handle orientation.
*/
moveHandle(handle: HTMLDivElement, offsetX: number, offsetY: number): void;
/**
* Save the current configuration of the dock layout.
*
* @returns A new config object for the current layout state.
*
* #### Notes
* The return value can be provided to the `restoreLayout` method
* in order to restore the layout to its current configuration.
*/
saveLayout(): DockLayout.ILayoutConfig;
/**
* Restore the layout to a previously saved configuration.
*
* @param config - The layout configuration to restore.
*
* #### Notes
* Widgets which currently belong to the layout but which are not
* contained in the config will be unparented.
*/
restoreLayout(config: DockLayout.ILayoutConfig): void;
/**
* Add a widget to the dock layout.
*
* @param widget - The widget to add to the dock layout.
*
* @param options - The additional options for adding the widget.
*
* #### Notes
* The widget will be moved if it is already contained in the layout.
*
* An error will be thrown if the reference widget is invalid.
*/
addWidget(widget: Widget, options?: DockLayout.IAddOptions): void;
/**
* Remove a widget from the layout.
*
* @param widget - The widget to remove from the layout.
*
* #### Notes
* A widget is automatically removed from the layout when its `parent`
* is set to `null`. This method should only be invoked directly when
* removing a widget from a layout which has yet to be installed on a
* parent widget.
*
* This method does *not* modify the widget's `parent`.
*/
removeWidget(widget: Widget): void;
/**
* Find the tab area which contains the given client position.
*
* @param clientX - The client X position of interest.
*
* @param clientY - The client Y position of interest.
*
* @returns The geometry of the tab area at the given position, or
* `null` if there is no tab area at the given position.
*/
hitTestTabAreas(clientX: number, clientY: number): DockLayout.ITabAreaGeometry | null;
/**
* Perform layout initialization which requires the parent widget.
*/
protected init(): void;
/**
* Attach the widget to the layout parent widget.
*
* @param widget - The widget to attach to the parent.
*
* #### Notes
* This is a no-op if the widget is already attached.
*/
protected attachWidget(widget: Widget): void;
/**
* Detach the widget from the layout parent widget.
*
* @param widget - The widget to detach from the parent.
*
* #### Notes
* This is a no-op if the widget is not attached.
*/
protected detachWidget(widget: Widget): void;
/**
* A message handler invoked on a `'before-show'` message.
*/
protected onBeforeShow(msg: Message): void;
/**
* A message handler invoked on a `'before-attach'` message.
*/
protected onBeforeAttach(msg: Message): void;
/**
* A message handler invoked on a `'child-shown'` message.
*/
protected onChildShown(msg: Widget.ChildMessage): void;
/**
* A message handler invoked on a `'child-hidden'` message.
*/
protected onChildHidden(msg: Widget.ChildMessage): void;
/**
* A message handler invoked on a `'resize'` message.
*/
protected onResize(msg: Widget.ResizeMessage): void;
/**
* A message handler invoked on an `'update-request'` message.
*/
protected onUpdateRequest(msg: Message): void;
/**
* A message handler invoked on a `'fit-request'` message.
*/
protected onFitRequest(msg: Message): void;
/**
* Remove the specified widget from the layout structure.
*
* #### Notes
* This is a no-op if the widget is not in the layout tree.
*
* This does not detach the widget from the parent node.
*/
private _removeWidget;
/**
* Insert a widget next to an existing tab.
*
* #### Notes
* This does not attach the widget to the parent widget.
*/
private _insertTab;
/**
* Insert a widget as a new split area.
*
* #### Notes
* This does not attach the widget to the parent widget.
*/
private _insertSplit;
/**
* Ensure the root is a split node with the given orientation.
*/
private _splitRoot;
/**
* Fit the layout to the total size required by the widgets.
*/
private _fit;
/**
* Update the layout position and size of the widgets.
*
* The parent offset dimensions should be `-1` if unknown.
*/
private _update;
/**
* Create a new tab bar for use by the dock layout.
*
* #### Notes
* The tab bar will be attached to the parent if it exists.
*/
private _createTabBar;
/**
* Create a new handle for the dock layout.
*
* #### Notes
* The handle will be attached to the parent if it exists.
*/
private _createHandle;
private _spacing;
private _dirty;
private _root;
private _box;
private _items;
}
/**
* The namespace for the `DockLayout` class statics.
*/
export declare namespace DockLayout {
/**
* An options object for creating a dock layout.
*/
interface IOptions {
/**
* The renderer to use for the dock layout.
*/
renderer: IRenderer;
/**
* The spacing between items in the layout.
*
* The default is `4`.
*/
spacing?: number;
}
/**
* A renderer for use with a dock layout.
*/
interface IRenderer {
/**
* Create a new tab bar for use with a dock layout.
*
* @returns A new tab bar for a dock layout.
*/
createTabBar(): TabBar<Widget>;
/**
* Create a new handle node for use with a dock layout.
*
* @returns A new handle node for a dock layout.
*/
createHandle(): HTMLDivElement;
}
/**
* A type alias for the supported insertion modes.
*
* An insert mode is used to specify how a widget should be added
* to the dock layout relative to a reference widget.
*/
type InsertMode = (
/**
* The area to the top of the reference widget.
*
* The widget will be inserted just above the reference widget.
*
* If the reference widget is null or invalid, the widget will be
* inserted at the top edge of the dock layout.
*/
'split-top' |
/**
* The area to the left of the reference widget.
*
* The widget will be inserted just left of the reference widget.
*
* If the reference widget is null or invalid, the widget will be
* inserted at the left edge of the dock layout.
*/
'split-left' |
/**
* The area to the right of the reference widget.
*
* The widget will be inserted just right of the reference widget.
*
* If the reference widget is null or invalid, the widget will be
* inserted at the right edge of the dock layout.
*/
'split-right' |
/**
* The area to the bottom of the reference widget.
*
* The widget will be inserted just below the reference widget.
*
* If the reference widget is null or invalid, the widget will be
* inserted at the bottom edge of the dock layout.
*/
'split-bottom' |
/**
* The tab position before the reference widget.
*
* The widget will be added as a tab before the reference widget.
*
* If the reference widget is null or invalid, a sensible default
* will be used.
*/
'tab-before' |
/**
* The tab position after the reference widget.
*
* The widget will be added as a tab after the reference widget.
*
* If the reference widget is null or invalid, a sensible default
* will be used.
*/
'tab-after');
/**
* An options object for adding a widget to the dock layout.
*/
interface IAddOptions {
/**
* The insertion mode for adding the widget.
*
* The default is `'tab-after'`.
*/
mode?: InsertMode;
/**
* The reference widget for the insert location.
*
* The default is `null`.
*/
ref?: Widget | null;
}
/**
* A layout config object for a tab area.
*/
interface ITabAreaConfig {
/**
* The discriminated type of the config object.
*/
type: 'tab-area';
/**
* The widgets contained in the tab area.
*/
widgets: Widget[];
/**
* The index of the selected tab.
*/
currentIndex: number;
}
/**
* A layout config object for a split area.
*/
interface ISplitAreaConfig {
/**
* The discriminated type of the config object.
*/
type: 'split-area';
/**
* The orientation of the split area.
*/
orientation: 'horizontal' | 'vertical';
/**
* The children in the split area.
*/
children: AreaConfig[];
/**
* The relative sizes of the children.
*/
sizes: number[];
}
/**
* A type alias for a general area config.
*/
type AreaConfig = ITabAreaConfig | ISplitAreaConfig;
/**
* A dock layout configuration object.
*/
interface ILayoutConfig {
/**
* The layout config for the main dock area.
*/
main: AreaConfig | null;
}
/**
* An object which represents the geometry of a tab area.
*/
interface ITabAreaGeometry {
/**
* The tab bar for the tab area.
*/
tabBar: TabBar<Widget>;
/**
* The local X position of the hit test in the dock area.
*
* #### Notes
* This is the distance from the left edge of the layout parent
* widget, to the local X coordinate of the hit test query.
*/
x: number;
/**
* The local Y position of the hit test in the dock area.
*
* #### Notes
* This is the distance from the top edge of the layout parent
* widget, to the local Y coordinate of the hit test query.
*/
y: number;
/**
* The local coordinate of the top edge of the tab area.
*
* #### Notes
* This is the distance from the top edge of the layout parent
* widget, to the top edge of the tab area.
*/
top: number;
/**
* The local coordinate of the left edge of the tab area.
*
* #### Notes
* This is the distance from the left edge of the layout parent
* widget, to the left edge of the tab area.
*/
left: number;
/**
* The local coordinate of the right edge of the tab area.
*
* #### Notes
* This is the distance from the right edge of the layout parent
* widget, to the right edge of the tab area.
*/
right: number;
/**
* The local coordinate of the bottom edge of the tab area.
*
* #### Notes
* This is the distance from the bottom edge of the layout parent
* widget, to the bottom edge of the tab area.
*/
bottom: number;
/**
* The width of the tab area.
*
* #### Notes
* This is total width allocated for the tab area.
*/
width: number;
/**
* The height of the tab area.
*
* #### Notes
* This is total height allocated for the tab area.
*/
height: number;
}
}
//# sourceMappingURL=docklayout.d.ts.map | the_stack |
import type { Client } from "../Client";
import type { CamelCaseObjectKeys, Saved, TimeRange } from "../Interface";
import type { Playlist } from "../structures/Playlist";
import type { Artist } from "../structures/Artist";
import type { Track } from "../structures/Track";
import type { Episode } from "../structures/Episode";
import type { Show } from "../structures/Show";
import type { Album } from "../structures/Album";
import { Player } from "./Player";
import { SpotifyAPIError } from "../Error";
import { createCacheStructArray, createCacheSavedStructArray } from "../Cache";
import type {
SpotifyType,
Image,
ExternalUrl,
UserProductType,
ExplicitContentSettings,
PrivateUser,
CreatePlaylistQuery
} from "spotify-types";
/**
* The client which handles all the current user api endpoints and with the details of the current user.
*/
export class UserClient {
/**
* The spotify client for this UserClient to work with.
*/
public readonly client!: Client;
/**
* The manager for the player api endpoints.
*/
public player: Player;
/**
* The name displayed on the user’s profile. null if not available.
*/
public displayName?: string | null;
/**
* The Spotify user ID for the user.
*/
public id!: string;
/**
* The Spotify URI for the user.
*/
public uri?: string;
/**
* The Spotify object type which will be 'user'.
*/
public type?: SpotifyType = 'user';
/**
* The user’s profile image.
*/
public images?: Image[];
/**
* Information about the followers of the user.
*/
public totalFollowers?: number;
/**
* Known external URLs for this user.
*/
public externalURL?: ExternalUrl;
/**
* The spotify subscription level of the user. If the user has the paticualr authorized scope for it.
*/
public product?: UserProductType;
/**
* The country of the user, as set in the user’s account profile.
*/
public country?: string;
/**
* The user’s email address, as entered by the user when creating their account.
*/
public email?: string;
/**
* The user’s explicit content settings.
*/
public explicitContent?: CamelCaseObjectKeys<ExplicitContentSettings>;
/**
* The client which handles all the current user api endpoints with the details of the current user.
* All the methods in this class requires the user authorized token.
*
* @param client The spotify api client.
* @example const user = new UserClient(client);
*/
public constructor(client: Client) {
this.player = new Player(client);
Object.defineProperty(this, 'client', { value: client });
}
/**
* Patches the current user details info to this manager.
*/
public async patchInfo() {
const data: PrivateUser = await this.client.fetch('/me');
if (!data) throw new SpotifyAPIError("Could not load private user data from the user authorized token.");
this.displayName = data.display_name;
this.id = data.id;
this.uri = data.uri;
this.images = data.images;
this.totalFollowers = data.followers.total;
this.externalURL = data.external_urls;
this.email = data.email;
this.product = data.product;
this.country = data.country;
if (data.explicit_content) this.explicitContent = {
filterEnabled: data.explicit_content.filter_enabled,
filterLocked: data.explicit_content.filter_locked
};
return this;
}
/**
* Get the list of playlists of the current user.
*
* @param options The limit, offset query parameter options.
* @example const playlists = await client.user.getPlaylists();
*/
public async getPlaylists(
options: {
limit?: number,
offset?: number
} = {}
): Promise<Playlist[]> {
const fetchedData = await this.client.fetch(`/me/playlists`, { params: options });
return fetchedData ? createCacheStructArray('playlists', this.client, fetchedData.items) : [];
}
/**
* Create a playlist.
*
* @param playlist The playlist details to set.
* @example const playlist = await client.user.createPlaylist({ name: 'My playlist' });
*/
public createPlaylist(playlist: CreatePlaylistQuery): Promise<Playlist | null> {
return this.client.playlists.create(this.id, playlist);
}
/**
* Verify if the current user follows a paticular playlist.
*
* @param playlistID The id of the spotify playlist.
* @example const currentUserFollows = await client.user.followsPlaylist('id');
*/
public followsPlaylist(playlistID: string): Promise<boolean> {
return this.client.users.followsPlaylist(playlistID, this.id).then(x => x[0] || false);
}
/**
* Verify if the current user follows one or more artists.
*
* @param ids The array of spotify artist ids.
* @example const [followsArtist] = await client.user.followsArtists('id1');
*/
public followsArtists(...ids: string[]): Promise<boolean[]> {
return this.client.fetch(`/me/following/contains`, {
params: {
type: 'artist',
ids: ids.join(',')
}
}).then(x => x || ids.map(() => false))
}
/**
* Verify if the current user follows one or more users.
*
* @param ids The array of spotify user ids.
* @example const [followsUser] = await client.user.followsUsers('id1');
*/
public followsUsers(...ids: string[]): Promise<boolean[]> {
return this.client.fetch(`/me/following/contains`, {
params: {
type: 'user',
ids: ids.join(',')
}
}).then(x => x || ids.map(() => false))
}
/**
* Get an array of artists who are been followed by the current usser.
*
* @param options The limit, after query parameters. The after option is the last artist ID retrieved from the previous request.
* @example const artists = await client.user.getFollowingArtists();
*/
public async getFollowingArtists(
options: {
limit?: number,
after?: string
} = {}
): Promise<Artist[]> {
const fetchedData = await this.client.fetch(`/me/following`, { params: { type: 'artist', ...options } });
return fetchedData ? createCacheStructArray('artists', this.client, fetchedData.artists.items) : [];
}
/**
* Get the top tracks of the user based on the current user's affinity.
*
* @param options The timeRange, limit, offset query paramaters.
* @example const topTracks = await client.user.getTopTracks();
*/
public async getTopTracks(
options: {
timeRange?: TimeRange,
limit?: number,
offset?: number
} = {}
): Promise<Track[]> {
const fetchedData = await this.client.fetch(`/me/top/tracks`, {
params: {
time_range: options.timeRange,
limit: options.limit,
offset: options.offset
}
});
return fetchedData ? createCacheStructArray('tracks', this.client, fetchedData.items) : [];
}
/**
* Get the top artists of the user based on the current user's affinity.
*
* @param options The timeRange, limit, offset query paramaters.
* @example const topArtists = await client.user.getTopArtists();
*/
public async getTopArtists(
options: {
timeRange?: TimeRange,
limit?: number,
offset?: number
} = {}
): Promise<Artist[]> {
const fetchedData = await this.client.fetch(`/me/top/artists`, {
params: {
time_range: options.timeRange,
limit: options.limit,
offset: options.offset
}
});
return fetchedData ? createCacheStructArray('artists', this.client, fetchedData.items) : [];
}
/**
* Get all the saved albums of the current user.
*
* @param options The limit, offset, market query paramaters.
* @example const savedAlbums = await client.user.getSavedAlbums();
*/
public async getSavedAlbums(
options: {
limit?: number,
offset?: number,
market?: string
}
): Promise<Saved<Album>[]> {
const fetchedData = await this.client.fetch(`/me/albums`, { params: options });
return fetchedData ? createCacheSavedStructArray('albums', this.client, fetchedData.items) : [];
}
/**
* Save albums to the current user library.
*
* @param ids The array of spotify user ids.
* @example await client.user.saveAlbums('id1', 'id2');
*/
public saveAlbums(...ids: string[]): Promise<boolean> {
return this.client.fetch(`/me/albums`, {
method: 'PUT',
params: { ids: ids.join(',') }
}).then(x => x != null);
}
/**
* Remove albums from the current user library.
*
* @param ids The array of spotify user ids.
* @example await client.user.removeAlbums('id1', 'id2');
*/
public removeAlbums(...ids: string[]): Promise<boolean> {
return this.client.fetch(`/me/albums`, {
method: 'DELETE',
params: { ids: ids.join(',') }
}).then(x => x != null);
}
/**
* Verify if the current user has a paticular one or more albums.
*
* @param ids The array of spotify album ids.
* @example const [hasFirstAlbum, hasSecondAlbum] = await client.user.hasAlbums('id1', 'id2');
*/
public hasAlbums(...ids: string[]): Promise<boolean[]> {
return this.client.fetch(`/me/albums/contains`, { params: { ids: ids.join(',') } })
.then(x => x || ids.map(() => false));
}
/**
* Get all the saved tracks of the current user.
*
* @param options The limit, offset, market query paramaters.
* @example const savedTracks = await client.user.getSavedTracks();
*/
public async getSavedTracks(
options: {
limit?: number,
offset?: number,
market?: string
}
): Promise<Saved<Track>[]> {
const fetchedData = await this.client.fetch(`/me/tracks`, { params: options });
return fetchedData ? createCacheSavedStructArray('tracks', this.client, fetchedData.items) : [];
}
/**
* Save tracks to the current user library.
*
* @param ids The array of spotify user ids.
* @example await client.user.saveTracks('id1', 'id2');
*/
public saveTracks(...ids: string[]): Promise<boolean> {
return this.client.fetch(`/me/tracks`, {
method: 'PUT',
params: { ids: ids.join(',') }
}).then(x => x != null);
}
/**
* Remove tracks from the current user library.
*
* @param ids The array of spotify user ids.
* @example await client.user.removeTracks('id1', 'id2');
*/
public removeTracks(...ids: string[]): Promise<boolean> {
return this.client.fetch(`/me/tracks`, {
method: 'DELETE',
params: { ids: ids.join(',') }
}).then(x => x != null);
}
/**
* Verify if the current user has a paticular one or more tracks.
*
* @param ids The array of spotify track ids.
* @example const [hasFirstTrack, hasSecondTrack] = await client.user.hasTracks('id1', 'id2');
*/
public hasTracks(...ids: string[]): Promise<boolean[]> {
return this.client.fetch(`/me/tracks/contains`, { params: { ids: ids.join(',') } })
.then(x => x || ids.map(() => false));
}
/**
* Get all the saved episodes of the current user.
*
* @param options The limit, offset, market query paramaters.
* @example const savedEpisodes = await client.user.getSavedEpisodes();
*/
public async getSavedEpisodes(
options: {
limit?: number,
offset?: number,
market?: string
}
): Promise<Saved<Episode>[]> {
const fetchedData = await this.client.fetch(`/me/episodes`, { params: options });
return fetchedData ? createCacheSavedStructArray('episodes', this.client, fetchedData.items) : [];
}
/**
* Save episodes to the current user library.
*
* @param ids The array of spotify user ids.
* @example await client.user.saveEpisodes('id1', 'id2');
*/
public saveEpisodes(...ids: string[]): Promise<boolean> {
return this.client.fetch(`/me/episodes`, {
method: 'PUT',
params: { ids: ids.join(',') }
}).then(x => x != null);
}
/**
* Remove episodes from the current user library.
*
* @param ids The array of spotify user ids.
* @example await client.user.removeEpisodes('id1', 'id2');
*/
public removeEpisodes(...ids: string[]): Promise<boolean> {
return this.client.fetch(`/me/episodes`, {
method: 'DELETE',
params: { ids: ids.join(',') }
}).then(x => x != null);
}
/**
* Verify if the current user has a paticular one or more episodes.
*
* @param ids The array of spotify episode ids.
* @example const [hasFirstEpisode, hasSecondEpisode] = await client.user.hasEpisodes('id1', 'id2');
*/
public hasEpisodes(...ids: string[]): Promise<boolean[]> {
return this.client.fetch(`/me/episodes/contains`, { params: { ids: ids.join(',') } })
.then(x => x || ids.map(() => false));
}
/**
* Get all the saved shows of the current user.
*
* @param options The limit, offset, market query paramaters.
* @example const savedShows = await client.user.getSavedShows();
*/
public async getSavedShows(
options: {
limit?: number,
offset?: number,
market?: string
}
): Promise<Saved<Show>[]> {
const fetchedData = await this.client.fetch(`/me/shows`, { params: options });
return fetchedData ? createCacheSavedStructArray('shows', this.client, fetchedData.items) : [];
}
/**
* Save shows to the current user library.
*
* @param ids The array of spotify user ids.
* @example await client.user.saveShows('id1', 'id2');
*/
public saveShows(...ids: string[]): Promise<boolean> {
return this.client.fetch(`/me/shows`, {
method: 'PUT',
params: { ids: ids.join(',') }
}).then(x => x != null);
}
/**
* Remove shows from the current user library.
*
* @param ids The array of spotify user ids.
* @example await client.user.removeShows('id1', 'id2');
*/
public removeShows(...ids: string[]): Promise<boolean> {
return this.client.fetch(`/me/shows`, {
method: 'DELETE',
params: { ids: ids.join(',') }
}).then(x => x != null);
}
/**
* Verify if the current user has a paticular one or more shows.
*
* @param ids The array of spotify show ids.
* @example const [hasFirstShow, hasSecondShow] = await client.user.hasShows('id1', 'id2');
*/
public hasShows(...ids: string[]): Promise<boolean[]> {
return this.client.fetch(`/me/shows/contains`, { params: { ids: ids.join(',') } })
.then(x => x || ids.map(() => false));
}
} | the_stack |
import { SendTransactionOpts } from '@0x/base-contract';
import { getContractAddressesForChainOrThrow } from '@0x/contract-addresses';
import { ExchangeContract } from '@0x/contracts-exchange';
import { ExchangeFunctionName } from '@0x/contracts-test-utils';
import { devConstants } from '@0x/dev-utils';
import { schemas } from '@0x/json-schemas';
import { generatePseudoRandomSalt, signatureUtils } from '@0x/order-utils';
import { Order, SignedOrder, SignedZeroExTransaction, ZeroExTransaction } from '@0x/types';
import { BigNumber, fetchAsync } from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wrapper';
import { CallData, ContractAbi, SupportedProvider, TxData } from 'ethereum-types';
import * as HttpStatus from 'http-status-codes';
import { flatten } from 'lodash';
import { artifacts } from '../artifacts';
import { CoordinatorContract, CoordinatorRegistryContract } from '../wrappers';
import { assert } from './utils/assert';
import {
CoordinatorServerApprovalResponse,
CoordinatorServerCancellationResponse,
CoordinatorServerError,
CoordinatorServerErrorMsg,
CoordinatorServerResponse,
} from './utils/coordinator_server_types';
import { decorators } from './utils/decorators';
export { CoordinatorServerErrorMsg, CoordinatorServerCancellationResponse };
const DEFAULT_TX_DATA = {
gas: devConstants.GAS_LIMIT,
gasPrice: new BigNumber(1),
value: new BigNumber(150000), // DEFAULT_PROTOCOL_FEE_MULTIPLIER
};
// tx expiration time will be set to (now + default_approval - time_buffer)
const DEFAULT_APPROVAL_EXPIRATION_TIME_SECONDS = 90;
const DEFAULT_EXPIRATION_TIME_BUFFER_SECONDS = 30;
/**
* This class includes all the functionality related to filling or cancelling orders through
* the 0x V2 Coordinator extension contract.
*/
export class CoordinatorClient {
public abi: ContractAbi = artifacts.Coordinator.compilerOutput.abi;
public chainId: number;
public address: string;
public exchangeAddress: string;
public registryAddress: string;
private readonly _web3Wrapper: Web3Wrapper;
private readonly _contractInstance: CoordinatorContract;
private readonly _registryInstance: CoordinatorRegistryContract;
private readonly _exchangeInstance: ExchangeContract;
private readonly _feeRecipientToEndpoint: { [feeRecipient: string]: string } = {};
private readonly _txDefaults: CallData = DEFAULT_TX_DATA;
/**
* Validates that the 0x transaction has been approved by all of the feeRecipients that correspond to each order in the transaction's Exchange calldata.
* Throws an error if the transaction approvals are not valid. Will not detect failures that would occur when the transaction is executed on the Exchange contract.
* @param transaction 0x transaction containing salt, signerAddress, and data.
* @param txOrigin Required signer of Ethereum transaction calling this function.
* @param transactionSignature Proof that the transaction has been signed by the signer.
* @param approvalSignatures Array of signatures that correspond to the feeRecipients of each order in the transaction's Exchange calldata.
*/
@decorators.asyncZeroExErrorHandler
public async assertValidCoordinatorApprovalsOrThrowAsync(
transaction: ZeroExTransaction,
txOrigin: string,
transactionSignature: string,
approvalSignatures: string[],
): Promise<void> {
assert.doesConformToSchema('transaction', transaction, schemas.zeroExTransactionSchema);
assert.isETHAddressHex('txOrigin', txOrigin);
assert.isHexString('transactionSignature', transactionSignature);
for (const approvalSignature of approvalSignatures) {
assert.isHexString('approvalSignature', approvalSignature);
}
return this._contractInstance
.assertValidCoordinatorApprovals(transaction, txOrigin, transactionSignature, approvalSignatures)
.callAsync();
}
/**
* Instantiate CoordinatorClient
* @param web3Wrapper Web3Wrapper instance to use.
* @param chainId Desired chainId.
* @param address The address of the Coordinator contract. If undefined, will
* default to the known address corresponding to the chainId.
* @param exchangeAddress The address of the Exchange contract. If undefined, will
* default to the known address corresponding to the chainId.
* @param registryAddress The address of the CoordinatorRegistry contract. If undefined, will
* default to the known address corresponding to the chainId.
*/
constructor(
address: string,
provider: SupportedProvider,
chainId: number,
txDefaults?: Partial<TxData>,
exchangeAddress?: string,
registryAddress?: string,
) {
this.chainId = chainId;
const contractAddresses = getContractAddressesForChainOrThrow(this.chainId);
this.address = address === undefined ? contractAddresses.coordinator : address;
this.exchangeAddress = exchangeAddress === undefined ? contractAddresses.exchange : exchangeAddress;
this.registryAddress = registryAddress === undefined ? contractAddresses.coordinatorRegistry : registryAddress;
this._web3Wrapper = new Web3Wrapper(provider);
this._txDefaults = { ...txDefaults, ...DEFAULT_TX_DATA };
this._contractInstance = new CoordinatorContract(
this.address,
this._web3Wrapper.getProvider(),
this._web3Wrapper.getContractDefaults(),
);
this._registryInstance = new CoordinatorRegistryContract(
this.registryAddress,
this._web3Wrapper.getProvider(),
this._web3Wrapper.getContractDefaults(),
);
this._exchangeInstance = new ExchangeContract(
this.exchangeAddress,
this._web3Wrapper.getProvider(),
this._web3Wrapper.getContractDefaults(),
);
}
/**
* Fills a signed order with an amount denominated in baseUnits of the taker asset. Under-the-hood, this
* method uses the `feeRecipientAddress` of the order to look up the coordinator server endpoint registered in the
* coordinator registry contract. It requests an approval from that coordinator server before
* submitting the order and approval as a 0x transaction to the coordinator extension contract. The coordinator extension
* contract validates approvals and then fills the order via the Exchange contract.
* @param order An object that conforms to the Order interface.
* @param takerAssetFillAmount The amount of the order (in taker asset baseUnits) that you wish to fill.
* @param signature Signature corresponding to the order.
* @param txData Transaction data. The `from` field should be the user Ethereum address who would like
* to fill these orders. Must be available via the Provider supplied at instantiation.
* @param sendTxOpts Optional arguments for sending the transaction.
* @return Transaction hash.
*/
@decorators.asyncZeroExErrorHandler
public async fillOrderAsync(
order: Order,
takerAssetFillAmount: BigNumber,
signature: string,
txData: TxData,
sendTxOpts: Partial<SendTransactionOpts> = { shouldValidate: true },
): Promise<string> {
assert.doesConformToSchema('order', order, schemas.orderSchema);
assert.isValidBaseUnitAmount('takerAssetFillAmount', takerAssetFillAmount);
return this._executeTxThroughCoordinatorAsync(
ExchangeFunctionName.FillOrder,
txData,
sendTxOpts,
[order],
order,
takerAssetFillAmount,
signature,
);
}
/**
* Attempts to fill a specific amount of an order. If the entire amount specified cannot be filled,
* the fill order is abandoned.
* @param order An object that conforms to the Order interface.
* @param takerAssetFillAmount The amount of the order (in taker asset baseUnits) that you wish to fill.
* @param signature Signature corresponding to the order.
* @param txData Transaction data. The `from` field should be the user Ethereum address who would like
* to fill these orders. Must be available via the Provider supplied at instantiation.
* @param sendTxOpts Optional arguments for sending the transaction.
* @return Transaction hash.
*/
@decorators.asyncZeroExErrorHandler
public async fillOrKillOrderAsync(
order: Order,
takerAssetFillAmount: BigNumber,
signature: string,
txData: TxData,
sendTxOpts: Partial<SendTransactionOpts> = { shouldValidate: true },
): Promise<string> {
assert.doesConformToSchema('order', order, schemas.orderSchema);
assert.isValidBaseUnitAmount('takerAssetFillAmount', takerAssetFillAmount);
return this._executeTxThroughCoordinatorAsync(
ExchangeFunctionName.FillOrKillOrder,
txData,
sendTxOpts,
[order],
order,
takerAssetFillAmount,
signature,
);
}
/**
* Batch version of fillOrderAsync. Executes multiple fills atomically in a single transaction.
* If any `feeRecipientAddress` in the batch is not registered to a coordinator server through the CoordinatorRegistryContract, the whole batch fails.
* @param orders An array of orders to fill.
* @param takerAssetFillAmounts The amounts of the orders (in taker asset baseUnits) that you wish to fill.
* @param signatures Signatures corresponding to the orders.
* @param txData Transaction data. The `from` field should be the user Ethereum address who would like
* to fill these orders. Must be available via the Provider supplied at instantiation.
* @param sendTxOpts Optional arguments for sending the transaction.
* @return Transaction hash.
*/
@decorators.asyncZeroExErrorHandler
public async batchFillOrdersAsync(
orders: Order[],
takerAssetFillAmounts: BigNumber[],
signatures: string[],
txData: TxData,
sendTxOpts?: Partial<SendTransactionOpts>,
): Promise<string> {
return this._batchFillAsync(
ExchangeFunctionName.BatchFillOrders,
orders,
takerAssetFillAmounts,
signatures,
txData,
sendTxOpts,
);
}
/**
* No throw version of batchFillOrdersAsync
* @param orders An array of orders to fill.
* @param takerAssetFillAmounts The amounts of the orders (in taker asset baseUnits) that you wish to fill.
* @param signatures Signatures corresponding to the orders.
* @param txData Transaction data. The `from` field should be the user Ethereum address who would like
* to fill these orders. Must be available via the Provider supplied at instantiation.
* @param sendTxOpts Optional arguments for sending the transaction.
* @return Transaction hash.
*/
public async batchFillOrdersNoThrowAsync(
orders: Order[],
takerAssetFillAmounts: BigNumber[],
signatures: string[],
txData: TxData,
sendTxOpts?: Partial<SendTransactionOpts>,
): Promise<string> {
return this._batchFillAsync(
ExchangeFunctionName.BatchFillOrdersNoThrow,
orders,
takerAssetFillAmounts,
signatures,
txData,
sendTxOpts,
);
}
/**
* Batch version of fillOrKillOrderAsync. Executes multiple fills atomically in a single transaction.
* @param orders An array of orders to fill.
* @param takerAssetFillAmounts The amounts of the orders (in taker asset baseUnits) that you wish to fill.
* @param signatures Signatures corresponding to the orders.
* @param txData Transaction data. The `from` field should be the user Ethereum address who would like
* to fill these orders. Must be available via the Provider supplied at instantiation.
* @param sendTxOpts Optional arguments for sending the transaction.
* @return Transaction hash.
*/
@decorators.asyncZeroExErrorHandler
public async batchFillOrKillOrdersAsync(
orders: Order[],
takerAssetFillAmounts: BigNumber[],
signatures: string[],
txData: TxData,
sendTxOpts?: Partial<SendTransactionOpts>,
): Promise<string> {
return this._batchFillAsync(
ExchangeFunctionName.BatchFillOrKillOrders,
orders,
takerAssetFillAmounts,
signatures,
txData,
sendTxOpts,
);
}
/**
* Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker.
* If any fill reverts, the error is caught and ignored. Finally, reverts if < makerAssetFillAmount has been bought.
* NOTE: This function does not enforce that the makerAsset is the same for each order.
* @param orders Array of order specifications.
* @param makerAssetFillAmount Desired amount of makerAsset to buy.
* @param signatures Proofs that orders have been signed by makers.
* @param txData Transaction data. The `from` field should be the user Ethereum address who would like
* to fill these orders. Must be available via the Provider supplied at instantiation.
* @param sendTxOpts Optional arguments for sending the transaction.
* @return Transaction hash.
*/
@decorators.asyncZeroExErrorHandler
public async marketBuyOrdersFillOrKillAsync(
orders: Order[],
makerAssetFillAmount: BigNumber,
signatures: string[],
txData: TxData,
sendTxOpts: SendTransactionOpts = { shouldValidate: true },
): Promise<string> {
return this._marketBuySellOrdersAsync(
ExchangeFunctionName.MarketBuyOrdersFillOrKill,
orders,
makerAssetFillAmount,
signatures,
txData,
sendTxOpts,
);
}
/**
* No throw version of marketBuyOrdersFillOrKillAsync
* @param orders An array of orders to fill.
* @param makerAssetFillAmount Maker asset fill amount.
* @param signatures Signatures corresponding to the orders.
* @param txData Transaction data. The `from` field should be the user Ethereum address who would like
* to fill these orders. Must be available via the Provider supplied at instantiation.
* @param sendTxOpts Optional arguments for sending the transaction.
* @return Transaction hash.
*/
@decorators.asyncZeroExErrorHandler
public async marketBuyOrdersNoThrowAsync(
orders: Order[],
makerAssetFillAmount: BigNumber,
signatures: string[],
txData: TxData,
sendTxOpts: SendTransactionOpts = { shouldValidate: true },
): Promise<string> {
return this._marketBuySellOrdersAsync(
ExchangeFunctionName.MarketBuyOrdersNoThrow,
orders,
makerAssetFillAmount,
signatures,
txData,
sendTxOpts,
);
}
/**
* Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker.
* If any fill reverts, the error is caught and ignored. Finally, reverts if < takerAssetFillAmount has been sold.
* NOTE: This function does not enforce that the takerAsset is the same for each order.
* @param orders Array of order specifications.
* @param takerAssetFillAmount Desired amount of takerAsset to sell.
* @param signatures Proofs that orders have been signed by makers.
* @param txData Transaction data. The `from` field should be the user Ethereum address who would like
* to fill these orders. Must be available via the Provider supplied at instantiation.
* @param sendTxOpts Optional arguments for sending the transaction.
* @return Transaction hash.
*/
@decorators.asyncZeroExErrorHandler
public async marketSellOrdersFillOrKillAsync(
orders: Order[],
takerAssetFillAmount: BigNumber,
signatures: string[],
txData: TxData,
sendTxOpts: SendTransactionOpts = { shouldValidate: true },
): Promise<string> {
return this._marketBuySellOrdersAsync(
ExchangeFunctionName.MarketSellOrdersFillOrKill,
orders,
takerAssetFillAmount,
signatures,
txData,
sendTxOpts,
);
}
/**
* No throw version of marketSellOrdersAsync
* @param orders An array of orders to fill.
* @param takerAssetFillAmount Taker asset fill amount.
* @param signatures Signatures corresponding to the orders.
* @param txData Transaction data. The `from` field should be the user Ethereum address who would like
* to fill these orders. Must be available via the Provider supplied at instantiation.
* @param sendTxOpts Optional arguments for sending the transaction.
* @return Transaction hash.
*/
@decorators.asyncZeroExErrorHandler
public async marketSellOrdersNoThrowAsync(
orders: Order[],
takerAssetFillAmount: BigNumber,
signatures: string[],
txData: TxData,
sendTxOpts: SendTransactionOpts = { shouldValidate: true },
): Promise<string> {
return this._marketBuySellOrdersAsync(
ExchangeFunctionName.MarketSellOrdersNoThrow,
orders,
takerAssetFillAmount,
signatures,
txData,
sendTxOpts,
);
}
/**
* Cancels an order on-chain by submitting an Ethereum transaction.
* @param order An object that conforms to the Order interface. The order you would like to cancel.
* @param txData Transaction data. The `from` field should be the maker's Ethereum address. Must be available
* via the Provider supplied at instantiation.
* @param sendTxOpts Optional arguments for sending the transaction.
* @return Transaction hash.
*/
@decorators.asyncZeroExErrorHandler
public async hardCancelOrderAsync(
order: Order,
txData: TxData,
sendTxOpts: SendTransactionOpts = { shouldValidate: true },
): Promise<string> {
assert.doesConformToSchema('order', order, schemas.orderSchema);
return this._executeTxThroughCoordinatorAsync(
ExchangeFunctionName.CancelOrder,
txData,
sendTxOpts,
[order],
order,
);
}
/**
* Batch version of hardCancelOrderAsync. Cancels orders on-chain by submitting an Ethereum transaction.
* Executes multiple cancels atomically in a single transaction.
* @param orders An array of orders to cancel.
* @param txData Transaction data. The `from` field should be the maker's Ethereum address. Must be available
* via the Provider supplied at instantiation.
* @param sendTxOpts Optional arguments for sending the transaction.
* @return Transaction hash.
*/
@decorators.asyncZeroExErrorHandler
public async batchHardCancelOrdersAsync(
orders: Order[],
txData: TxData,
sendTxOpts: SendTransactionOpts = { shouldValidate: true },
): Promise<string> {
assert.doesConformToSchema('orders', orders, schemas.ordersSchema);
return this._executeTxThroughCoordinatorAsync(
ExchangeFunctionName.BatchCancelOrders,
txData,
sendTxOpts,
orders,
orders,
);
}
/**
* Cancels orders on-chain by submitting an Ethereum transaction.
* Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch
* and senderAddress equal to coordinator extension contract address.
* @param targetOrderEpoch Target order epoch.
* @param txData Transaction data. The `from` field should be the maker's Ethereum address. Must be available
* via the Provider supplied at instantiation.
* @param sendTxOpts Optional arguments for sending the transaction.
* @return Transaction hash.
*/
@decorators.asyncZeroExErrorHandler
public async hardCancelOrdersUpToAsync(
targetOrderEpoch: BigNumber,
txData: TxData,
sendTxOpts: SendTransactionOpts = { shouldValidate: true },
): Promise<string> {
assert.isBigNumber('targetOrderEpoch', targetOrderEpoch);
return this._executeTxThroughCoordinatorAsync(
ExchangeFunctionName.CancelOrdersUpTo,
txData,
sendTxOpts,
[],
targetOrderEpoch,
);
}
/**
* Soft cancel a given order.
* Soft cancels are recorded only on coordinator operator servers and do not involve an Ethereum transaction.
* See [soft cancels](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/coordinator-specification.md#soft-cancels).
* @param order An object that conforms to the Order or SignedOrder interface. The order you would like to cancel.
* @return CoordinatorServerCancellationResponse. See [Cancellation Response](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/coordinator-specification.md#response).
*/
@decorators.asyncZeroExErrorHandler
public async softCancelAsync(order: Order): Promise<CoordinatorServerCancellationResponse> {
assert.doesConformToSchema('order', order, schemas.orderSchema);
assert.isETHAddressHex('feeRecipientAddress', order.feeRecipientAddress);
assert.isSenderAddressAsync('makerAddress', order.makerAddress, this._web3Wrapper);
const data = this._exchangeInstance.cancelOrder(order).getABIEncodedTransactionData();
const transaction = await this._generateSignedZeroExTransactionAsync(data, order.makerAddress);
const endpoint = await this._getServerEndpointOrThrowAsync(order);
const response = await this._executeServerRequestAsync(transaction, order.makerAddress, endpoint);
if (response.isError) {
const approvedOrders = new Array();
const cancellations = new Array();
const errors = [
{
...response,
orders: [order],
},
];
throw new CoordinatorServerError(
CoordinatorServerErrorMsg.CancellationFailed,
approvedOrders,
cancellations,
errors,
);
} else {
return response.body as CoordinatorServerCancellationResponse;
}
}
/**
* Batch version of softCancelOrderAsync. Requests multiple soft cancels
* @param orders An array of orders to cancel.
* @return CoordinatorServerCancellationResponse. See [Cancellation Response](https://github.com/0xProject/0x-protocol-specification/blob/master/v2/coordinator-specification.md#response).
*/
@decorators.asyncZeroExErrorHandler
public async batchSoftCancelAsync(orders: SignedOrder[]): Promise<CoordinatorServerCancellationResponse[]> {
assert.doesConformToSchema('orders', orders, schemas.ordersSchema);
const makerAddress = getMakerAddressOrThrow(orders);
assert.isSenderAddressAsync('makerAddress', makerAddress, this._web3Wrapper);
const data = this._exchangeInstance.batchCancelOrders(orders).getABIEncodedTransactionData();
const transaction = await this._generateSignedZeroExTransactionAsync(data, makerAddress);
// make server requests
const errorResponses: CoordinatorServerResponse[] = [];
const successResponses: CoordinatorServerCancellationResponse[] = [];
const serverEndpointsToOrders = await this._mapServerEndpointsToOrdersAsync(orders);
for (const endpoint of Object.keys(serverEndpointsToOrders)) {
const response = await this._executeServerRequestAsync(transaction, makerAddress, endpoint);
if (response.isError) {
errorResponses.push(response);
} else {
successResponses.push(response.body as CoordinatorServerCancellationResponse);
}
}
// if no errors
if (errorResponses.length === 0) {
return successResponses;
} else {
// lookup orders with errors
const errorsWithOrders = errorResponses.map(resp => {
const endpoint = resp.coordinatorOperator;
const _orders = serverEndpointsToOrders[endpoint];
return {
...resp,
orders: _orders,
};
});
const approvedOrders = new Array();
const cancellations = successResponses;
// return errors and approvals
throw new CoordinatorServerError(
CoordinatorServerErrorMsg.CancellationFailed,
approvedOrders,
cancellations,
errorsWithOrders,
);
}
}
/**
* Recovers the address of a signer given a hash and signature.
* @param hash Any 32 byte hash.
* @param signature Proof that the hash has been signed by signer.
* @returns Signer address.
*/
@decorators.asyncZeroExErrorHandler
public async getSignerAddressAsync(hash: string, signature: string): Promise<string> {
assert.isHexString('hash', hash);
assert.isHexString('signature', signature);
const signerAddress = await this._contractInstance.getSignerAddress(hash, signature).callAsync();
return signerAddress;
}
private async _marketBuySellOrdersAsync(
exchangeFn: ExchangeFunctionName,
orders: Order[],
assetFillAmount: BigNumber,
signatures: string[],
txData: TxData,
sendTxOpts: SendTransactionOpts = { shouldValidate: true },
): Promise<string> {
assert.doesConformToSchema('orders', orders, schemas.ordersSchema);
assert.isBigNumber('assetFillAmount', assetFillAmount);
return this._executeTxThroughCoordinatorAsync(
exchangeFn,
txData,
sendTxOpts,
orders,
orders,
assetFillAmount,
signatures,
);
}
private async _batchFillAsync(
exchangeFn: ExchangeFunctionName,
orders: Order[],
takerAssetFillAmounts: BigNumber[],
signatures: string[],
txData: TxData,
sendTxOpts: SendTransactionOpts = { shouldValidate: true },
): Promise<string> {
assert.doesConformToSchema('orders', orders, schemas.ordersSchema);
takerAssetFillAmounts.forEach(takerAssetFillAmount =>
assert.isValidBaseUnitAmount('takerAssetFillAmount', takerAssetFillAmount),
);
return this._executeTxThroughCoordinatorAsync(
exchangeFn,
txData,
sendTxOpts,
orders,
orders,
takerAssetFillAmounts,
signatures,
);
}
private async _executeTxThroughCoordinatorAsync(
exchangeFn: ExchangeFunctionName,
txData: TxData,
sendTxOpts: Partial<SendTransactionOpts>,
ordersNeedingApprovals: Order[],
...args: any[] // tslint:disable-line:trailing-comma
): Promise<string> {
assert.isETHAddressHex('takerAddress', txData.from);
await assert.isSenderAddressAsync('takerAddress', txData.from, this._web3Wrapper);
// get ABI encoded transaction data for the desired exchange method
const data = (this._exchangeInstance as any)[exchangeFn](...args).getABIEncodedTransactionData();
// generate and sign a ZeroExTransaction
const signedZrxTx = await this._generateSignedZeroExTransactionAsync(data, txData.from, txData.gasPrice);
// get approval signatures from registered coordinator operators
const approvalSignatures = await this._getApprovalsAsync(signedZrxTx, ordersNeedingApprovals, txData.from);
// execute the transaction through the Coordinator Contract
const txDataWithDefaults = {
...this._txDefaults,
...txData, // override defaults
};
const txHash = this._contractInstance
.executeTransaction(signedZrxTx, txData.from, signedZrxTx.signature, approvalSignatures)
.sendTransactionAsync(txDataWithDefaults, sendTxOpts);
return txHash;
}
private async _generateSignedZeroExTransactionAsync(
data: string,
signerAddress: string,
gasPrice?: BigNumber | string | number,
): Promise<SignedZeroExTransaction> {
const transaction: ZeroExTransaction = {
salt: generatePseudoRandomSalt(),
signerAddress,
data,
domain: {
verifyingContract: this.exchangeAddress,
chainId: await this._web3Wrapper.getChainIdAsync(),
},
expirationTimeSeconds: new BigNumber(
Math.floor(Date.now() / 1000) +
DEFAULT_APPROVAL_EXPIRATION_TIME_SECONDS -
DEFAULT_EXPIRATION_TIME_BUFFER_SECONDS,
),
gasPrice: gasPrice ? new BigNumber(gasPrice) : new BigNumber(1),
};
const signedZrxTx = await signatureUtils.ecSignTransactionAsync(
this._web3Wrapper.getProvider(),
transaction,
transaction.signerAddress,
);
return signedZrxTx;
}
private async _getApprovalsAsync(
transaction: SignedZeroExTransaction,
orders: Order[],
txOrigin: string,
): Promise<string[]> {
const coordinatorOrders = orders.filter(o => o.senderAddress === this.address);
if (coordinatorOrders.length === 0) {
return [];
}
const serverEndpointsToOrders = await this._mapServerEndpointsToOrdersAsync(coordinatorOrders);
// make server requests
const errorResponses: CoordinatorServerResponse[] = [];
const approvalResponses: CoordinatorServerResponse[] = [];
for (const endpoint of Object.keys(serverEndpointsToOrders)) {
const response = await this._executeServerRequestAsync(transaction, txOrigin, endpoint);
if (response.isError) {
errorResponses.push(response);
} else {
approvalResponses.push(response);
}
}
// if no errors
if (errorResponses.length === 0) {
// concatenate all approval responses
return approvalResponses.reduce(
(accumulator, response) =>
accumulator.concat((response.body as CoordinatorServerApprovalResponse).signatures),
[] as string[],
);
} else {
// format errors and approvals
// concatenate approvals
const notCoordinatorOrders = orders.filter(o => o.senderAddress !== this.address);
const approvedOrdersNested = approvalResponses.map(resp => {
const endpoint = resp.coordinatorOperator;
return serverEndpointsToOrders[endpoint];
});
const approvedOrders = flatten(approvedOrdersNested.concat(notCoordinatorOrders));
// lookup orders with errors
const errorsWithOrders = errorResponses.map(resp => {
const endpoint = resp.coordinatorOperator;
return {
...resp,
orders: serverEndpointsToOrders[endpoint],
};
});
// throw informative error
const cancellations = new Array();
throw new CoordinatorServerError(
CoordinatorServerErrorMsg.FillFailed,
approvedOrders,
cancellations,
errorsWithOrders,
);
}
}
private async _getServerEndpointOrThrowAsync(order: Order): Promise<string> {
const cached = this._feeRecipientToEndpoint[order.feeRecipientAddress];
const endpoint =
cached !== undefined
? cached
: await _fetchServerEndpointOrThrowAsync(order.feeRecipientAddress, this._registryInstance);
return endpoint;
async function _fetchServerEndpointOrThrowAsync(
feeRecipient: string,
registryInstance: CoordinatorRegistryContract,
): Promise<string> {
const coordinatorOperatorEndpoint = await registryInstance.getCoordinatorEndpoint(feeRecipient).callAsync();
if (coordinatorOperatorEndpoint === '' || coordinatorOperatorEndpoint === undefined) {
throw new Error(
`No Coordinator server endpoint found in Coordinator Registry for feeRecipientAddress: ${feeRecipient}. Registry contract address: [${
registryInstance.address
}] Order: [${JSON.stringify(order)}]`,
);
}
return coordinatorOperatorEndpoint;
}
}
private async _executeServerRequestAsync(
signedTransaction: SignedZeroExTransaction,
txOrigin: string,
endpoint: string,
): Promise<CoordinatorServerResponse> {
const requestPayload = {
signedTransaction,
txOrigin,
};
const response = await fetchAsync(`${endpoint}/v2/request_transaction?chainId=${this.chainId}`, {
body: JSON.stringify(requestPayload),
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
});
const isError = response.status !== HttpStatus.OK;
const isValidationError = response.status === HttpStatus.BAD_REQUEST;
const json = isError && !isValidationError ? undefined : await response.json();
const result = {
isError,
status: response.status,
body: isError ? undefined : json,
error: isError ? json : undefined,
request: requestPayload,
coordinatorOperator: endpoint,
};
return result;
}
private async _mapServerEndpointsToOrdersAsync(
coordinatorOrders: Order[],
): Promise<{ [endpoint: string]: Order[] }> {
const groupByFeeRecipient: { [feeRecipient: string]: Order[] } = {};
for (const order of coordinatorOrders) {
const feeRecipient = order.feeRecipientAddress;
if (groupByFeeRecipient[feeRecipient] === undefined) {
groupByFeeRecipient[feeRecipient] = [] as Order[];
}
groupByFeeRecipient[feeRecipient].push(order);
}
const serverEndpointsToOrders: { [endpoint: string]: Order[] } = {};
for (const orders of Object.values(groupByFeeRecipient)) {
const endpoint = await this._getServerEndpointOrThrowAsync(orders[0]);
if (serverEndpointsToOrders[endpoint] === undefined) {
serverEndpointsToOrders[endpoint] = [];
}
serverEndpointsToOrders[endpoint] = serverEndpointsToOrders[endpoint].concat(orders);
}
return serverEndpointsToOrders;
}
}
function getMakerAddressOrThrow(orders: Array<Order | SignedOrder>): string {
const uniqueMakerAddresses = new Set(orders.map(o => o.makerAddress));
if (uniqueMakerAddresses.size > 1) {
throw new Error(`All orders in a batch must have the same makerAddress`);
}
return orders[0].makerAddress;
}
// tslint:disable:max-file-line-count | the_stack |
import { Diagram } from '../diagram';
import { NodeModel, LaneModel, PhaseModel, SwimLaneModel } from '../objects/node-model';
import { Node, Shape, SwimLane } from '../objects/node';
import { GridPanel, GridCell, GridRow, RowDefinition, ColumnDefinition } from '../core/containers/grid';
import { Lane, Phase } from '../objects/node';
import { DiagramAction, NodeConstraints, DiagramConstraints, DiagramEvent, ElementAction } from '../enum/enum';
import { cloneObject, randomId } from './../utility/base-util';
import { Container } from '../core/containers/container';
import { DiagramElement } from '../core/elements/diagram-element';
import { TextElement } from '../core/elements/text-element';
import { Size } from '../primitives/size';
import { PointModel } from '../primitives/point-model';
import { Canvas } from '../core/containers/canvas';
import { Rect } from '../primitives/rect';
import { HistoryEntry } from '../diagram/history';
import { StackEntryObject, ICollectionChangeEventArgs } from '../objects/interface/IElement';
import { Connector } from '../objects/connector';
import { ConnectorModel } from '../objects/connector-model';
import { SelectorModel } from '../objects/node-model';
import { checkParentAsContainer, findBounds, removeChildInContainer } from '../interaction/container-interaction';
import { IElement } from '../objects/interface/IElement';
import { ClipBoardObject } from '../interaction/command-manager';
import { canSelect } from './constraints-util';
/**
* SwimLane modules are used to rendering and interaction.
*/
/** @private */
/**
* initSwimLane method \
*
* @returns {void} initSwimLane method .\
* @param { GridPanel} grid - provide the grid value.
* @param { Diagram} diagram - provide the diagram value.
* @param {NodeModel} node - provide the node value.
* @private
*/
export function initSwimLane(grid: GridPanel, diagram: Diagram, node: NodeModel): void {
if (!node.width && (node.shape as SwimLane).phases.length === 0) {
node.width = 100;
}
const row: RowDefinition[] = []; const columns: ColumnDefinition[] = [];
let index: number = 0; const shape: SwimLaneModel = node.shape as SwimLaneModel;
const orientation: boolean = shape.orientation === 'Horizontal' ? true : false;
if (shape.header && (shape as SwimLane).hasHeader) {
createRow(row, shape.header.height);
}
initGridRow(row, orientation, node);
initGridColumns(columns, orientation, node);
grid.setDefinitions(row, columns);
if (shape.header && (shape as SwimLane).hasHeader) {
headerDefine(grid, diagram, node);
index++;
}
if (shape.phases.length > 0 && shape.phaseSize) {
for (let k: number = 0; k < shape.phases.length; k++) {
if (shape.phases[k].id === '') {
shape.phases[k].id = randomId();
}
phaseDefine(grid, diagram, node, index, orientation, k);
}
index++;
}
if (shape.lanes.length > 0) {
for (let k: number = 0; k < shape.lanes.length; k++) {
if (shape.lanes[k].id === '') {
shape.lanes[k].id = randomId();
}
laneCollection(grid, diagram, node, index, k, orientation);
index++;
}
}
}
/**
* addObjectToGrid method \
*
* @returns {Container} addObjectToGrid method .\
* @param { Diagram} diagram - provide the diagram value.
* @param { GridPanel} grid - provide the grid value.
* @param {NodeModel} parent - provide the parent value.
* @param {NodeModel} object - provide the object value.
* @param {boolean} isHeader - provide the isHeader value.
* @param {boolean} isPhase - provide the isPhase value.
* @param {boolean} isLane - provide the isLane value.
* @param {string} canvas - provide the canvas value.
* @private
*/
export function addObjectToGrid(
diagram: Diagram, grid: GridPanel, parent: NodeModel, object: NodeModel,
isHeader?: boolean, isPhase?: boolean, isLane?: boolean, canvas?: string): Container {
const node: Node = new Node(diagram, 'nodes', object, true);
node.parentId = parent.id;
node.isHeader = (isHeader) ? true : false; node.isPhase = (isPhase) ? true : false;
node.isLane = (isLane) ? true : false;
const id: string = (isPhase) ? 'PhaseHeaderParent' : 'LaneHeaderParent';
if (canvas) { node[id] = canvas; }
node.constraints &= ~(NodeConstraints.InConnect | NodeConstraints.OutConnect);
node.constraints |= NodeConstraints.HideThumbs;
diagram.initObject(node);
diagram.nodes.push(node);
if (node.wrapper.children.length > 0) {
for (let i: number = 0; i < node.wrapper.children.length; i++) {
const child: DiagramElement = node.wrapper.children[i];
if (child instanceof DiagramElement) {
child.isCalculateDesiredSize = false;
}
if (child instanceof TextElement) {
child.canConsiderBounds = false;
if (!isHeader && ((parent.shape as SwimLaneModel).orientation === 'Vertical' && isPhase) ||
((parent.shape as SwimLaneModel).orientation !== 'Vertical' && isLane)) {
child.isLaneOrientation = true;
child.refreshTextElement();
}
}
}
node.wrapper.measure(new Size(undefined, undefined));
node.wrapper.arrange(node.wrapper.desiredSize);
}
return node.wrapper;
}
/**
* headerDefine method \
*
* @returns {void} headerDefine method .\
* @param { GridPanel} grid - provide the grid value.
* @param {Diagram} diagram - provide the diagram value.
* @param {NodeModel} object - provide the object value.
* @private
*/
export function headerDefine(grid: GridPanel, diagram: Diagram, object: NodeModel): void {
let maxWidth: number = 0;
const columns: ColumnDefinition[] = grid.columnDefinitions();
const shape: SwimLaneModel = object.shape as SwimLaneModel;
for (let i: number = 0; i < columns.length; i++) {
maxWidth += columns[i].width;
}
shape.header.id = shape.header.id || randomId();
const node: NodeModel = {
id: object.id + shape.header.id,
annotations: [cloneObject(shape.header.annotation)],
style: shape.header.style ? shape.header.style : undefined,
offsetX: object.offsetX, offsetY: object.offsetY,
rowIndex: 0, columnIndex: 0,
maxWidth: maxWidth,
container: { type: 'Canvas', orientation: 'Horizontal' }
} as NodeModel;
if (!canSelect(object)) {
node.constraints &= ~NodeConstraints.Select;
}
const wrapper: Container = addObjectToGrid(diagram, grid, object, node, true);
grid.addObject(wrapper, 0, 0, 1, grid.columnDefinitions().length);
}
/**
* phaseDefine method \
*
* @returns {void} phaseDefine method .\
* @param { GridPanel} grid - provide the grid value.
* @param {Diagram} diagram - provide the diagram value.
* @param {NodeModel} object - provide the object value.
* @param {number} indexValue - provide the indexValue value.
* @param {boolean} orientation - provide the orientation value.
* @param {number} phaseIndex - provide the phaseIndex value.
* @private
*/
export function phaseDefine(
grid: GridPanel, diagram: Diagram, object: NodeModel, indexValue: number, orientation: boolean, phaseIndex: number): void {
let rowValue: number = 0; let colValue: number = 0; let maxWidth: number;
const shape: SwimLaneModel = object.shape as SwimLaneModel;
if (orientation) {
colValue = phaseIndex; rowValue = indexValue;
maxWidth = grid.columnDefinitions()[phaseIndex].width;
} else {
rowValue = shape.header && (shape as SwimLane).hasHeader ? phaseIndex + 1 : phaseIndex;
}
const phaseObject: NodeModel = {
annotations: [cloneObject(shape.phases[phaseIndex].header.annotation)],
maxWidth: maxWidth,
id: object.id + shape.phases[phaseIndex].id + '_header',
addInfo:shape.phases[phaseIndex].addInfo,
offsetX: object.offsetX, offsetY: object.offsetY,
style: shape.phases[phaseIndex].style,
rowIndex: rowValue, columnIndex: colValue,
container: { type: 'Canvas', orientation: orientation ? 'Horizontal' : 'Vertical' }
};
phaseObject.annotations[0].rotateAngle = orientation ? 0 : 270;
if (!canSelect(object)) {
phaseObject.constraints &= ~NodeConstraints.Select;
}
shape.phases[phaseIndex].header.id = phaseObject.id;
const wrapper: Container = addObjectToGrid(
diagram, grid, object, phaseObject, false, true, false, shape.phases[phaseIndex].id);
grid.addObject(wrapper, rowValue, colValue);
}
/**
* laneCollection method \
*
* @returns {void} laneCollection method .\
* @param { GridPanel} grid - provide the grid value.
* @param {Diagram} diagram - provide the diagram value.
* @param {NodeModel} object - provide the object value.
* @param {number} indexValue - provide the indexValue value.
* @param {number} laneIndex - provide the laneIndex value.
* @param {boolean} orientation - provide the orientation value.
* @private
*/
export function laneCollection(
grid: GridPanel, diagram: Diagram, object: NodeModel, indexValue: number, laneIndex: number, orientation: boolean): void {
let laneNode: NodeModel; let parentWrapper: Container; let gridCell: GridCell; let canvas: NodeModel; let childWrapper: Container;
const shape: SwimLaneModel = object.shape as SwimLaneModel;
const value: number = shape.phases.length || 1;
const isHeader: number = (shape.header && (shape as SwimLane).hasHeader) ? 1 : 0;
let rowValue: number = orientation ? indexValue : isHeader;
const phaseCount: number = (shape.phaseSize && shape.phases.length > 0) ? 1 : 0;
for (let l: number = 0; l < value; l++) {
let colValue: number = orientation ? l : laneIndex + phaseCount;
gridCell = grid.rows[rowValue].cells[colValue];
canvas = {
id: object.id + shape.lanes[laneIndex].id + l,
rowIndex: rowValue, columnIndex: colValue,
width: gridCell.minWidth, height: gridCell.minHeight,
offsetX: object.offsetX, offsetY: object.offsetY,
style: shape.lanes[laneIndex].style,
addInfo:shape.lanes[laneIndex].addInfo,
constraints: NodeConstraints.Default | NodeConstraints.ReadOnly | NodeConstraints.AllowDrop,
container: { type: 'Canvas', orientation: orientation ? 'Horizontal' : 'Vertical' }
};
if (!canSelect(object)) {
canvas.constraints &= ~NodeConstraints.Select;
}
parentWrapper = addObjectToGrid(diagram, grid, object, canvas, false, false, true);
parentWrapper.children[0].isCalculateDesiredSize = false;
if (l === 0) {
laneNode = {
id: object.id + shape.lanes[laneIndex].id + '_' + l + '_header',
style: shape.lanes[laneIndex].header.style,
annotations: [cloneObject(shape.lanes[laneIndex].header.annotation)],
offsetX: object.offsetX, offsetY: object.offsetY,
rowIndex: rowValue, columnIndex: colValue,
container: { type: 'Canvas', orientation: orientation ? 'Horizontal' : 'Vertical' }
};
laneNode.annotations[0].rotateAngle = orientation ? 270 : 0;
shape.lanes[laneIndex].header.id = laneNode.id;
// eslint-disable-next-line
(orientation) ? laneNode.width = shape.lanes[laneIndex].header.width :
laneNode.height = shape.lanes[laneIndex].header.height;
if (!canSelect(object)) {
laneNode.constraints &= ~NodeConstraints.Select;
}
childWrapper = addObjectToGrid(
diagram, grid, object, laneNode, false, false, true, shape.lanes[laneIndex].id);
if (orientation) {
childWrapper.children[0].elementActions = childWrapper.children[0].elementActions | ElementAction.HorizontalLaneHeader;
}
parentWrapper.children.push(childWrapper);
}
grid.addObject(parentWrapper, rowValue, colValue);
if (!orientation) { rowValue++; }
colValue = orientation ? l : laneIndex + 1;
}
}
/**
* createRow method \
*
* @returns {void} createRow method .\
* @param { RowDefinition[]} row - provide the row value.
* @param {number} height - provide the height value.
* @private
*/
export function createRow(row: RowDefinition[], height: number): void {
const rows: RowDefinition = new RowDefinition();
rows.height = height;
row.push(rows);
}
/**
* createColumn method \
*
* @returns {void} createColumn method .\
* @param {number} width - provide the width value.
* @private
*/
export function createColumn(width: number): ColumnDefinition {
const cols: ColumnDefinition = new ColumnDefinition();
cols.width = width;
return cols;
}
/**
* initGridRow method \
*
* @returns {void} initGridRow method .\
* @param {RowDefinition[]} row - provide the row value.
* @param {boolean} orientation - provide the row value.
* @param {NodeModel} object - provide the row value.
* @private
*/
export function initGridRow(row: RowDefinition[], orientation: boolean, object: NodeModel): void {
let totalHeight: number = 0; let height: number;
const shape: SwimLaneModel = object.shape as SwimLaneModel;
if (row.length > 0) {
for (let i: number = 0; i < row.length; i++) {
totalHeight += row[i].height;
}
}
if (orientation) {
if (shape.phases.length > 0 && shape.phaseSize) {
totalHeight += shape.phaseSize;
createRow(row, shape.phaseSize);
}
if (shape.lanes.length > 0) {
for (let i: number = 0; i < shape.lanes.length; i++) {
height = shape.lanes[i].height; totalHeight += height;
if (i === shape.lanes.length - 1 && totalHeight < object.height) {
height += object.height - totalHeight;
}
createRow(row, height);
}
}
} else {
if (shape.phases.length > 0) {
let phaseHeight: number = 0;
for (let i: number = 0; i < shape.phases.length; i++) {
let phaseOffset: number = shape.phases[i].offset;
if (i === 0) {
phaseHeight += phaseOffset;
} else {
phaseOffset -= phaseHeight;
phaseHeight += phaseOffset;
}
height = phaseOffset; totalHeight += height;
if (i === shape.phases.length - 1 && totalHeight < object.height) {
height += object.height - totalHeight;
}
createRow(row, height);
}
} else {
createRow(row, object.height);
}
}
}
/**
* initGridColumns method \
*
* @returns {void} initGridRow method .\
* @param {ColumnDefinition[]} columns - provide the row value.
* @param {boolean} orientation - provide the row value.
* @param {NodeModel} object - provide the row value.
* @private
*/
export function initGridColumns(columns: ColumnDefinition[], orientation: boolean, object: NodeModel): void {
let totalWidth: number = 0; const shape: SwimLaneModel = object.shape as SwimLaneModel;
let phaseOffset: number; let cols: ColumnDefinition;
let k: number; let j: number; let value: number;
if (shape.phases.length > 0 && shape.orientation === 'Horizontal') {
for (j = 0; j < shape.phases.length; j++) {
phaseOffset = shape.phases[j].offset;
if (j === 0) {
totalWidth += phaseOffset;
} else {
phaseOffset -= totalWidth;
totalWidth += phaseOffset;
}
cols = createColumn(phaseOffset);
if (j === shape.phases.length - 1 && totalWidth < object.width) {
cols.width += object.width - totalWidth;
}
columns.push(cols);
}
} else if (!orientation) {
value = (shape.phaseSize && shape.phases.length > 0) ? shape.lanes.length
+ 1 : shape.lanes.length;
if (shape.phaseSize && shape.phases.length > 0) {
totalWidth += shape.phaseSize;
cols = createColumn(shape.phaseSize);
columns.push(cols);
}
for (k = 0; k < shape.lanes.length; k++) {
totalWidth += shape.lanes[k].width;
cols = createColumn(shape.lanes[k].width);
if (k === shape.lanes.length - 1 && totalWidth < object.width) {
cols.width += object.width - totalWidth;
}
columns.push(cols);
}
if ((shape.phases.length === 0 && shape.lanes.length === 0)) {
cols = createColumn(object.width);
columns.push(cols);
}
} else {
cols = createColumn(object.width);
columns.push(cols);
}
}
/**
* getConnectors method \
*
* @returns {void} getConnectors method .\
* @param {Diagram} diagram - provide the row value.
* @param {GridPanel} grid - provide the row value.
* @param {number} rowIndex - provide the row value.
* @param {boolean} isRowUpdate - provide the row value.
* @private
*/
export function getConnectors(diagram: Diagram, grid: GridPanel, rowIndex: number, isRowUpdate: boolean): string[] {
const connectors: string[] = []; let conn: number = 0; let childNode: Container; let node: Node;
let k: number; let i: number; let j: number; let canvas: Container; let row: GridRow;
const length: number = grid.rowDefinitions().length; let edges: string[];
for (let i: number = 0; i < length; i++) {
row = grid.rows[i];
for (j = 0; j < row.cells.length; j++) {
canvas = row.cells[j].children[0] as Container;
if (canvas && canvas.children && canvas.children.length) {
for (k = 1; k < canvas.children.length; k++) {
childNode = canvas.children[k] as Container;
node = diagram.getObject(childNode.id) as Node;
if (node && ((node as Node).inEdges.length > 0 || (node as Node).outEdges.length > 0)) {
edges = (node as Node).inEdges.concat((node as Node).outEdges);
for (conn = 0; conn < edges.length; conn++) {
if (connectors.indexOf(edges[conn]) === -1) {
connectors.push(edges[conn]);
}
}
}
}
}
}
}
return connectors;
}
/**
* swimLaneMeasureAndArrange method \
*
* @returns {void} swimLaneMeasureAndArrange method .\
* @param {NodeModel} obj - provide the row value.
* @private
*/
export function swimLaneMeasureAndArrange(obj: NodeModel): void {
const canvas: Container = obj.wrapper;
canvas.measure(new Size(obj.width, obj.height));
if (canvas.children[0] instanceof GridPanel) {
const grid: GridPanel = canvas.children[0] as GridPanel; let isMeasure: boolean = false;
if (grid.width && grid.width < grid.desiredSize.width) {
isMeasure = true; grid.width = grid.desiredSize.width;
}
if (grid.height && grid.height < grid.desiredSize.height) {
isMeasure = true; grid.height = grid.desiredSize.height;
}
if (isMeasure) { grid.measure(new Size(grid.width, grid.height)); }
}
canvas.arrange(canvas.desiredSize);
}
/**
* ChangeLaneIndex method \
*
* @returns {void} ChangeLaneIndex method .\
* @param {Diagram} diagram - provide the row value.
* @param {NodeModel} obj - provide the row value.
* @param {number} startRowIndex - provide the row value.
* @private
*/
export function ChangeLaneIndex(diagram: Diagram, obj: NodeModel, startRowIndex: number): void {
const container: GridPanel = obj.wrapper.children[0] as GridPanel;
let i: number; let j: number; let k: number; let object: Node; let subChild: Node;
let row: GridRow; let cell: GridCell; let child: Canvas;
for (i = startRowIndex; i < container.rows.length; i++) {
row = container.rows[i];
for (j = 0; j < row.cells.length; j++) {
cell = row.cells[j];
if (cell.children && cell.children.length > 0) {
for (k = 0; k < cell.children.length; k++) {
child = cell.children[k] as Canvas;
object = diagram.nameTable[child.id] as Node;
if (object.isLane && child.children.length > 1) {
subChild = diagram.nameTable[child.children[1].id] as Node;
if (subChild && subChild.isLane) {
subChild.rowIndex = i; subChild.columnIndex = j;
}
}
object.rowIndex = i; object.columnIndex = j;
}
}
}
}
}
/**
* arrangeChildNodesInSwimLane method \
*
* @returns {void} arrangeChildNodesInSwimLane method .\
* @param {Diagram} diagram - provide the row value.
* @param {NodeModel} obj - provide the row value.
* @private
*/
export function arrangeChildNodesInSwimLane(diagram: Diagram, obj: NodeModel): void {
const grid: GridPanel = obj.wrapper.children[0] as GridPanel;
const shape: SwimLaneModel = obj.shape as SwimLaneModel;
const padding: number = (shape as SwimLane).padding;
const lanes: LaneModel[] = shape.lanes; let top: number = grid.bounds.y;
let rowvalue: number; let columnValue: number;
const phaseCount: number = (shape.phaseSize > 0) ? shape.phases.length : 0;
let node: NodeModel; let canvas: Container; let cell: GridCell;
let i: number; let j: number; let k: number;
const orientation: boolean = shape.orientation === 'Horizontal' ? true : false;
const col: number = orientation ? shape.phases.length || 1 : lanes.length + 1;
let row: number = orientation ? ((shape.header && (shape as SwimLane).hasHeader) ? 1 : 0) +
(shape.phases.length > 0 ? 1 : 0) + (shape.lanes.length)
: (shape.header && (shape as SwimLane).hasHeader ? 1 : 0) + shape.phases.length;
if (phaseCount === 0 && !orientation && shape.lanes.length) {
row += 1;
}
if (orientation) {
rowvalue = (shape.header && (shape as SwimLane).hasHeader ? 1 : 0) + (phaseCount > 0 ? 1 : 0);
columnValue = 0;
} else {
rowvalue = (shape.header && (shape as SwimLane).hasHeader ? 1 : 0);
columnValue = phaseCount > 0 ? 1 : 0;
}
if (lanes.length > 0) {
top += (shape.header && (shape as SwimLane).hasHeader) ? shape.header.height : 0;
for (i = 0; i < lanes.length; i++) {
for (j = 0; j < lanes[i].children.length; j++) {
node = lanes[i].children[j];
node.offsetX = lanes[i].width;
node.offsetY = lanes[i].height;
diagram.initObject(node as Node);
diagram.nodes.push(node);
canvas = node.wrapper;
if (orientation) {
for (k = columnValue; k < col; k++) {
cell = grid.rows[rowvalue].cells[k];
if (canvas.margin.left < (cell.bounds.right - grid.bounds.x)) {
(node as Node).parentId = cell.children[0].id;
if (k > columnValue) {
canvas.margin.left = canvas.margin.left - (cell.bounds.left - grid.bounds.left);
} else {
if (((cell.children[0] as Canvas).children[1].actualSize.width + padding) >= canvas.margin.left) {
canvas.margin.left = (cell.children[0] as Canvas).children[1].actualSize.width + padding;
}
}
if (canvas.margin.left < padding) { canvas.margin.left = padding; }
if (canvas.margin.top < padding) { canvas.margin.top = padding; }
addChildToLane(canvas, node, diagram);
break;
}
}
} else {
for (let k: number = rowvalue; k < row; k++) {
cell = grid.rows[k].cells[columnValue];
if (canvas.margin.top < (cell.bounds.bottom - top)) {
(node as Node).parentId = cell.children[0].id;
if (k > rowvalue) {
canvas.margin.top = canvas.margin.top - (cell.bounds.top - top);
} else {
if (((cell.children[0] as Canvas).children[1].actualSize.height + padding) >= canvas.margin.top) {
canvas.margin.top = (cell.children[0] as Canvas).children[1].actualSize.height + padding;
}
}
if (canvas.margin.left < padding) { canvas.margin.left = padding; }
if (canvas.margin.top < padding) { canvas.margin.top = padding; }
addChildToLane(canvas, node, diagram);
break;
}
}
}
}
// eslint-disable-next-line
orientation ? rowvalue++ : columnValue++;
}
}
grid.measure(new Size(obj.width, obj.height)); grid.arrange(grid.desiredSize);
updateChildOuterBounds(grid, obj);
obj.width = obj.wrapper.width = grid.width;
obj.height = obj.wrapper.height = grid.height;
updateHeaderMaxWidth(diagram, obj);
obj.wrapper.measure(new Size(obj.width, obj.height));
obj.wrapper.arrange(grid.desiredSize);
checkLaneChildrenOffset(obj);
checkPhaseOffset(obj, diagram);
checkLaneSize(obj);
}
/**
* addChildToLane method \
*
* @returns {void} addChildToLane method .\
* @param {Container} canvas - provide the row value.
* @param {NodeModel} node - provide the row value.
* @param {Diagram} diagram - provide the row value.
* @private
*/
function addChildToLane(canvas: Container, node: NodeModel, diagram: Diagram): void {
canvas.measure(new Size(node.width, node.height));
canvas.arrange(canvas.desiredSize);
const parent: NodeModel = diagram.getObject((node as Node).parentId);
diagram.addChild(parent, node.id);
}
/**
* updateChildOuterBounds method \
*
* @returns {void} updateChildOuterBounds method .\
* @param {GridPanel} grid - provide the row value.
* @param {NodeModel} obj - provide the row value.
* @private
*/
export function updateChildOuterBounds(grid: GridPanel, obj: NodeModel): void {
const columnDefinitions: ColumnDefinition[] = grid.columnDefinitions();
const rowDefinitions: RowDefinition[] = grid.rowDefinitions();
let i: number; let k: number; let j: number; let cell: GridCell; let child: Canvas; let row: GridRow;
let rowIndex: number = findStartLaneIndex(obj);
if ((obj.shape as SwimLaneModel).orientation === 'Vertical') {
if (rowIndex === 0) {
rowIndex = ((obj.shape as SwimLaneModel).header && (obj.shape as SwimLane).hasHeader) ? 1 : 0;
}
}
const padding: number = (obj.shape as SwimLane).padding;
for (i = 0; i < columnDefinitions.length; i++) {
grid.updateColumnWidth(i, columnDefinitions[i].width, true, padding);
}
for (i = rowIndex; i < rowDefinitions.length; i++) {
grid.updateRowHeight(i, rowDefinitions[i].height, true, padding);
}
for (k = 0; k < rowDefinitions.length; k++) {
row = grid.rows[k];
for (i = 0; i < columnDefinitions.length; i++) {
cell = row.cells[i];
if (cell.children && cell.children.length > 0) {
for (j = 0; j < cell.children.length; j++) {
child = cell.children[j] as Canvas;
if (child.maxWidth) {
child.maxWidth = cell.actualSize.width;
}
if (child.maxHeight) {
child.maxHeight = cell.actualSize.height;
}
}
}
}
}
}
/**
* checkLaneSize method \
*
* @returns {void} checkLaneSize method .\
* @param {NodeModel} obj - provide the row value.
* @private
*/
export function checkLaneSize(obj: NodeModel): void {
if (obj.shape.type === 'SwimLane' && !(obj.shape as SwimLaneModel).isLane && !(obj.shape as SwimLaneModel).isPhase) {
let lane: LaneModel; let i: number; let columns: ColumnDefinition[];
let size: number; //let laneCount: number = 0;
const lanes: LaneModel[] = (obj.shape as SwimLaneModel).lanes;
let laneIndex: number = findStartLaneIndex(obj);
const rows: RowDefinition[] = (obj.wrapper.children[0] as GridPanel).rowDefinitions();
for (i = 0; i < lanes.length; i++, laneIndex++) {
lane = lanes[i];
if ((obj.shape as SwimLaneModel).orientation === 'Horizontal') {
size = rows[laneIndex].height;
if (lane.height !== size) {
lane.height = size;
}
} else {
columns = (obj.wrapper.children[0] as GridPanel).columnDefinitions();
size = columns[laneIndex].width;
if (lane.width !== size) {
lane.width = size;
}
}
}
}
}
/**
* checkPhaseOffset method \
*
* @returns {void} checkPhaseOffset method .\
* @param {NodeModel} obj - provide the obj value.
* @param {Diagram} diagram - provide the obj value.
* @private
*/
export function checkPhaseOffset(obj: NodeModel, diagram: Diagram): void {
const shape: SwimLaneModel = obj.shape as SwimLaneModel;
const phases: PhaseModel[] = shape.phases; let i: number; let offset: number;
let phaseRow: GridRow; let phase: Canvas;
const gridRowIndex: number = (shape.header && (shape as SwimLane).hasHeader) ? 1 : 0;
let grid: GridPanel = obj.wrapper.children[0] as GridPanel;
const top: number = grid.bounds.y + ((shape.header && (shape as SwimLane).hasHeader) ? shape.header.height : 0);
if (obj.shape.type === 'SwimLane') {
obj = diagram.getObject(obj.id) || obj;
if (phases.length > 0) {
grid = obj.wrapper.children[0] as GridPanel;
if (shape.orientation === 'Horizontal') {
phaseRow = (shape.header && (shape as SwimLane).hasHeader) ? grid.rows[1] : grid.rows[0];
for (i = 0; i < phases.length; i++) {
phase = phaseRow.cells[i].children[0] as Canvas;
offset = phase.bounds.right - grid.bounds.x;
if (phases[i].offset !== offset) {
phases[i].offset = offset;
}
(diagram.nameTable[phase.id] as NodeModel).maxWidth = phase.maxWidth;
}
} else {
for (i = 0; i < phases.length; i++) {
phase = grid.rows[gridRowIndex + i].cells[0].children[0] as Canvas;
offset = phase.bounds.bottom - top;
if (phases[i].offset !== offset) {
phases[i].offset = offset;
}
(diagram.nameTable[phase.id] as NodeModel).maxWidth = phase.maxWidth;
}
}
}
}
}
/**
* updateConnectorsProperties method \
*
* @returns {void} checkPhaseOffset method .\
* @param {string[]} connectors - provide the obj value.
* @param {Diagram} diagram - provide the obj value.
* @private
*/
export function updateConnectorsProperties(connectors: string[], diagram: Diagram): void {
if (connectors && connectors.length > 0) {
let edges: Connector;
if (diagram.lineRoutingModule && (diagram.constraints & DiagramConstraints.LineRouting)) {
diagram.lineRoutingModule.renderVirtualRegion(diagram, true);
}
for (let i: number = 0; i < connectors.length; i++) {
edges = diagram.getObject(connectors[i]) as Connector;
if (diagram.lineRoutingModule && (diagram.constraints & DiagramConstraints.LineRouting) && edges.type === 'Orthogonal') {
diagram.lineRoutingModule.refreshConnectorSegments(diagram, edges, true);
} else {
diagram.connectorPropertyChange(edges, {} as Connector, {
sourceID: edges.sourceID, targetID: edges.targetID
} as Connector);
}
}
}
}
/**
* laneInterChanged method \
*
* @returns {void} laneInterChanged method .\
* @param {Diagram} diagram - provide the diagram value.
* @param {NodeModel} obj - provide the obj value.
* @param {NodeModel} target - provide the target value.
* @param {PointModel} position - provide the position value.
* @private
*/
export function laneInterChanged(diagram: Diagram, obj: NodeModel, target: NodeModel, position?: PointModel): void {
let index: number; let undoElement: StackEntryObject; let entry: HistoryEntry; let redoElement: StackEntryObject;
let sourceIndex: number; let targetIndex: number; let temp: LaneModel;
let sourceLaneIndex: number; let targetLaneIndex: number; let rowIndex: number;
const swimLane: NodeModel = ((diagram.getObject((obj as Node).parentId) as NodeModel));
const shape: SwimLaneModel = swimLane.shape as SwimLaneModel;
const grid: GridPanel = swimLane.wrapper.children[0] as GridPanel;
const lanes: LaneModel[] = shape.lanes;
const connectors: string[] = getConnectors(diagram, grid, obj.rowIndex, true);
if ((shape.orientation === 'Horizontal' && obj.rowIndex !== target.rowIndex) ||
(shape.orientation === 'Vertical' && obj.columnIndex !== target.columnIndex)) {
if (shape.orientation === 'Horizontal') {
sourceIndex = obj.rowIndex; targetIndex = (target as Node).rowIndex;
index = ((shape.header && (shape as SwimLane).hasHeader) ? 1 : 0) + (shape.phases.length && shape.phaseSize ? 1 : 0);
sourceLaneIndex = obj.rowIndex - index;
targetLaneIndex = (target as Node).rowIndex - index;
if (lanes[sourceLaneIndex].canMove) {
if (sourceLaneIndex < targetLaneIndex) {
if (position && target.wrapper.offsetY > position.y) {
targetIndex += (targetLaneIndex > 0) ? -1 : 1;
targetLaneIndex += (targetLaneIndex > 0) ? -1 : 1;
}
} else {
if (position && target.wrapper.offsetY < position.y) {
targetIndex += 1; targetLaneIndex += 1;
}
}
if (sourceIndex !== targetIndex) {
grid.updateRowIndex(sourceIndex, targetIndex);
}
}
} else {
sourceIndex = obj.columnIndex;
targetIndex = target.columnIndex;
index = (shape.phases.length && shape.phaseSize) ? 1 : 0;
sourceLaneIndex = obj.columnIndex - index;
targetLaneIndex = (target as Node).columnIndex - index;
rowIndex = (shape.header && (shape as SwimLane).hasHeader) ? 1 : 0;
if (lanes[sourceLaneIndex].canMove) {
if (sourceLaneIndex < targetLaneIndex) {
if (position && target.wrapper.offsetX > position.x) {
targetIndex += (targetLaneIndex > 0) ? -1 : 1;
targetLaneIndex += (targetLaneIndex > 0) ? -1 : 1;
}
} else {
if (position && target.wrapper.offsetX < position.x) {
targetIndex += 1; targetLaneIndex += 1;
}
}
if (sourceIndex !== targetIndex) {
if ((shape.phaseSize === 0 || shape.phases.length === 0) && (targetIndex === 0 || sourceIndex === 0)) {
if (shape.header && (shape as SwimLane).hasHeader) {
const changeHeaderIndex: number = (targetIndex === 0) ? sourceIndex : targetIndex;
grid.rows[0].cells[changeHeaderIndex].children = grid.rows[0].cells[0].children;
grid.rows[0].cells[changeHeaderIndex].columnSpan = grid.rows[0].cells[0].columnSpan;
grid.rows[0].cells[0].children = [];
}
}
grid.updateColumnIndex(0, sourceIndex, targetIndex);
}
}
}
if (sourceIndex !== targetIndex) {
temp = lanes[sourceLaneIndex];
if (temp.canMove) {
undoElement = {
target: cloneObject(target), source: cloneObject(obj)
};
temp = lanes[sourceLaneIndex];
lanes.splice(sourceLaneIndex, 1);
lanes.splice(targetLaneIndex, 0, temp);
redoElement = {
target: cloneObject(undoElement.source), source: cloneObject(undoElement.target)
};
entry = {
type: 'LanePositionChanged', redoObject: redoElement as NodeModel,
undoObject: undoElement as NodeModel, category: 'Internal'
};
if (!(diagram.diagramActions & DiagramAction.UndoRedo)) {
diagram.commandHandler.addHistoryEntry(entry);
}
ChangeLaneIndex(diagram, swimLane, 0);
updateConnectorsProperties(connectors, diagram);
updateSwimLaneChildPosition(lanes as Lane[], diagram);
swimLane.wrapper.measure(new Size(swimLane.width, swimLane.height));
swimLane.wrapper.arrange(swimLane.wrapper.desiredSize);
diagram.updateDiagramObject(swimLane);
}
}
}
diagram.updateDiagramElementQuad();
}
/**
* updateSwimLaneObject method \
*
* @returns {void} updateSwimLaneObject method .\
* @param {Diagram} diagram - provide the diagram value.
* @param {Node} obj - provide the obj value.
* @param {NodeModel} swimLane - provide the target value.
* @param {NodeModel} helperObject - provide the position value.
* @private
*/
export function updateSwimLaneObject(diagram: Diagram, obj: Node, swimLane: NodeModel, helperObject: NodeModel): void {
const parentNode: NodeModel = diagram.getObject(swimLane.id);
const shape: SwimLaneModel = parentNode.shape as SwimLaneModel;
let index: number = (shape.header && (shape as SwimLane).hasHeader) ? 1 : 0;
const lanes: LaneModel[] = shape.lanes;
const phases: PhaseModel[] = shape.phases;
const helperWidth: number = helperObject.wrapper.actualSize.width;
const helperHeight: number = helperObject.wrapper.actualSize.height;
const objWidth: number = obj.wrapper.actualSize.width;
const objHeight: number = obj.wrapper.actualSize.height;
if (parentNode.shape.type === 'SwimLane') {
if (shape.orientation === 'Horizontal') {
if (obj.isPhase) {
phases[obj.columnIndex].offset += (helperWidth - objWidth);
} else {
index = (shape.phaseSize && shape.phases.length > 0) ? index + 1 : index;
lanes[(obj.rowIndex - index)].height += (helperHeight - objHeight);
}
} else {
if (obj.isPhase) {
phases[(obj.rowIndex - index)].offset += (helperHeight - objHeight);
} else {
index = (shape.phaseSize && shape.phases.length > 0) ? 1 : 0;
lanes[(obj.columnIndex - index)].width += (helperWidth - objWidth);
}
}
}
}
/**
* findLaneIndex method \
*
* @returns {number} findLaneIndex method .\
* @param {NodeModel} swimLane - provide the diagram value.
* @param {NodeModel} laneObj - provide the obj value.
* @private
*/
export function findLaneIndex(swimLane: NodeModel, laneObj: NodeModel): number {
let laneIndex: number; const shape: SwimLaneModel = swimLane.shape as SwimLaneModel;
let index: number = (shape.header && (shape as SwimLane).hasHeader) ? 1 : 0;
if (shape.orientation === 'Horizontal') {
index += shape.phases.length > 0 ? 1 : 0;
laneIndex = laneObj.rowIndex - index;
} else {
laneIndex = laneObj.columnIndex - (shape.phaseSize && shape.phases.length > 0 ? 1 : 0);
}
return laneIndex;
}
/**
* findPhaseIndex method \
*
* @returns {number} findPhaseIndex method .\
* @param {NodeModel} phase - provide the diagram value.
* @param {NodeModel} swimLane - provide the obj value.
* @private
*/
export function findPhaseIndex(phase: NodeModel, swimLane: NodeModel): number {
const shape: SwimLaneModel = swimLane.shape as SwimLaneModel;
const index: number = (shape.header && (shape as SwimLane).hasHeader) ? 1 : 0;
const phaseIndex: number = (shape.orientation === 'Horizontal') ? phase.columnIndex : phase.rowIndex - index;
return phaseIndex;
}
/**
* findStartLaneIndex method \
*
* @returns {number} findStartLaneIndex method .\
* @param {NodeModel} swimLane - provide the obj value.
* @private
*/
export function findStartLaneIndex(swimLane: NodeModel): number {
let index: number = 0; const shape: SwimLaneModel = swimLane.shape as SwimLaneModel;
if (shape.orientation === 'Horizontal') {
index = (shape.header && (shape as SwimLane).hasHeader) ? 1 : 0;
}
if (shape.phases.length > 0 && shape.phaseSize) {
index += 1;
}
return index;
}
/**
* updatePhaseMaxWidth method \
*
* @returns {void} updatePhaseMaxWidth method .\
* @param {NodeModel} parent - provide the obj value.
* @param {Diagram} diagram - provide the obj value.
* @param {Canvas} wrapper - provide the obj value.
* @param {number} columnIndex - provide the obj value.
* @private
*/
export function updatePhaseMaxWidth(parent: NodeModel, diagram: Diagram, wrapper: Canvas, columnIndex: number): void {
const shape: SwimLaneModel = parent.shape as SwimLaneModel;
if (shape.phases.length > 0) {
const node: Node = diagram.nameTable[shape.phases[columnIndex].header.id];
if (node && node.maxWidth < wrapper.outerBounds.width) {
node.maxWidth = wrapper.outerBounds.width;
node.wrapper.maxWidth = wrapper.outerBounds.width;
}
}
}
/**
* updateHeaderMaxWidth method \
*
* @returns {void} updateHeaderMaxWidth method .\
* @param {NodeModel} diagram - provide the obj value.
* @param {NodeModel} swimLane - provide the obj value.
* @private
*/
export function updateHeaderMaxWidth(diagram: Diagram, swimLane: NodeModel): void {
if ((swimLane.shape as SwimLaneModel).header && (swimLane.shape as SwimLane).hasHeader) {
const grid: GridPanel = swimLane.wrapper.children[0] as GridPanel;
const id: string = grid.rows[0].cells[0].children[0].id;
const headerNode: Node = diagram.nameTable[id];
if (headerNode && headerNode.isHeader && headerNode.maxWidth < swimLane.width) {
headerNode.maxWidth = swimLane.width;
headerNode.wrapper.maxWidth = swimLane.width;
}
}
}
/**
* addLane method \
*
* @returns {void} addLane method .\
* @param {Diagram} diagram - provide the obj value.
* @param {NodeModel} parent - provide the obj value.
* @param {LaneModel} lane - provide the obj value.
* @param {number} count - provide the obj value.
* @private
*/
export function addLane(diagram: Diagram, parent: NodeModel, lane: LaneModel, count?: number): void {
let args: ICollectionChangeEventArgs;
const swimLane: NodeModel = diagram.nameTable[parent.id];
if (swimLane.shape.type === 'SwimLane') {
diagram.protectPropertyChange(true);
const grid: GridPanel = swimLane.wrapper.children[0] as GridPanel; const bounds: Rect = grid.bounds;
const shape: SwimLaneModel = swimLane.shape as SwimLaneModel; let redoObj: NodeModel;
let orientation: boolean = false; let entry: HistoryEntry;
let index: number; let children: NodeModel[];
let j: number; let i: number; let k: number; let cell: GridCell; let child: NodeModel; let point: PointModel;
const laneObj: LaneModel = new Lane(shape as Shape, 'lanes', lane, true);
index = (shape.header && (shape as SwimLane).hasHeader) ? 1 : 0;
if (shape.orientation === 'Horizontal') {
orientation = true;
index = shape.phases.length > 0 ? index + 1 : index;
}
const connectors: string[] = getConnectors(diagram, grid, 0, true);
const laneIndex: number = (count !== undefined) ? count : shape.lanes.length;
index += laneIndex;
args = {
element: laneObj, cause: diagram.diagramActions, state: 'Changing', type: 'Addition', cancel: false, laneIndex: laneIndex
};
diagram.triggerEvent(DiagramEvent.collectionChange, args);
if (!args.cancel) {
if (orientation) {
const rowDef: RowDefinition = new RowDefinition();
rowDef.height = lane.height;
grid.addRow(index, rowDef, false);
swimLane.height = (swimLane.height !== undefined) ? swimLane.height + lane.height : swimLane.height;
swimLane.wrapper.height = grid.height = swimLane.height;
} else {
const colDef: ColumnDefinition = new ColumnDefinition();
colDef.width = lane.width;
grid.addColumn(laneIndex + 1, colDef, false);
if (swimLane.width) {
swimLane.width += lane.width;
swimLane.wrapper.width = grid.width = swimLane.width;
}
if (!(diagram.diagramActions & DiagramAction.UndoRedo)) {
grid.rows[0].cells[0].columnSpan += 1;
}
}
if (!(diagram.diagramActions & DiagramAction.UndoRedo)) {
laneObj.id = (laneObj.id === '') ? randomId() : laneObj.id;
}
if (count !== undefined) {
shape.lanes.splice(count, 0, laneObj);
} else {
shape.lanes.push(laneObj);
}
args = {
element: laneObj, cause: diagram.diagramActions, state: 'Changed', type: 'Addition', cancel: false, laneIndex: laneIndex
};
diagram.triggerEvent(DiagramEvent.collectionChange, args);
laneCollection(grid, diagram, swimLane, index, laneIndex, orientation);
redoObj = (shape.orientation === 'Horizontal') ?
diagram.nameTable[grid.rows[index].cells[0].children[0].id] :
((shape.header && (shape as SwimLane).hasHeader) ? diagram.nameTable[grid.rows[1].cells[index].children[0].id] :
diagram.nameTable[grid.rows[0].cells[index].children[0].id]);
if (!(diagram.diagramActions & DiagramAction.UndoRedo)) {
entry = {
type: 'LaneCollectionChanged', changeType: 'Insert', undoObject: cloneObject(laneObj),
redoObject: cloneObject(redoObj), category: 'Internal'
};
diagram.addHistoryEntry(entry);
}
const startRowIndex: number = (shape.orientation === 'Horizontal') ?
index : ((shape.header && (shape as SwimLane).hasHeader) ? 1 : 0);
ChangeLaneIndex(diagram, swimLane, startRowIndex);
swimLaneMeasureAndArrange(swimLane);
updateHeaderMaxWidth(diagram, swimLane);
children = lane.children;
if (children && children.length > 0) {
for (j = 0; j < children.length; j++) {
child = children[j];
point = { x: child.wrapper.offsetX, y: child.wrapper.offsetY };
if (shape.orientation === 'Horizontal') {
cell = grid.rows[index].cells[i];
for (i = 0; i < grid.rows[index].cells.length; i++) {
addChildNodeToNewLane(diagram, grid.rows[index].cells[i], point, child);
}
} else {
for (k = 0; k < grid.rows.length; k++) {
cell = grid.rows[k].cells[index];
addChildNodeToNewLane(diagram, cell, point, child);
}
}
}
}
updateConnectorsProperties(connectors, diagram);
diagram.drag(swimLane, bounds.x - grid.bounds.x, bounds.y - grid.bounds.y);
}
diagram.protectPropertyChange(false);
}
}
/**
* addChildNodeToNewLane method \
*
* @returns {void} addChildNodeToNewLane method .\
* @param {Diagram} diagram - provide the diagram value.
* @param {GridCell} cell - provide the cell value.
* @param {PointModel} point - provide the point value.
* @param {NodeModel} child - provide the child value.
* @private
*/
function addChildNodeToNewLane(diagram: Diagram, cell: GridCell, point: PointModel, child: NodeModel): void {
if (cell.children && cell.children.length > 0) {
const canvas: Canvas = cell.children[0] as Canvas;
const parent: NodeModel = diagram.nameTable[canvas.id];
if (canvas.bounds.containsPoint(point)) {
diagram.addChild(parent, child);
}
}
}
/**
* addPhase method \
*
* @returns {void} addPhase method .\
* @param {Diagram} diagram - provide the diagram value.
* @param {NodeModel} parent - provide the cell value.
* @param {PhaseModel} newPhase - provide the point value.
* @private
*/
export function addPhase(diagram: Diagram, parent: NodeModel, newPhase: PhaseModel): void {
if (parent.shape.type === 'SwimLane') {
let gridRowIndex: number; let gridColIndex: number; let phaseNode: NodeModel;
let phase: PhaseModel; let previousPhase: PhaseModel; let nextPhase: NodeModel;
let phaseIndex: number; let i: number;
const x: number = parent.wrapper.bounds.x; const y: number = parent.wrapper.bounds.y;
const shape: SwimLaneModel = parent.shape as SwimLaneModel;
const padding: number = (shape as SwimLane).padding; const phasesCollection: PhaseModel[] = shape.phases; let width: number;
const grid: GridPanel = parent.wrapper.children[0] as GridPanel;
const orientation: boolean = shape.orientation === 'Horizontal' ? true : false;
gridRowIndex = (shape.header && (shape as SwimLane).hasHeader) ? 0 : -1;
if (shape.phases.length > 0) { gridRowIndex += 1; gridColIndex = 0; }
const laneHeaderSize: number = (orientation) ? shape.lanes[0].header.width : shape.lanes[0].header.height;
if (newPhase.offset > laneHeaderSize) {
for (i = 0; i < phasesCollection.length; i++) {
phase = phasesCollection[i];
previousPhase = (i > 0) ? phasesCollection[i - 1] : phase;
if (phase.offset > newPhase.offset) {
width = (i > 0) ? newPhase.offset - previousPhase.offset : newPhase.offset;
if (orientation) {
const nextCol: ColumnDefinition = grid.columnDefinitions()[i];
nextCol.width -= width;
nextPhase = diagram.nameTable[shape.phases[i].header.id];
nextPhase.maxWidth = nextPhase.wrapper.maxWidth = nextCol.width;
grid.updateColumnWidth(i, nextCol.width, false);
const addPhase: ColumnDefinition = new ColumnDefinition();
addPhase.width = width; phaseIndex = i;
grid.addColumn(i, addPhase, false);
break;
} else {
const nextRow: RowDefinition = grid.rowDefinitions()[i + gridRowIndex];
nextRow.height -= width; nextPhase = diagram.nameTable[shape.phases[i].header.id];
grid.updateRowHeight(i + gridRowIndex, nextRow.height, false);
const addPhase: RowDefinition = new RowDefinition();
addPhase.height = width; phaseIndex = i;
grid.addRow(i + gridRowIndex, addPhase, false);
break;
}
}
}
if (diagram.diagramActions & DiagramAction.UndoRedo && phaseIndex === undefined) {
const entry: HistoryEntry = diagram.historyManager.currentEntry.next;
if (entry.isLastPhase) {
phaseIndex = phasesCollection.length;
addLastPhase(phaseIndex, parent, entry, grid, orientation, newPhase);
}
}
const phaseObj: PhaseModel = new Phase((parent.shape) as Shape, 'phases', newPhase, true);
if (!(diagram.diagramActions & DiagramAction.UndoRedo)) { phaseObj.id += randomId(); }
shape.phases.splice(phaseIndex, 0, phaseObj);
phaseDefine(grid, diagram, parent, gridRowIndex, orientation, phaseIndex);
if (orientation) {
phaseNode = diagram.nameTable[grid.rows[gridRowIndex].cells[phaseIndex].children[0].id];
if (phaseIndex === 0 && shape.header && (shape as SwimLane).hasHeader) {
grid.rows[0].cells[0].children = grid.rows[0].cells[1].children; grid.rows[0].cells[1].children = [];
const fristRow: GridRow = grid.rows[0];
for (let i: number = 0; i < fristRow.cells.length; i++) {
fristRow.cells[i].minWidth = undefined;
if (i === 0) {
fristRow.cells[i].columnSpan = grid.rows[0].cells.length;
} else { fristRow.cells[i].columnSpan = 1; }
}
}
addHorizontalPhase(diagram, parent, grid, phaseIndex, orientation);
const col: ColumnDefinition[] = grid.columnDefinitions();
grid.updateColumnWidth(phaseIndex, col[phaseIndex].width, true, padding);
phaseNode.maxWidth = phaseNode.wrapper.maxWidth = col[phaseIndex].width;
if (col.length > phaseIndex + 1) {
const nextPhaseNode: NodeModel = diagram.nameTable[grid.rows[gridRowIndex].cells[phaseIndex + 1].children[0].id];
grid.updateColumnWidth(phaseIndex + 1, col[phaseIndex + 1].width, true, padding);
nextPhaseNode.maxWidth = nextPhaseNode.wrapper.maxWidth = col[phaseIndex + 1].width;
}
parent.width = parent.wrapper.width = parent.wrapper.children[0].width = grid.width;
} else {
phaseNode = diagram.nameTable[grid.rows[gridRowIndex + phaseIndex].cells[0].children[0].id];
const row: RowDefinition[] = grid.rowDefinitions();
let size: number = row[gridRowIndex + phaseIndex].height;
addVerticalPhase(diagram, parent, grid, gridRowIndex + phaseIndex, orientation);
grid.updateRowHeight(gridRowIndex + phaseIndex, size, true, padding);
if (row.length > gridRowIndex + phaseIndex + 1) {
size = row[gridRowIndex + phaseIndex + 1].height;
grid.updateRowHeight(gridRowIndex + phaseIndex + 1, size, true, padding);
}
parent.height = parent.wrapper.height = parent.wrapper.children[0].height = grid.actualSize.height;
}
swimLaneMeasureAndArrange(parent); parent.width = parent.wrapper.actualSize.width;
updateHeaderMaxWidth(diagram, parent);
diagram.drag(parent, x - parent.wrapper.bounds.x, y - parent.wrapper.bounds.y);
checkPhaseOffset(parent, diagram);
if (!(diagram.diagramActions & DiagramAction.UndoRedo)) {
const entry: HistoryEntry = {
type: 'PhaseCollectionChanged', changeType: 'Insert', undoObject: cloneObject(phaseObj),
redoObject: cloneObject(phaseNode), category: 'Internal'
};
diagram.addHistoryEntry(entry);
}
diagram.updateDiagramObject(parent);
}
}
}
/**
* addLastPhase method \
*
* @returns {void} addLastPhase method .\
* @param {number} phaseIndex - provide the diagram value.
* @param {NodeModel} parent - provide the cell value.
* @param {HistoryEntry} entry - provide the point value.
* @param {GridPanel} grid - provide the grid value.
* @param {boolean} orientation - provide the orientation value.
* @param {PhaseModel} newPhase - provide the newPhase value.
* @private
*/
export function addLastPhase(
phaseIndex: number, parent: NodeModel, entry: HistoryEntry, grid: GridPanel, orientation: boolean, newPhase: PhaseModel): void {
const shape: SwimLaneModel = parent.shape as SwimLaneModel;
const prevPhase: PhaseModel = shape.phases[phaseIndex - 2];
const prevOffset: number = entry.previousPhase.offset;
if (orientation) {
const nextCol: ColumnDefinition = grid.columnDefinitions()[phaseIndex - 1];
const addPhase: ColumnDefinition = new ColumnDefinition();
if (phaseIndex > 1) {
addPhase.width = (nextCol.width) - (prevOffset - prevPhase.offset);
nextCol.width = prevOffset - prevPhase.offset;
} else {
addPhase.width = nextCol.width - prevOffset;
nextCol.width = prevOffset;
}
grid.updateColumnWidth(phaseIndex - 1, nextCol.width, false);
grid.addColumn(phaseIndex, addPhase, false);
} else {
const nextCol: RowDefinition = grid.rowDefinitions()[phaseIndex];
const addPhase: RowDefinition = new RowDefinition();
if (phaseIndex > 1) {
addPhase.height = (entry.undoObject as PhaseModel).offset - prevOffset;
nextCol.height = prevOffset - prevPhase.offset;
} else {
addPhase.height = nextCol.height - prevOffset;
nextCol.height = prevOffset;
}
grid.updateRowHeight(phaseIndex, nextCol.height, false);
grid.addRow(1 + phaseIndex, addPhase, false);
}
}
/**
* addHorizontalPhase method \
*
* @returns {void} addHorizontalPhase method .\
* @param {Diagram} diagram - provide the diagram value.
* @param {NodeModel} node - provide the cell value.
* @param {GridPanel} grid - provide the point value.
* @param {number} index - provide the point value.
* @param {boolean} orientation - provide the point value.
* @private
*/
export function addHorizontalPhase(diagram: Diagram, node: NodeModel, grid: GridPanel, index: number, orientation: boolean): void {
const shape: SwimLaneModel = node.shape as SwimLaneModel; let nextCell: GridCell; let i: number;
let prevCell: GridCell; let gridCell: GridCell; let row: GridRow;
const laneIndex: number = findStartLaneIndex(node);
if (shape.header && (shape as SwimLane).hasHeader) {
grid.rows[0].cells[0].columnSpan = grid.rows[0].cells.length;
}
for (i = laneIndex; i < grid.rows.length; i++) {
row = grid.rows[i]; prevCell = row.cells[index - 1];
gridCell = row.cells[index]; nextCell = row.cells[index + 1];
addSwimlanePhases(diagram, node, prevCell, gridCell, nextCell, i, index);
}
ChangeLaneIndex(diagram, node, 1);
}
/**
* addVerticalPhase method \
*
* @returns {void} addVerticalPhase method .\
* @param {Diagram} diagram - provide the diagram value.
* @param {NodeModel} node - provide the cell value.
* @param {GridPanel} grid - provide the point value.
* @param {number} rowIndex - provide the point value.
* @param {boolean} orientation - provide the point value.
* @private
*/
export function addVerticalPhase(diagram: Diagram, node: NodeModel, grid: GridPanel, rowIndex: number, orientation: boolean): void {
let prevCell: GridCell; let gridCell: GridCell; let nextCell: GridCell;
const row: GridRow = grid.rows[rowIndex];
const nextRow: GridRow = grid.rows[rowIndex + 1];
const prevRow: GridRow = grid.rows[rowIndex - 1];
for (let i: number = 1; i < row.cells.length; i++) {
gridCell = row.cells[i];
nextCell = (nextRow) ? nextRow.cells[i] : undefined;
prevCell = prevRow.cells[i];
addSwimlanePhases(diagram, node, prevCell, gridCell, nextCell, rowIndex, i);
}
ChangeLaneIndex(diagram, node, 1);
}
/**
* addSwimlanePhases method \
*
* @returns {void} addSwimlanePhases method .\
* @param {Diagram} diagram - provide the diagram value.
* @param {NodeModel} node - provide the node value.
* @param {GridPanel} prevCell - provide the prevCell value.
* @param {number} gridCell - provide the gridCell value.
* @param {boolean} nextCell - provide the nextCell value.
* @param {boolean} rowIndex - provide the rowIndex value.
* @param {boolean} columnIndex - provide the columnIndex value.
* @private
*/
function addSwimlanePhases(
diagram: Diagram, node: NodeModel, prevCell: GridCell,
gridCell: GridCell, nextCell: GridCell, rowIndex: number, columnIndex: number): void {
let x: number; let y: number;
const shape: SwimLaneModel = node.shape as SwimLaneModel;
const orientation: boolean = shape.orientation === 'Horizontal' ? true : false;
const grid: GridPanel = node.wrapper.children[0] as GridPanel;
const width: number = gridCell.desiredCellWidth; const height: number = gridCell.desiredCellHeight;
//const col: number = (orientation) ? rowIndex : columnIndex;
//let parentWrapper: Container;
let j: number;
const i: number = (orientation) ? rowIndex : columnIndex;
if (prevCell) {
x = orientation ? prevCell.bounds.x + prevCell.bounds.width : prevCell.bounds.x;
y = orientation ? prevCell.bounds.y : prevCell.bounds.y + prevCell.bounds.height;
} else {
x = grid.bounds.x; y = nextCell.bounds.y;
}
const rect: Rect = new Rect(x, y, width, height);
const canvas: NodeModel = {
id: node.id + ((orientation) ? shape.lanes[i - 2] : shape.lanes[i - 1]).id + randomId()[0],
rowIndex: rowIndex, columnIndex: columnIndex,
width: gridCell.minWidth, height: gridCell.minHeight,
style: ((orientation) ? shape.lanes[i - 2] : shape.lanes[i - 1]).style,
constraints: NodeConstraints.Default | NodeConstraints.AllowDrop,
container: { type: 'Canvas', orientation: orientation ? 'Horizontal' : 'Vertical' }
} as NodeModel;
const parentWrapper: Container = addObjectToGrid(diagram, grid, node, canvas, false, false, true);
parentWrapper.children[0].isCalculateDesiredSize = false;
grid.addObject(parentWrapper, rowIndex, columnIndex);
if (nextCell && nextCell.children && nextCell.children.length) {
for (j = 0; j < nextCell.children.length; j++) {
if (orientation) {
diagram.nameTable[nextCell.children[j].id].columnIndex += 1;
} else {
diagram.nameTable[nextCell.children[j].id].rowIndex += 1;
}
}
}
arrangeChildInGrid(diagram, nextCell, gridCell, rect, parentWrapper, orientation, prevCell);
}
/**
* arrangeChildInGrid method \
*
* @returns {void} arrangeChildInGrid method .\
* @param {Diagram} diagram - provide the diagram value.
* @param {GridCell} nextCell - provide the nextCell value.
* @param {GridPanel} gridCell - provide the gridCell value.
* @param {Rect} rect - provide the rect value.
* @param {Container} parentWrapper - provide the parentWrapper value.
* @param {boolean} orientation - provide the orientation value.
* @param {GridCell} prevCell - provide the prevCell value.
* @private
*/
export function arrangeChildInGrid(
diagram: Diagram, nextCell: GridCell, gridCell: GridCell,
rect: Rect, parentWrapper: Container, orientation: boolean, prevCell?: GridCell): void {
let child: Container; let point: PointModel; let childNode: NodeModel;
const parent: NodeModel = diagram.nameTable[parentWrapper.id];
const changeCell: GridCell = (!nextCell) ? prevCell : nextCell;
const swimLane: NodeModel = diagram.nameTable[(parent as Node).parentId];
const padding: number = (swimLane.shape as SwimLane).padding;
if (changeCell.children && (changeCell.children[0] as Container).children.length > 1) {
for (let j: number = 1; j < (changeCell.children[0] as Container).children.length; j++) {
child = (changeCell.children[0] as Container).children[j] as Container;
childNode = diagram.nameTable[child.id] as NodeModel;
point = (orientation) ? { x: child.bounds.x, y: child.bounds.center.y } :
{ x: child.bounds.center.x, y: child.bounds.top };
if (rect.containsPoint(point)) {
(gridCell.children[0] as Container).children.push(child);
(changeCell.children[0] as Container).children.splice(j, 1);
j--;
diagram.deleteChild(childNode);
if (!(childNode as Node).isLane) {
(childNode as Node).parentId = parentWrapper.id;
}
if (!parent.children) {
parent.children = [];
}
if (!nextCell) {
if (orientation) {
childNode.margin.left = childNode.wrapper.bounds.x - changeCell.children[0].bounds.right;
} else {
childNode.margin.top = childNode.wrapper.bounds.y - changeCell.children[0].bounds.bottom;
}
}
parent.children.push(child.id);
childNode.zIndex = parent.zIndex + 1;
diagram.removeElements(childNode);
} else if (nextCell) {
if (orientation) {
childNode.margin.left -= gridCell.desiredCellWidth;
if (padding > childNode.margin.left) {
childNode.margin.left = padding;
}
} else {
childNode.margin.top -= gridCell.desiredCellHeight;
if (padding > childNode.margin.top) {
childNode.margin.top = padding;
}
}
}
}
}
}
/**
* swimLaneSelection method \
*
* @returns {void} swimLaneSelection method .\
* @param {Diagram} diagram - provide the diagram value.
* @param {NodeModel} node - provide the node value.
* @param {string} corner - provide the corner value.
* @private
*/
export function swimLaneSelection(diagram: Diagram, node: NodeModel, corner: string): void {
if (node.shape.type === 'SwimLane' && (corner === 'ResizeSouth' || corner === 'ResizeEast')) {
const shape: SwimLaneModel = node.shape as SwimLaneModel;
const wrapper: GridPanel = node.wrapper.children[0] as GridPanel;
let child: Container; let index: number;
if (corner === 'ResizeSouth') {
if (shape.orientation === 'Vertical') {
child = wrapper.rows[wrapper.rows.length - 1].cells[0];
} else {
index = wrapper.rows.length - 1;
child = wrapper.rows[index].cells[wrapper.rows[index].cells.length - 1];
}
} else {
index = (shape.header && (shape as SwimLane).hasHeader) ? 1 : 0;
child = wrapper.rows[index].cells[wrapper.rows[index].cells.length - 1];
}
diagram.commandHandler.select(diagram.nameTable[child.children[0].id]);
}
}
/**
* pasteSwimLane method \
*
* @returns {void} pasteSwimLane method .\
* @param {Diagram} swimLane - provide the diagram value.
* @param {NodeModel} diagram - provide the diagram value.
* @param {string} clipboardData - provide the clipboardData value.
* @param {string} laneNode - provide the laneNode value.
* @param {string} isLane - provide the isLane value.
* @param {string} isUndo - provide the isUndo value.
* @private
*/
export function pasteSwimLane(
swimLane: NodeModel, diagram: Diagram, clipboardData?: ClipBoardObject,
laneNode?: NodeModel, isLane?: boolean, isUndo?: boolean): NodeModel {
let i: number; let j: number; let lane: LaneModel; let phase: PhaseModel; let node: Node;
const ranId: string = randomId(); let cloneLane: NodeModel; let childX: number; let childY: number;
const shape: SwimLaneModel = swimLane.shape as SwimLaneModel; //let lanes: LaneModel[];
const phases: PhaseModel[] = shape.phases;
const nodeX: number = swimLane.offsetX - swimLane.wrapper.actualSize.width / 2;
let nodeY: number = swimLane.offsetY - swimLane.wrapper.actualSize.height / 2;
if (shape.orientation === 'Vertical') {
nodeY += (shape.header && (shape as SwimLane).hasHeader) ? shape.header.height : 0;
}
if (!isUndo) {
if (!isLane) {
swimLane.id += ranId;
if (shape && shape.header && (shape as SwimLane).hasHeader) {
shape.header.id += ranId;
} else {
shape.header = undefined;
}
}
for (i = 0; phases && i < phases.length; i++) {
phase = phases[i];
phase.id += ranId;
}
}
const lanes: LaneModel[] = (isLane) ? [clipboardData.childTable[laneNode.id]] : shape.lanes;
for (i = 0; lanes && i < lanes.length; i++) {
lane = lanes[i];
if (!isUndo) {
lane.id += ranId;
}
for (j = 0; lane.children && j < lane.children.length; j++) {
node = lane.children[j] as Node;
childX = node.wrapper.offsetX - node.width / 2;
childY = node.wrapper.offsetY - node.height / 2;
node.zIndex = -1;
node.inEdges = node.outEdges = [];
if (isUndo || (clipboardData && (clipboardData.pasteIndex === 1 || clipboardData.pasteIndex === 0))) {
if (shape.orientation === 'Vertical') {
node.margin.top = childY - nodeY;
} else {
node.margin.left = childX - nodeX;
}
}
if (!isUndo) {
node.id += ranId;
}
}
}
if (!isUndo) {
if (isLane) {
const newShape: SwimLaneModel = {
lanes: lanes,
phases: phases, phaseSize: shape.phaseSize,
type: 'SwimLane', orientation: shape.orientation,
header: { annotation: { content: 'Title' }, height: 50 }
} as SwimLaneModel;
cloneLane = { shape: newShape } as NodeModel;
if (shape.orientation === 'Horizontal') {
cloneLane.width = swimLane.wrapper.actualSize.width;
cloneLane.height = laneNode.wrapper.actualSize.height + shape.header.height + shape.phaseSize;
cloneLane.offsetX = swimLane.wrapper.offsetX + (clipboardData.pasteIndex * 10);
cloneLane.offsetY = laneNode.wrapper.offsetY + (clipboardData.pasteIndex * 10);
} else {
cloneLane.width = laneNode.wrapper.actualSize.width;
cloneLane.height = swimLane.wrapper.actualSize.height;
cloneLane.offsetX = laneNode.wrapper.offsetX + (clipboardData.pasteIndex * 10);
cloneLane.offsetY = swimLane.wrapper.offsetY + (clipboardData.pasteIndex * 10);
}
swimLane = cloneLane;
}
if (clipboardData.pasteIndex !== 0) {
swimLane.offsetX += 10; swimLane.offsetY += 10;
}
swimLane.zIndex = -1;
swimLane = diagram.add(swimLane) as NodeModel;
if (!isLane) {
for (const i of Object.keys(clipboardData.childTable)) {
const connector: ConnectorModel = clipboardData.childTable[i] as ConnectorModel;
connector.id += ranId;
connector.sourceID += ranId;
connector.targetID += ranId;
connector.zIndex = -1;
diagram.add(connector);
}
}
if (diagram.mode !== 'SVG') {
diagram.refreshDiagramLayer();
}
diagram.select([swimLane]);
}
return swimLane;
}
/**
* gridSelection method \
*
* @returns {void} gridSelection method .\
* @param {Diagram} diagram - provide the diagram value.
* @param {SelectorModel} selectorModel - provide the selectorModel value.
* @param {string} id - provide the id value.
* @param {boolean} isSymbolDrag - provide the isSymbolDrag value.
* @private
*/
export function gridSelection(diagram: Diagram, selectorModel: SelectorModel, id?: string, isSymbolDrag?: boolean): Canvas {
let canvas: Canvas; let node: NodeModel = selectorModel.nodes[0];
if (isSymbolDrag || checkParentAsContainer(diagram, node, true)) {
let targetnode: NodeModel; let bounds: Rect;
let swimLaneId: string; const element: DiagramElement = new DiagramElement();
if (id) {
swimLaneId = (diagram.nameTable[id].parentId);
targetnode = node = diagram.nameTable[id];
}
const wrapper: Container = !id ? node.wrapper : targetnode.wrapper;
const parentNode: NodeModel = diagram.nameTable[swimLaneId || (node as Node).parentId];
if (parentNode && parentNode.container.type === 'Grid') {
canvas = new Canvas(); canvas.children = [];
if (isSymbolDrag || !((node as Node).isHeader)) {
if ((parentNode.container.orientation === 'Horizontal' && (node as Node).isPhase) ||
(parentNode.container.orientation === 'Vertical' &&
(node.rowIndex > 0 && node.columnIndex > 0 || (node as Node).isLane))) {
bounds = findBounds(
parentNode,
(targetnode) ? targetnode.columnIndex : node.columnIndex,
((parentNode.shape as SwimLaneModel).header && (parentNode.shape as SwimLane).hasHeader) ? true : false);
canvas.offsetX = bounds.center.x; canvas.offsetY = bounds.center.y;
element.width = bounds.width; element.height = bounds.height;
} else {
canvas.offsetX = parentNode.offsetX;
canvas.offsetY = wrapper.offsetY;
element.width = parentNode.wrapper.actualSize.width;
element.height = wrapper.actualSize.height;
}
}
canvas.children.push(element);
canvas.measure(new Size());
canvas.arrange(canvas.desiredSize);
}
}
return canvas;
}
/**
* removeLaneChildNode method \
*
* @returns {void} removeLaneChildNode method .\
* @param {Diagram} diagram - provide the diagram value.
* @param {NodeModel} swimLaneNode - provide the diagram value.
* @param {NodeModel} currentObj - provide the currentObj value.
* @param {NodeModel} isChildNode - provide the isChildNode value.
* @param {number} laneIndex - provide the laneIndex value.
* @private
*/
export function removeLaneChildNode(
diagram: Diagram, swimLaneNode: NodeModel, currentObj: NodeModel, isChildNode?: NodeModel, laneIndex?: number): void {
laneIndex = (laneIndex !== undefined) ? laneIndex : findLaneIndex(swimLaneNode, currentObj);
let preventHistory: boolean = false;
const lanenode: LaneModel = (swimLaneNode.shape as SwimLaneModel).lanes[laneIndex];
for (let j: number = lanenode.children.length - 1; j >= 0; j--) {
if (isChildNode) {
if (isChildNode.id === lanenode.children[j].id) {
lanenode.children.splice(j, 1);
}
} else {
diagram.removeDependentConnector(lanenode.children[j] as Node);
if (!(diagram.diagramActions & DiagramAction.UndoRedo)) {
diagram.diagramActions = diagram.diagramActions | DiagramAction.UndoRedo;
preventHistory = true;
}
diagram.remove(lanenode.children[j]);
lanenode.children.splice(j, 1);
if (preventHistory) {
diagram.diagramActions = diagram.diagramActions & ~DiagramAction.UndoRedo;
}
}
}
}
/**
* getGridChildren method \
*
* @returns {DiagramElement} getGridChildren method .\
* @param {Diagram} obj - provide the obj value.
* @private
*/
export function getGridChildren(obj: DiagramElement): DiagramElement {
const children: DiagramElement = (obj as Container).children[0];
return children;
}
/**
* removeSwimLane method \
*
* @returns {void} removeSwimLane method .\
* @param {Diagram} diagram - provide the obj value.
* @param {NodeModel} obj - provide the obj value.
* @private
*/
export function removeSwimLane(diagram: Diagram, obj: NodeModel): void {
const rows: GridRow[] = (obj.wrapper.children[0] as GridPanel).rows;
//let preventHistory: boolean = false;
let node: NodeModel;
let i: number; let j: number; let k: number; let child: Container; let removeNode: Node;
for (i = 0; i < rows.length; i++) {
for (j = 0; j < rows[i].cells.length; j++) {
child = getGridChildren(rows[i].cells[j]) as Container;
if (child && child.children) {
for (k = child.children.length - 1; k >= 0; k--) {
if ((child.children[k] as Container).children) {
removeNode = diagram.nameTable[child.children[k].id];
if (removeNode) {
if (removeNode.isLane) {
deleteNode(diagram, removeNode);
} else {
diagram.removeDependentConnector(removeNode);
diagram.diagramActions |= DiagramAction.PreventHistory;
if ((removeNode.constraints & NodeConstraints.Delete)) {
diagram.remove(removeNode);
} else {
removeChildInContainer(diagram, removeNode, {}, false);
}
diagram.diagramActions &= ~DiagramAction.PreventHistory;
}
}
}
}
}
if (child) {
node = diagram.nameTable[child.id];
if (node) {
deleteNode(diagram, node);
}
}
}
}
}
/**
* deleteNode method \
*
* @returns {void} deleteNode method .\
* @param {Diagram} diagram - provide the obj value.
* @param {NodeModel} node - provide the obj value.
* @private
*/
function deleteNode(diagram: Diagram, node: NodeModel): void {
diagram.nodes.splice(diagram.nodes.indexOf(node), 1);
diagram.removeFromAQuad(node as IElement);
diagram.removeObjectsFromLayer(node);
delete diagram.nameTable[node.id];
diagram.removeElements(node);
}
/**
* removeLane method \
*
* @returns {void} removeLane method .\
* @param {Diagram} diagram - provide the obj value.
* @param {NodeModel} lane - provide the obj value.
* @param {NodeModel} swimLane - provide the obj value.
* @param {LaneModel} lanes - provide the obj value.
* @private
*/
export function removeLane(diagram: Diagram, lane: NodeModel, swimLane: NodeModel, lanes?: LaneModel): void {
let args: ICollectionChangeEventArgs;
if (swimLane.shape.type === 'SwimLane') {
const shape: SwimLaneModel = swimLane.shape as SwimLaneModel; let laneIndex: number;
if (shape.lanes.length === 1) {
diagram.remove(swimLane);
} else {
const x: number = swimLane.wrapper.bounds.x; const y: number = swimLane.wrapper.bounds.y;
let row: GridRow; let i: number; let cell: GridCell; let j: number; let child: Canvas;
const grid: GridPanel = swimLane.wrapper.children[0] as GridPanel;
laneIndex = (lanes) ? (shape.lanes.indexOf(lanes)) : findLaneIndex(swimLane, lane);
args = {
element: lane, cause: diagram.diagramActions, state: 'Changing', type: 'Removal', cancel: false, laneIndex: laneIndex
};
diagram.triggerEvent(DiagramEvent.collectionChange, args);
if (!args.cancel) {
const undoObj: LaneModel = cloneObject(shape.lanes[laneIndex]) as LaneModel;
removeLaneChildNode(diagram, swimLane, lane as NodeModel, undefined, laneIndex);
if (!(diagram.diagramActions & DiagramAction.UndoRedo)) {
const entry: HistoryEntry = {
type: 'LaneCollectionChanged', changeType: 'Remove', undoObject: undoObj,
redoObject: cloneObject(lane), category: 'Internal'
};
diagram.addHistoryEntry(entry);
}
shape.lanes.splice(laneIndex, 1);
let index: number = (lane) ? (shape.orientation === 'Horizontal' ? lane.rowIndex : lane.columnIndex) :
(findStartLaneIndex(swimLane) + laneIndex);
if (shape.orientation === 'Horizontal') {
row = grid.rows[index];
for (i = 0; i < row.cells.length; i++) {
cell = row.cells[i];
if (cell && cell.children.length > 0) {
for (j = 0; j < cell.children.length; j++) {
child = cell.children[j] as Canvas;
removeChildren(diagram, child);
}
}
}
grid.removeRow(index);
} else {
swimLane.width = (swimLane.width !== undefined) ?
swimLane.width - grid.rows[0].cells[index].actualSize.width : swimLane.width;
for (i = 0; i < grid.rows.length; i++) {
cell = grid.rows[i].cells[index];
if (cell && cell.children.length > 0) {
for (j = 0; j < cell.children.length; j++) {
child = cell.children[j] as Canvas;
removeChildren(diagram, child);
}
}
}
grid.removeColumn(index);
}
args = {
element: lane, cause: diagram.diagramActions, state: 'Changed', type: 'Removal', cancel: false, laneIndex: laneIndex
};
diagram.triggerEvent(DiagramEvent.collectionChange, args);
swimLane.width = swimLane.wrapper.width = grid.width;
swimLane.height = swimLane.wrapper.height = grid.height;
swimLaneMeasureAndArrange(swimLane);
if ((swimLane.shape as SwimLaneModel).orientation === 'Vertical') {
index = 0;
}
ChangeLaneIndex(diagram, swimLane, index);
diagram.drag(swimLane, x - swimLane.wrapper.bounds.x, y - swimLane.wrapper.bounds.y);
diagram.updateDiagramObject(swimLane);
}
}
}
}
/**
* removeChildren method \
*
* @returns {void} removeChildren method .\
* @param {Diagram} diagram - provide the obj value.
* @param {Canvas} canvas - provide the obj value.
* @private
*/
export function removeChildren(diagram: Diagram, canvas: Canvas): void {
let i: number; let node: NodeModel;
if (canvas instanceof Canvas) {
if (canvas.children.length > 0) {
for (i = 0; i < canvas.children.length; i++) {
if (canvas.children[i] instanceof Canvas) {
removeChildren(diagram, canvas.children[i] as Canvas);
}
}
}
node = diagram.getObject(canvas.id);
deleteNode(diagram, node);
}
}
/**
* removePhase method \
*
* @returns {void} removePhase method .\
* @param {Diagram} diagram - provide the obj value.
* @param {NodeModel} phase - provide the obj value.
* @param {NodeModel} swimLane - provide the obj value.
* @param {PhaseModel} swimLanePhases - provide the obj value.
* @private
*/
export function removePhase(diagram: Diagram, phase: NodeModel, swimLane: NodeModel, swimLanePhases?: PhaseModel): void {
diagram.protectPropertyChange(true);
const x: number = swimLane.wrapper.bounds.x; const y: number = swimLane.wrapper.bounds.y;
let isLastPhase: boolean = false; let previousPhase: PhaseModel;
const shape: SwimLaneModel = swimLane.shape as SwimLaneModel;
const grid: GridPanel = swimLane.wrapper.children[0] as GridPanel;
const phaseIndex: number = swimLanePhases ? shape.phases.indexOf(swimLanePhases) : findPhaseIndex(phase, swimLane);
const phaseLength: number = shape.phases.length;
if (shape.phases.length > 1) {
if (phaseIndex === phaseLength - 1) {
isLastPhase = true;
previousPhase = cloneObject(shape.phases[phaseIndex - 1]) as PhaseModel;
}
const undoObj: PhaseModel = cloneObject(shape.phases[phaseIndex]) as PhaseModel;
shape.phases.splice(phaseIndex, 1);
if (!(diagram.diagramActions & DiagramAction.UndoRedo)) {
const entry: HistoryEntry = {
type: 'PhaseCollectionChanged', changeType: 'Remove', undoObject: undoObj, previousPhase: previousPhase,
redoObject: cloneObject(phase), category: 'Internal', isLastPhase: isLastPhase
};
diagram.addHistoryEntry(entry);
}
if (shape.orientation === 'Horizontal') {
removeHorizontalPhase(diagram, grid, phase, phaseIndex);
} else {
removeVerticalPhase(diagram, grid, phase, phaseIndex, swimLane);
}
updateHeaderMaxWidth(diagram, swimLane);
ChangeLaneIndex(diagram, swimLane, 1);
checkPhaseOffset(swimLane, diagram);
diagram.protectPropertyChange(false);
diagram.updateDiagramObject(swimLane);
}
}
/**
* removeHorizontalPhase method \
*
* @returns {void} removeHorizontalPhase method .\
* @param {Diagram} diagram - provide the obj value.
* @param {GridPanel} grid - provide the obj value.
* @param {NodeModel} phase - provide the obj value.
* @param {number} phaseIndex - provide the obj value.
* @private
*/
export function removeHorizontalPhase(diagram: Diagram, grid: GridPanel, phase: NodeModel, phaseIndex?: number): void {
let row: GridRow; let cell: GridCell; let prevCell: Canvas; let actualChild: Canvas; //let prevChild: Canvas;
let prevCanvas: Canvas; let width: number; phaseIndex = (phaseIndex !== undefined) ? phaseIndex : phase.columnIndex;
let i: number; let j: number; let k: number; let child: Canvas; let node: Node; let object: Node;
for (i = 0; i < grid.rows.length; i++) {
row = grid.rows[i];
if (row.cells.length > 1) {
cell = row.cells[phaseIndex];
prevCell = (row.cells.length - 1 === phaseIndex) ? row.cells[phaseIndex - 1] :
row.cells[phaseIndex + 1];
prevCanvas = prevCell.children[0] as Canvas;
if (cell.children.length > 0) {
actualChild = cell.children[0] as Canvas;
node = diagram.nameTable[actualChild.id] as Node;
if (prevCell.children.length === 0 && cell.children.length > 0) {
prevCell.children = cell.children;
(prevCell as GridCell).columnSpan = (cell as GridCell).columnSpan - 1;
} else {
for (j = 0; j < actualChild.children.length; j++) {
child = actualChild.children[j] as Canvas;
if (child instanceof Canvas) {
object = diagram.nameTable[child.id] as Node;
if (!object.isLane) {
object.parentId = prevCanvas.id;
}
if ((row.cells.length - 1 === phaseIndex)) {
object.margin.left = object.wrapper.bounds.x - prevCanvas.bounds.x;
child.margin.left = object.wrapper.bounds.x - prevCanvas.bounds.x;
}
prevCanvas.children.push(child);
if (diagram.nameTable[prevCanvas.id]) {
const parentNode: NodeModel = diagram.nameTable[prevCanvas.id];
if (!parentNode.children) {
parentNode.children = [];
}
parentNode.children.push(child.id);
}
actualChild.children.splice(j, 1); j--;
if (node && node.children && node.children.indexOf(object.id) !== -1) {
node.children.splice(node.children.indexOf(object.id), 1);
}
}
if ((row.cells.length - 1 !== phaseIndex)) {
for (k = 0; k < prevCanvas.children.length; k++) {
const prevChild: Canvas = prevCanvas.children[k] as Canvas;
if (prevChild instanceof Canvas) {
const prevNode: NodeModel = diagram.nameTable[prevChild.id];
prevNode.margin.left = prevNode.wrapper.bounds.x - actualChild.bounds.x;
prevChild.margin.left = prevNode.wrapper.bounds.x - actualChild.bounds.x;
}
}
}
}
if (node && node.isPhase) {
const object: NodeModel = diagram.nameTable[prevCanvas.id];
if (object) {
prevCanvas.maxWidth = object.wrapper.maxWidth = object.wrapper.maxWidth += node.wrapper.maxWidth;
}
}
deleteNode(diagram, node);
}
}
}
}
const prevWidth: number = grid.columnDefinitions()[phaseIndex].width;
grid.removeColumn(phaseIndex);
if ((phaseIndex < grid.columnDefinitions().length)) {
width = grid.columnDefinitions()[phaseIndex].width;
width += prevWidth;
grid.updateColumnWidth(phaseIndex, width, true);
} else {
width = grid.columnDefinitions()[phaseIndex - 1].width;
width += prevWidth;
grid.updateColumnWidth(phaseIndex - 1, width, true);
}
}
/**
* removeVerticalPhase method \
*
* @returns {void} removeVerticalPhase method .\
* @param {Diagram} diagram - provide the diagram value.
* @param {GridPanel} grid - provide the grid value.
* @param {NodeModel} phase - provide the phase value.
* @param {number} phaseIndex - provide the phaseIndex value.
* @param {number} swimLane - provide the swimLane value.
* @private
*/
export function removeVerticalPhase(diagram: Diagram, grid: GridPanel, phase: NodeModel, phaseIndex: number, swimLane: NodeModel): void {
let cell: GridCell; let height: number;
let i: number; let j: number; let k: number;
let prevCell: GridCell; let prevChild: Canvas;
const shape: SwimLaneModel = swimLane.shape as SwimLaneModel; let child: Canvas; let object: Node;
const phaseRowIndex: number = (phaseIndex !== undefined) ? ((shape.header) ? phaseIndex + 1 : phaseIndex) : phase.rowIndex;
const row: GridRow = grid.rows[phaseRowIndex];
let top: number = swimLane.wrapper.bounds.y;
const phaseCount: number = shape.phases.length;
if (shape.header !== undefined && (shape as SwimLane).hasHeader) {
top += grid.rowDefinitions()[0].height;
}
const prevRow: GridRow = (phaseIndex === phaseCount) ? grid.rows[phaseRowIndex - 1] : grid.rows[phaseRowIndex + 1];
for (i = 0; i < row.cells.length; i++) {
cell = row.cells[i];
prevCell = prevRow.cells[i]; prevChild = prevCell.children[0] as Canvas;
if (cell.children.length > 0) {
const children: Canvas = cell.children[0] as Canvas;
const node: NodeModel = diagram.nameTable[children.id] as NodeModel;
if (phaseIndex < phaseCount) {
for (k = 0; k < prevChild.children.length; k++) {
child = prevChild.children[k] as Canvas;
if (child instanceof Canvas) {
object = diagram.nameTable[child.id];
object.margin.top = object.wrapper.bounds.y - (phaseIndex === 0 ? top : children.bounds.y);
child.margin.top = object.wrapper.bounds.y - (phaseIndex === 0 ? top : children.bounds.y);
}
}
}
for (j = 0; j < children.children.length; j++) {
child = children.children[j] as Canvas;
if (child instanceof Canvas) {
object = diagram.nameTable[child.id] as Node;
object.parentId = prevChild.id;
if (phaseIndex === phaseCount) {
object.margin.top = object.wrapper.bounds.y - (phaseIndex === 0 ? top : prevChild.bounds.y);
child.margin.top = object.wrapper.bounds.y - (phaseIndex === 0 ? top : prevChild.bounds.y);
}
prevChild.children.push(child);
children.children.splice(j, 1); j--;
if (node.children && node.children.indexOf(object.id) !== -1) {
node.children.splice(node.children.indexOf(object.id), 1);
}
}
}
deleteNode(diagram, node);
}
}
const prevHeight: number = grid.rowDefinitions()[phaseRowIndex].height;
grid.removeRow(phaseRowIndex);
if ((phaseRowIndex < grid.rowDefinitions().length)) {
height = grid.rowDefinitions()[phaseRowIndex].height;
height += prevHeight;
grid.updateRowHeight(phaseRowIndex, height, true);
} else {
height = grid.rowDefinitions()[phaseRowIndex - 1].height;
height += prevHeight;
grid.updateRowHeight(phaseRowIndex - 1, height, true);
}
}
/**
* considerSwimLanePadding method \
*
* @returns {void} considerSwimLanePadding method .\
* @param {Diagram} diagram - provide the diagram value.
* @param {NodeModel} node - provide the grid value.
* @param {number} padding - provide the phase value.
* @private
*/
export function considerSwimLanePadding(diagram: Diagram, node: NodeModel, padding: number): void {
const lane: Node = diagram.nameTable[(node as Node).parentId];
if (lane && lane.isLane) {
const swimLane: NodeModel = diagram.nameTable[lane.parentId];
const grid: GridPanel = swimLane.wrapper.children[0] as GridPanel;
//let x: number = swimLane.wrapper.bounds.x; let y: number = swimLane.wrapper.bounds.y;
grid.updateColumnWidth(lane.columnIndex, grid.columnDefinitions()[lane.columnIndex].width, true, padding);
grid.updateRowHeight(lane.rowIndex, grid.rowDefinitions()[lane.rowIndex].height, true, padding);
const canvas: Canvas = lane.wrapper as Canvas;
let laneHeader: Canvas; let isConsiderHeader: boolean = false;
if (node.margin.left < padding) {
node.margin.left = padding;
}
if (node.margin.top < padding) {
node.margin.top = padding;
}
for (let i: number = 0; i < canvas.children.length; i++) {
const child: Canvas = canvas.children[i] as Canvas;
if (child instanceof Canvas) {
const childNode: Node = diagram.nameTable[child.id];
if (childNode.isLane) {
laneHeader = childNode.wrapper as Canvas;
isConsiderHeader = true;
break;
}
}
}
if (laneHeader) {
if ((swimLane.shape as SwimLaneModel).orientation === 'Horizontal') {
if (node.margin.left < padding + laneHeader.actualSize.width) {
node.margin.left = padding + laneHeader.actualSize.width;
}
} else {
if (node.margin.top < padding + laneHeader.actualSize.height) {
node.margin.top = padding + laneHeader.actualSize.height;
}
}
}
swimLane.wrapper.measure(new Size(swimLane.width, swimLane.height));
swimLane.wrapper.arrange(swimLane.wrapper.desiredSize);
node.offsetX = node.wrapper.offsetX; node.offsetY = node.wrapper.offsetY;
diagram.nodePropertyChange(node as Node, {} as Node, { margin: { left: node.margin.left, top: node.margin.top } } as Node);
grid.measure(new Size(grid.width, grid.height));
grid.arrange(grid.desiredSize);
swimLane.width = swimLane.wrapper.width = swimLane.wrapper.children[0].actualSize.width;
swimLane.height = swimLane.wrapper.height = swimLane.wrapper.children[0].actualSize.height;
}
}
/**
* checkLaneChildrenOffset method \
*
* @returns {void} checkLaneChildrenOffset method .\
* @param {NodeModel} swimLane - provide the diagram value.
* @private
*/
export function checkLaneChildrenOffset(swimLane: NodeModel): void {
if (swimLane.shape.type === 'SwimLane') {
const lanes: LaneModel[] = (swimLane.shape as SwimLaneModel).lanes;
let lane: LaneModel; let child: NodeModel;
for (let i: number = 0; i < lanes.length; i++) {
lane = lanes[i];
for (let j: number = 0; j < lane.children.length; j++) {
child = lane.children[j];
child.offsetX = child.wrapper.offsetX;
child.offsetY = child.wrapper.offsetY;
}
}
}
}
/**
* findLane method \
*
* @returns {LaneModel} findLane method .\
* @param {Node} laneNode - provide the laneNode value.
* @param {Diagram} diagram - provide the diagram value.
* @private
*/
export function findLane(laneNode: Node, diagram: Diagram): LaneModel {
let lane: LaneModel;
if (laneNode.isLane) {
const swimLane: NodeModel = diagram.getObject(laneNode.parentId);
if (swimLane && swimLane.shape.type === 'SwimLane' && (laneNode as Node).isLane) {
const laneIndex: number = findLaneIndex(swimLane, laneNode as NodeModel);
lane = (swimLane.shape as SwimLane).lanes[laneIndex];
}
}
return lane;
}
/**
* canLaneInterchange method \
*
* @returns {boolean} canLaneInterchange method .\
* @param {Node} laneNode - provide the laneNode value.
* @param {Diagram} diagram - provide the diagram value.
* @private
*/
export function canLaneInterchange(laneNode: Node, diagram: Diagram): boolean {
if (laneNode.isLane) {
const lane: LaneModel = findLane(laneNode, diagram);
const eventHandler: string = 'eventHandler';
let resize: string = diagram[eventHandler].action;
let canResize: boolean = resize.includes('Resize');
if (canResize || lane.canMove) {
return true;
}
}
return false;
}
/**
* updateSwimLaneChildPosition method \
*
* @returns {void} updateSwimLaneChildPosition method .\
* @param {Lane[]} lanes - provide the laneNode value.
* @param {Diagram} diagram - provide the diagram value.
* @private
*/
export function updateSwimLaneChildPosition(lanes: Lane[], diagram: Diagram): void {
let lane: Lane; let node: NodeModel;
for (let i: number = 0; i < lanes.length; i++) {
lane = lanes[i];
for (let j: number = 0; j < lane.children.length; j++) {
node = diagram.nameTable[lane.children[j].id];
node.offsetX = node.wrapper.offsetX;
node.offsetY = node.wrapper.offsetY;
}
}
} | the_stack |
import { StateSyncAgent } from '../state/StateSyncAgent';
import { PeeringAgentBase } from '../peer/PeeringAgentBase';
import { AgentPod, Event, AgentSetChangeEvent, AgentSetChange, AgentPodEventType } from '../../service/AgentPod';
import { AgentId } from '../../service/Agent';
import { Endpoint } from '../network/NetworkAgent';
//import { PeerId } from '../../network/Peer';
import { HashedMap } from 'data/model/HashedMap';
import { Hash, HashedObject } from 'data/model';
import { Shuffle } from 'util/shuffling';
import { Logger, LogLevel } from 'util/logging';
import { PeerGroupAgent, PeerMeshEventType, NewPeerEvent, LostPeerEvent } from '../peer/PeerGroupAgent';
/*
* A gossip agent is created with a given gossipId (these usually match 1-to-1
* with peerGroupIds), and then is instructed to gossip about the state reported
* by other agents (this.trackedAgentIds keeps track of which ones).
*
* Each agent's state is represented by a HashedObject, and thus states can be
* hashed and hashes sent over to quickly assess if a remote and a local instance
* of the same agent are in the same state.
*
* All the tracked agents must implement the StateSyncAgent interface. They are
* expected to spew an AgentStateUpdate event on the bus whenever they enter a
* new state, and to receive a state that was picked up via gossip when their
* receiveRemoteState() method is invoked.
*
* The gossip agents on different nodes exchange messages about two things:
*
* - They can ask for (SendFullState message) or send (SendFullState message) the
* set of hashes of the states of all the agents being tracked.
*
* - They can ask for (RequestStateObject) or send (SendStateObject) the object
* representing the state of a given agent.
*
*
* A gossip agent follows these simple rules:
*
* - On startup it will send the hashes of the states of all the tracked agents
* to all connected peers. Whenever a new peer is detected, it'll send it the
* hashes as well.
*
* - Upon receiving a set of hashes of states from a peer, they'll see if they are
* tracking the state of any of them, and if the states differ the corresponding
* object states will be asked for (*).
*
* - When a local agent advertises through the bus it is entering a new state by
* emitting the AgentStateUpdate event, any gossip agents tracking its state will
* gossip the new state object to all their peers.
*
* - Upon receiving a new state object for an agent whose state it is tracking, a
* gossip agent will invoke the receiveRemoteState() method of the corresponding
* agent, and learn whether this state is new or known. If it is known, it'll
* assume the agent on the peer has an old state, and it will send the state
* object of the local agent in response.
*
* (*) If the received state hash matches that of the state of another peer for
* that same agent, the asking step is skipped and that state object is used
* instead.
*/
enum GossipType {
SendFullState = 'send-full-state',
SendStateObject = 'send-state-object',
RequestFullState = 'request-full-state',
RequestStateObject = 'request-state-object'
};
interface SendFullState {
type: GossipType.SendFullState,
state: {entries: [AgentId, Hash][], hashes: Hash[]} //HashedMap<AgentId, Hash>.toArrays
};
interface SendStateObject {
type : GossipType.SendStateObject,
agentId : AgentId,
state : any,
timestamp : number
};
interface RequestFullState {
type: GossipType.RequestFullState
}
interface RequestStateObject {
type : GossipType.RequestStateObject,
agentId : AgentId
}
type GossipMessage = SendFullState | SendStateObject | RequestFullState | RequestStateObject;
type GossipParams = {
peerGossipFraction : number,
peerGossipProb : number,
minGossipPeers : number,
maxCachedPrevStates : number,
newStateErrorRetries : number,
newStateErrorDelay : number,
maxGossipDelay : number
};
type PeerState = Map<AgentId, Hash>;
enum GossipEventTypes {
AgentStateUpdate = 'agent-state-update'
};
type AgentStateUpdateEvent = {
type: GossipEventTypes.AgentStateUpdate,
content: { agentId: AgentId, state: HashedObject }
}
class StateGossipAgent extends PeeringAgentBase {
static agentIdForGossip(gossipId: string) {
return 'state-gossip-agent-for-' + gossipId;
}
static peerMessageLog = new Logger(StateGossipAgent.name, LogLevel.INFO);
static controlLog = new Logger(StateGossipAgent.name, LogLevel.INFO);
// tunable working parameters
params: GossipParams = {
peerGossipFraction : 0.2,
peerGossipProb : 0.5,
minGossipPeers : 4,
maxCachedPrevStates : 50,
newStateErrorRetries : 3,
newStateErrorDelay : 1500,
maxGossipDelay : 5000
};
gossipId: string;
pod?: AgentPod;
trackedAgentIds: Set<AgentId>;
localState: PeerState;
remoteState: Map<Endpoint, PeerState>;
localStateObjects: Map<AgentId, HashedObject>;
remoteStateObjects: Map<Endpoint, Map<AgentId, HashedObject>>;
previousStatesCache: Map<AgentId, Array<Hash>>;
peerMessageLog = StateGossipAgent.peerMessageLog;
controlLog = StateGossipAgent.controlLog;
constructor(topic: string, peerNetwork: PeerGroupAgent) {
super(peerNetwork);
this.gossipId = topic;
this.trackedAgentIds = new Set();
this.localState = new Map();
this.remoteState = new Map();
this.localStateObjects = new Map();
this.remoteStateObjects = new Map();
this.previousStatesCache = new Map();
}
getAgentId(): string {
return StateGossipAgent.agentIdForGossip(this.gossipId);
}
getNetwork() : AgentPod {
return this.pod as AgentPod;
}
// gossip agent control:
ready(pod: AgentPod): void {
this.pod = pod;
this.controlLog.debug('Agent ready');
}
trackAgentState(agentId: AgentId) {
this.trackedAgentIds.add(agentId);
}
untrackAgentState(agentId: AgentId) {
this.trackedAgentIds.delete(agentId);
this.previousStatesCache.delete(agentId);
this.localState.delete(agentId);
this.localStateObjects.delete(agentId);
}
isTrackingState(agentId: AgentId) {
return this.trackedAgentIds.has(agentId);
}
shutdown() {
}
// public functions, exposing states heard through gossip
getRemoteState(ep: Endpoint, agentId: AgentId): Hash|undefined {
return this.remoteState.get(ep)?.get(agentId);
}
getRemoteStateObject(ep: Endpoint, agentId: AgentId): HashedObject|undefined {
return this.remoteStateObjects.get(ep)?.get(agentId);
}
// local events listening
receiveLocalEvent(ev: Event): void {
if (ev.type === AgentPodEventType.AgentSetChange) {
let changeEv = ev as AgentSetChangeEvent;
if (changeEv.content.change === AgentSetChange.Removal) {
this.clearAgentState(changeEv.content.agentId)
}
} else if (ev.type === GossipEventTypes.AgentStateUpdate) {
let updateEv = ev as AgentStateUpdateEvent;
this.localAgentStateUpdate(updateEv.content.agentId, updateEv.content.state);
} else if (ev.type === PeerMeshEventType.NewPeer) {
let newPeerEv = ev as NewPeerEvent;
if (newPeerEv.content.peerGroupId === this.peerGroupAgent.peerGroupId) {
this.controlLog.trace(this.peerGroupAgent.localPeer.endpoint + ' detected new peer: ' + newPeerEv.content.peer.endpoint)
this.sendFullState(newPeerEv.content.peer.endpoint);
}
} else if (ev.type === PeerMeshEventType.LostPeer) {
let lostPeerEv = ev as LostPeerEvent;
if (lostPeerEv.content.peerGroupId === this.peerGroupAgent.peerGroupId) {
this.controlLog.trace(this.peerGroupAgent.localPeer.endpoint + ' lost a peer: ' + lostPeerEv.content.peer.endpoint)
this.clearPeerState(lostPeerEv.content.peer.endpoint);
}
}
}
// incoming messages
receivePeerMessage(source: Endpoint, sender: Hash, recipient: Hash, content: any): void {
sender; recipient;
this.receiveGossip(source, content as GossipMessage);
}
private clearAgentState(agentId: AgentId) {
this.localState.delete(agentId);
this.localStateObjects.delete(agentId);
this.previousStatesCache.delete(agentId);
}
private clearPeerState(endpoint: Endpoint) {
this.remoteState.delete(endpoint);
this.remoteStateObjects.delete(endpoint);
}
// Gossiping and caching of local states:
// cached states start at the front of the array and are
// shifted right as new states to cache arrive.
private localAgentStateUpdate(agentId: AgentId, state: HashedObject) {
if (this.trackedAgentIds.has(agentId)) {
const hash = state.hash();
const currentState = this.localState.get(agentId);
if (currentState !== undefined && hash !== currentState) {
this.cachePreviousStateHash(agentId, currentState);
}
this.localState.set(agentId, hash);
this.localStateObjects.set(agentId, state);
this.controlLog.trace('Gossiping state ' + hash + ' from ' + this.peerGroupAgent.getLocalPeer().endpoint);
this.gossipNewState(agentId);
}
}
private gossipNewState(agentId: AgentId, sender?: Endpoint, timestamp?: number) {
const peers = this.getPeerControl().getPeers();
let count = Math.ceil(this.getPeerControl().params.maxPeers * this.params.peerGossipFraction);
if (count < this.params.minGossipPeers) {
count = this.params.minGossipPeers;
}
if (count > peers.length) {
count = peers.length;
}
if (timestamp === undefined) {
timestamp = new Date().getTime();
}
Shuffle.array(peers);
this.controlLog.trace('Gossiping state to ' + count + ' peers on ' + this.peerGroupAgent.getLocalPeer().endpoint);
for (let i=0; i<count; i++) {
if (sender === undefined || sender !== peers[i].endpoint) {
try {
this.sendStateObject(peers[i].endpoint, agentId);
} catch (e) {
this.peerMessageLog.debug('Could not gossip message to ' + peers[i].endpoint + ', send failed with: ' + e);
}
}
}
}
private cachePreviousStateHash(agentId: AgentId, state: Hash) {
let prevStates = this.previousStatesCache.get(agentId);
if (prevStates === undefined) {
prevStates = [];
this.previousStatesCache.set(agentId, prevStates);
}
// remove if already cached
let idx = prevStates.indexOf(state);
if (idx >= 0) {
prevStates.splice(idx, 1);
}
// truncate array to make room for new state
const maxLength = this.params.maxCachedPrevStates - 1;
if (prevStates.length > maxLength) {
const toDelete = prevStates.length - maxLength;
prevStates.splice(maxLength, toDelete);
}
// put state at the start of the cached states array
prevStates.unshift(state);
}
private stateHashIsInPreviousCache(agentId: AgentId, state: Hash) {
const cache = this.previousStatesCache.get(agentId);
return (cache !== undefined) && cache.indexOf(state) >= 0;
}
// handling and caching of remote states
private setRemoteState(ep: Endpoint, agentId: AgentId, state: Hash, stateObject: HashedObject) {
let peerState = this.remoteState.get(ep);
if (peerState === undefined) {
peerState = new Map();
this.remoteState.set(ep, peerState);
}
peerState.set(agentId, state);
let peerStateObjects = this.remoteStateObjects.get(ep);
if (peerStateObjects === undefined) {
peerStateObjects = new Map();
this.remoteStateObjects.set(ep, peerStateObjects);
}
peerStateObjects.set(agentId, stateObject);
}
private lookupStateObject(agentId: AgentId, state: Hash) {
for (const [ep, peerState] of this.remoteState.entries()) {
if (peerState.get(agentId) === state) {
const stateObj = this.remoteStateObjects.get(ep)?.get(agentId);
if (stateObj !== undefined) {
return stateObj
}
}
}
return undefined;
}
private receiveGossip(source: Endpoint, gossip: GossipMessage): void {
this.peerMessageLog.debug(this.getPeerControl().getLocalPeer().endpoint + ' received ' + gossip.type + ' from ' + source);
if (gossip.type === GossipType.SendFullState) {
let state = new HashedMap<AgentId, Hash>();
state.fromArrays(gossip.state.hashes, gossip.state.entries);
this.receiveFullState(source, new Map(state.entries()));
}
if (gossip.type === GossipType.SendStateObject) {
let state = HashedObject.fromLiteral(gossip.state);
this.receiveStateObject(source, gossip.agentId, state, gossip.timestamp);
}
if (gossip.type === GossipType.RequestFullState) {
this.sendFullState(source);
}
if (gossip.type === GossipType.RequestStateObject) {
this.sendStateObject(source, gossip.agentId);
}
}
private getLocalStateAgent(agentId: AgentId) {
const agent = this.getNetwork().getAgent(agentId);
if (agent !== undefined && 'receiveRemoteState' in agent) {
return agent;
} else {
return undefined;
}
}
// message handling
private receiveFullState(sender: Endpoint, state: PeerState) {
for(const [agentId, hash] of state.entries()) {
if (this.trackedAgentIds.has(agentId)) {
const agent = this.getLocalStateAgent(agentId);
if (agent !== undefined) {
const currentState = this.localState.get(agentId);
if (currentState !== hash) {
const cacheHit = this.stateHashIsInPreviousCache(agentId, hash);
if (! cacheHit) {
try {
const stateObj = this.lookupStateObject(agentId, hash);
if (stateObj === undefined) {
this.requestStateObject(sender, agentId);
} else {
this.receiveStateObject(sender, agentId, stateObj, Date.now());
}
} catch (e) {
//FIXME
}
// I _think_ it's better to not gossip in this case.
}
}
}
}
}
}
private async receiveStateObject(sender: Endpoint, agentId: AgentId, stateObj: HashedObject, _timestamp: number) {
if (await stateObj.validate(new Map())) {
const state = stateObj.hash();
this.setRemoteState(sender, agentId, state, stateObj)
const cacheHit = this.stateHashIsInPreviousCache(agentId, state);
let receivedOldState = cacheHit;
if (!receivedOldState) {
try {
receivedOldState = ! (await this.notifyAgentOfStateArrival(sender, agentId, state, stateObj));
} catch (e) {
// maybe cache erroneous states so we don't process them over and over?
StateGossipAgent.controlLog.warning('Received erroneous state from ' + sender, e);
}
}
if (receivedOldState && this.localState.get(agentId) !== state) {
this.peerMessageLog.trace('Received old state for ' + agentId + ' from ' + sender + ', sending our own state over there.');
this.sendStateObject(sender, agentId);
}
} else {
this.peerMessageLog.trace('Received invalid state for ' + agentId + ' from ' + sender + ', ignoring.');
}
}
private async notifyAgentOfStateArrival(sender: Endpoint, agentId: AgentId, stateHash: Hash, state: HashedObject) : Promise<boolean> {
const agent = this.getLocalStateAgent(agentId);
let isNew = false;
let valueReady = false;
if (agent !== undefined) {
const stateAgent = agent as StateSyncAgent;
try {
isNew = await stateAgent.receiveRemoteState(sender, stateHash, state);
valueReady = true;
} catch (e) {
let retries=0;
while (valueReady === false && retries < this.params.newStateErrorRetries) {
await new Promise(r => setTimeout(r, this.params.newStateErrorDelay));
isNew = await stateAgent.receiveRemoteState(sender, stateHash, state);
valueReady = true;
}
}
if (valueReady) {
return isNew;
} else {
throw new Error('Error processing remote state.');
}
} else {
throw new Error('Cannot find receiving agent.');
}
}
// message sending
private sendFullState(ep: Endpoint) {
let fullStateMessage: SendFullState = {
type : GossipType.SendFullState,
state : new HashedMap<AgentId, Hash>(this.localState.entries()).toArrays()
};
this.sendMessageToPeer(ep, this.getAgentId(), fullStateMessage);
}
private sendStateObject(peerEndpoint: Endpoint, agentId: AgentId) {
const state = this.localStateObjects.get(agentId);
if (state !== undefined) {
const timestamp = Date.now();
let literal = state.toLiteral();
let stateUpdateMessage : SendStateObject = {
type : GossipType.SendStateObject,
agentId : agentId,
state : literal,
timestamp : timestamp
};
this.peerMessageLog.debug('Sending state for ' + agentId + ' from ' + this.peerGroupAgent.getLocalPeer().endpoint + ' to ' + peerEndpoint);
let result = this.sendMessageToPeer(peerEndpoint, this.getAgentId(), stateUpdateMessage);
if (!result) {
this.controlLog.debug('Sending state failed!');
}
} else {
this.controlLog.warning('Attempting to send our own state to ' + peerEndpoint + ' for agent ' + agentId + ', but no state object found');
}
}
private requestStateObject(peerEndpoint: Endpoint, agentId: AgentId) {
let requestStateUpdateMessage : RequestStateObject = {
type : GossipType.RequestStateObject,
agentId : agentId
};
this.peerMessageLog.debug('Sending state update request for ' + agentId + ' from ' + this.peerGroupAgent.getLocalPeer().endpoint + ' to ' + peerEndpoint);
let result = this.sendMessageToPeer(peerEndpoint, this.getAgentId(), requestStateUpdateMessage);
if (!result) {
this.controlLog.debug('Sending state request failed!');
}
}
}
export { StateGossipAgent, AgentStateUpdateEvent, GossipEventTypes }; | the_stack |
module awk.grid {
var _ = Utils;
export class FilterManager {
private $compile: any;
private $scope: any;
private gridOptionsWrapper: GridOptionsWrapper;
private grid: any;
private allFilters: any;
private rowModel: any;
private popupService: PopupService;
private valueService: ValueService;
private columnController: ColumnController;
private quickFilter: string;
private advancedFilterPresent: boolean;
private externalFilterPresent: boolean;
public init(grid: Grid, gridOptionsWrapper: GridOptionsWrapper, $compile: any, $scope: any,
columnController: ColumnController, popupService: PopupService, valueService: ValueService) {
this.$compile = $compile;
this.$scope = $scope;
this.gridOptionsWrapper = gridOptionsWrapper;
this.grid = grid;
this.allFilters = {};
this.columnController = columnController;
this.popupService = popupService;
this.valueService = valueService;
this.columnController = columnController;
this.quickFilter = null;
}
public setFilterModel(model: any) {
if (model) {
// mark the filters as we set them, so any active filters left over we stop
var modelKeys = Object.keys(model);
_.iterateObject(this.allFilters, (colId, filterWrapper) => {
_.removeFromArray(modelKeys, colId);
var newModel = model[colId];
this.setModelOnFilterWrapper(filterWrapper.filter, newModel);
});
// at this point, processedFields contains data for which we don't have a filter working yet
_.iterateArray(modelKeys, (colId) => {
var column = this.columnController.getColumn(colId);
if (!column) {
console.warn('Warning ag-grid setFilterModel - no column found for colId ' + colId);
return;
}
var filterWrapper = this.getOrCreateFilterWrapper(column);
this.setModelOnFilterWrapper(filterWrapper.filter, model[colId]);
});
} else {
_.iterateObject(this.allFilters, (key, filterWrapper) => {
this.setModelOnFilterWrapper(filterWrapper.filter, null);
});
}
}
private setModelOnFilterWrapper(filter: { getApi: () => { setModel: Function }}, newModel: any) {
// because user can provide filters, we provide useful error checking and messages
if (typeof filter.getApi !== 'function') {
console.warn('Warning ag-grid - filter missing getApi method, which is needed for getFilterModel');
return;
}
var filterApi = filter.getApi();
if (typeof filterApi.setModel !== 'function') {
console.warn('Warning ag-grid - filter API missing setModel method, which is needed for setFilterModel');
return;
}
filterApi.setModel(newModel);
}
public getFilterModel() {
var result = <any>{};
_.iterateObject(this.allFilters, function (key: any, filterWrapper: any) {
// because user can provide filters, we provide useful error checking and messages
if (typeof filterWrapper.filter.getApi !== 'function') {
console.warn('Warning ag-grid - filter missing getApi method, which is needed for getFilterModel');
return;
}
var filterApi = filterWrapper.filter.getApi();
if (typeof filterApi.getModel !== 'function') {
console.warn('Warning ag-grid - filter API missing getModel method, which is needed for getFilterModel');
return;
}
var model = filterApi.getModel();
if (model) {
result[key] = model;
}
});
return result;
}
public setRowModel(rowModel: any) {
this.rowModel = rowModel;
}
// returns true if any advanced filter (ie not quick filter) active
private isAdvancedFilterPresent() {
var atLeastOneActive = false;
_.iterateObject(this.allFilters, function (key, filterWrapper) {
if (!filterWrapper.filter.isFilterActive) { // because users can do custom filters, give nice error message
console.error('Filter is missing method isFilterActive');
}
if (filterWrapper.filter.isFilterActive()) {
atLeastOneActive = true;
}
});
return atLeastOneActive;
}
// returns true if quickFilter or advancedFilter
public isAnyFilterPresent(): boolean {
return this.isQuickFilterPresent() || this.advancedFilterPresent || this.externalFilterPresent;
}
// returns true if given col has a filter active
public isFilterPresentForCol(colId: any) {
var filterWrapper = this.allFilters[colId];
if (!filterWrapper) {
return false;
}
if (!filterWrapper.filter.isFilterActive) { // because users can do custom filters, give nice error message
console.error('Filter is missing method isFilterActive');
}
var filterPresent = filterWrapper.filter.isFilterActive();
return filterPresent;
}
private doesFilterPass(node: RowNode, filterToSkip?: any) {
var data = node.data;
var colKeys = Object.keys(this.allFilters);
for (var i = 0, l = colKeys.length; i < l; i++) { // critical code, don't use functional programming
var colId = colKeys[i];
var filterWrapper = this.allFilters[colId];
// if no filter, always pass
if (filterWrapper === undefined) {
continue;
}
if (filterWrapper.filter === filterToSkip) {
continue
}
if (!filterWrapper.filter.doesFilterPass) { // because users can do custom filters, give nice error message
console.error('Filter is missing method doesFilterPass');
}
var params = {
node: node,
data: data
};
if (!filterWrapper.filter.doesFilterPass(params)) {
return false;
}
}
// all filters passed
return true;
}
// returns true if it has changed (not just same value again)
public setQuickFilter(newFilter: any): boolean {
if (newFilter === undefined || newFilter === "") {
newFilter = null;
}
if (this.quickFilter !== newFilter) {
if (this.gridOptionsWrapper.isVirtualPaging()) {
console.warn('ag-grid: cannot do quick filtering when doing virtual paging');
return;
}
//want 'null' to mean to filter, so remove undefined and empty string
if (newFilter === undefined || newFilter === "") {
newFilter = null;
}
if (newFilter !== null) {
newFilter = newFilter.toUpperCase();
}
this.quickFilter = newFilter;
return true;
} else {
return false;
}
}
public onFilterChanged(): void {
this.advancedFilterPresent = this.isAdvancedFilterPresent();
this.externalFilterPresent = this.gridOptionsWrapper.isExternalFilterPresent();
_.iterateObject(this.allFilters, function (key, filterWrapper) {
if (filterWrapper.filter.onAnyFilterChanged) {
filterWrapper.filter.onAnyFilterChanged();
}
});
}
private isQuickFilterPresent(): boolean {
return this.quickFilter !== null;
}
public doesRowPassOtherFilters(filterToSkip: any, node: any): boolean {
return this.doesRowPassFilter(node, filterToSkip);
}
public doesRowPassFilter(node: any, filterToSkip?: any): boolean {
//first up, check quick filter
if (this.isQuickFilterPresent()) {
if (!node.quickFilterAggregateText) {
this.aggregateRowForQuickFilter(node);
}
if (node.quickFilterAggregateText.indexOf(this.quickFilter) < 0) {
//quick filter fails, so skip item
return false;
}
}
//secondly, give the client a chance to reject this row
if (this.externalFilterPresent) {
if (!this.gridOptionsWrapper.doesExternalFilterPass(node)) {
return false;
}
}
//lastly, check our internal advanced filter
if (this.advancedFilterPresent) {
if (!this.doesFilterPass(node, filterToSkip)) {
return false;
}
}
//got this far, all filters pass
return true;
}
private aggregateRowForQuickFilter(node: RowNode) {
var aggregatedText = '';
var that = this;
this.columnController.getAllColumns().forEach(function (column: Column) {
var data = node.data;
var value = that.valueService.getValue(column.colDef, data, node);
if (value && value !== '') {
aggregatedText = aggregatedText + value.toString().toUpperCase() + "_";
}
});
node.quickFilterAggregateText = aggregatedText;
}
public refreshDisplayedValues() {
if (!this.rowModel.getTopLevelNodes) {
console.error('ag-Grid: could not find getTopLevelNodes on rowModel. you cannot use setFilter when' +
'doing virtualScrolling as the filter has no way of getting the full set of values to display. ' +
'Either stop using this filter type, or provide the filter with a set of values (see the docs' +
'on configuring the setFilter).')
}
var rows = this.rowModel.getTopLevelNodes();
var colKeys = Object.keys(this.allFilters);
for (var i = 0, l = colKeys.length; i < l; i++) {
var colId = colKeys[i];
var filterWrapper = this.allFilters[colId];
// if no filter, always pass
if (filterWrapper === undefined || (typeof filterWrapper.filter.setFilteredDisplayValues !== 'function')) {
continue;
}
var displayedFilterValues = new Array();
for (var j = 0; j < rows.length; j++) {
if (this.doesFilterPass(rows[j], i)) {
displayedFilterValues.push(rows[j])
}
}
filterWrapper.filter.setFilteredDisplayValues(displayedFilterValues)
}
}
public onNewRowsLoaded() {
var that = this;
Object.keys(this.allFilters).forEach(function (field) {
var filter = that.allFilters[field].filter;
if (filter.onNewRowsLoaded) {
filter.onNewRowsLoaded();
}
});
}
private createValueGetter(column: Column) {
var that = this;
return function valueGetter(node: any) {
return that.valueService.getValue(column.colDef, node.data, node);
};
}
public getFilterApi(column: Column) {
var filterWrapper = this.getOrCreateFilterWrapper(column);
if (filterWrapper) {
if (typeof filterWrapper.filter.getApi === 'function') {
return filterWrapper.filter.getApi();
}
}
}
private getOrCreateFilterWrapper(column: Column) {
var filterWrapper = this.allFilters[column.colId];
if (!filterWrapper) {
filterWrapper = this.createFilterWrapper(column);
this.allFilters[column.colId] = filterWrapper;
this.refreshDisplayedValues();
}
return filterWrapper;
}
private createFilterWrapper(column: Column) {
var colDef = column.colDef;
var filterWrapper = {
column: column,
filter: <any> null,
scope: <any> null,
gui: <any> null
};
if (typeof colDef.filter === 'function') {
// if user provided a filter, just use it
// first up, create child scope if needed
if (this.gridOptionsWrapper.isAngularCompileFilters()) {
filterWrapper.scope = this.$scope.$new();;
}
// now create filter (had to cast to any to get 'new' working)
this.assertMethodHasNoParameters(colDef.filter);
filterWrapper.filter = new (<any>colDef.filter)();
} else if (colDef.filter === 'text') {
filterWrapper.filter = new TextFilter();
} else if (colDef.filter === 'number') {
filterWrapper.filter = new NumberFilter();
} else {
filterWrapper.filter = new SetFilter();
}
var filterChangedCallback = this.grid.onFilterChanged.bind(this.grid);
var filterModifiedCallback = this.grid.onFilterModified.bind(this.grid);
var doesRowPassOtherFilters = this.doesRowPassOtherFilters.bind(this, filterWrapper.filter);
var filterParams = colDef.filterParams;
var params = {
colDef: colDef,
rowModel: this.rowModel,
filterChangedCallback: filterChangedCallback,
filterModifiedCallback: filterModifiedCallback,
filterParams: filterParams,
localeTextFunc: this.gridOptionsWrapper.getLocaleTextFunc(),
valueGetter: this.createValueGetter(column),
doesRowPassOtherFilter: doesRowPassOtherFilters,
$scope: filterWrapper.scope
};
if (!filterWrapper.filter.init) { // because users can do custom filters, give nice error message
throw 'Filter is missing method init';
}
filterWrapper.filter.init(params);
if (!filterWrapper.filter.getGui) { // because users can do custom filters, give nice error message
throw 'Filter is missing method getGui';
}
var eFilterGui = document.createElement('div');
eFilterGui.className = 'ag-filter';
var guiFromFilter = filterWrapper.filter.getGui();
if (_.isNodeOrElement(guiFromFilter)) {
//a dom node or element was returned, so add child
eFilterGui.appendChild(guiFromFilter);
} else {
//otherwise assume it was html, so just insert
var eTextSpan = document.createElement('span');
eTextSpan.innerHTML = guiFromFilter;
eFilterGui.appendChild(eTextSpan);
}
if (filterWrapper.scope) {
filterWrapper.gui = this.$compile(eFilterGui)(filterWrapper.scope)[0];
} else {
filterWrapper.gui = eFilterGui;
}
return filterWrapper;
}
private assertMethodHasNoParameters(theMethod: any) {
var getRowsParams = _.getFunctionParameters(theMethod);
if (getRowsParams.length > 0) {
console.warn('ag-grid: It looks like your filter is of the old type and expecting parameters in the constructor.');
console.warn('ag-grid: From ag-grid 1.14, the constructor should take no parameters and init() used instead.');
}
}
public showFilter(column: Column, eventSource: any) {
var filterWrapper = this.getOrCreateFilterWrapper(column);
this.popupService.positionPopup(eventSource, filterWrapper.gui, 200);
var hidePopup = this.popupService.addAsModalPopup(filterWrapper.gui, true);
if (filterWrapper.filter.afterGuiAttached) {
var params = {
hidePopup: hidePopup,
eventSource: eventSource
};
filterWrapper.filter.afterGuiAttached(params);
}
}
}
} | the_stack |
import * as path from "path";
import { CharacterPair, Position, Range, TextDocument, Uri } from "vscode";
import { COMPONENT_EXT, isScriptComponent } from "../entities/component";
import { getTagPattern, parseTags, Tag, TagContext } from "../entities/tag";
import { cfmlCommentRules, CommentContext, CommentType } from "../features/comment";
import { DocumentStateContext } from "./documentUtil";
import { equalsIgnoreCase } from "./textUtil";
import { stringArrayIncludesIgnoreCase } from "./collections";
const CFM_FILE_EXTS: string[] = [".cfm", ".cfml"];
export const APPLICATION_CFM_GLOB: string = "**/Application.cfm";
// const notContinuingExpressionPattern: RegExp = /(?:^|[^\w$.\s])\s*$/;
const continuingExpressionPattern: RegExp = /(?:\.\s*|[\w$])$/;
const cfscriptLineCommentPattern: RegExp = /\/\/[^\r\n]*/g;
const cfscriptBlockCommentPattern: RegExp = /\/\*[\s\S]*?\*\//g;
const tagBlockCommentPattern: RegExp = /<!--[\s\S]*?-->/g;
const characterPairs: CharacterPair[] = [
["{", "}"],
["[", "]"],
["(", ")"],
["\"", "\""],
["'", "'"],
["#", "#"],
["<", ">"]
];
const NEW_LINE = "\n".charCodeAt(0);
const LEFT_PAREN = "(".charCodeAt(0);
const RIGHT_PAREN = ")".charCodeAt(0);
const SINGLE_QUOTE = "'".charCodeAt(0);
const DOUBLE_QUOTE = '"'.charCodeAt(0);
const BOF = 0;
const identPattern = /[$A-Za-z_][$\w]*/;
const identPartPattern = /[$\w]/;
export interface StringContext {
inString: boolean;
activeStringDelimiter: string;
start: Position;
embeddedCFML: boolean;
embeddedCFMLStartPosition?: Position;
}
export interface DocumentContextRanges {
commentRanges: Range[];
stringRanges?: Range[];
stringEmbeddedCfmlRanges?: Range[];
}
export class BackwardIterator {
private documentStateContext: DocumentStateContext;
private lineNumber: number;
private lineCharacterOffset: number;
private lineText: string;
constructor(documentStateContext: DocumentStateContext, position: Position) {
this.documentStateContext = documentStateContext;
this.lineNumber = position.line;
this.lineCharacterOffset = position.character;
this.lineText = this.getLineText();
}
/**
* Returns whether there is another character
*/
public hasNext(): boolean {
return this.lineNumber >= 0;
}
/**
* Gets the next character code
*/
public next(): number {
if (this.lineCharacterOffset < 0) {
this.lineNumber--;
if (this.lineNumber >= 0) {
this.lineText = this.getLineText();
this.lineCharacterOffset = this.lineText.length - 1;
return NEW_LINE;
}
return BOF;
}
const charCode: number = this.lineText.charCodeAt(this.lineCharacterOffset);
this.lineCharacterOffset--;
return charCode;
}
/**
* Gets current position in iterator
*/
public getPosition(): Position {
let lineNumber = this.lineNumber;
let lineCharacterOffset = this.lineCharacterOffset;
if (lineCharacterOffset < 0) {
lineNumber--;
if (lineNumber >= 0) {
const document: TextDocument = this.getDocument();
const lineRange: Range = document.lineAt(lineNumber).range;
const lineText: string = this.documentStateContext.sanitizedDocumentText.slice(document.offsetAt(lineRange.start), document.offsetAt(lineRange.end));
lineCharacterOffset = lineText.length - 1;
} else {
return undefined;
}
}
return new Position(lineNumber, lineCharacterOffset);
}
/**
* Sets a position in iterator
* @param newPosition Sets a new position for the iterator
*/
public setPosition(newPosition: Position): void {
if (this.lineNumber !== newPosition.line) {
this.lineNumber = newPosition.line;
this.lineText = this.getLineText();
}
this.lineCharacterOffset = newPosition.character;
}
/**
* Gets document
*/
public getDocument(): TextDocument {
return this.documentStateContext.document;
}
/**
* Gets documentStateContext
*/
public getDocumentStateContext(): DocumentStateContext {
return this.documentStateContext;
}
/**
* Gets the current line text
*/
private getLineText(): string {
const document: TextDocument = this.getDocument();
const lineRange: Range = document.lineAt(this.lineNumber).range;
return this.documentStateContext.sanitizedDocumentText.slice(document.offsetAt(lineRange.start), document.offsetAt(lineRange.end));
}
}
/**
* Checks whether the given document is a CFM file
* @param document The document to check
*/
export function isCfmFile(document: TextDocument): boolean {
const extensionName: string = path.extname(document.fileName);
for (const currExt of CFM_FILE_EXTS) {
if (equalsIgnoreCase(extensionName, currExt)) {
return true;
}
}
return false;
}
/**
* Checks whether the given document is a CFC file
* @param document The document to check
*/
export function isCfcFile(document: TextDocument): boolean {
return isCfcUri(document.uri);
}
/**
* Checks whether the given URI represents a CFC file
* @param uri The URI to check
*/
export function isCfcUri(uri: Uri): boolean {
const extensionName = path.extname(uri.fsPath);
return equalsIgnoreCase(extensionName, COMPONENT_EXT);
}
/**
* Returns all of the ranges in which tagged cfscript is active
* @param document The document to check
* @param range Optional range within which to check
*/
export function getCfScriptRanges(document: TextDocument, range?: Range): Range[] {
let ranges: Range[] = [];
let documentText: string;
let textOffset: number;
if (range && document.validateRange(range)) {
documentText = document.getText(range);
textOffset = document.offsetAt(range.start);
} else {
documentText = document.getText();
textOffset = 0;
}
const cfscriptTagPattern: RegExp = getTagPattern("cfscript");
let cfscriptTagMatch: RegExpExecArray = null;
while (cfscriptTagMatch = cfscriptTagPattern.exec(documentText)) {
const prefixLen: number = cfscriptTagMatch[1].length + cfscriptTagMatch[2].length + 1;
const cfscriptBodyText: string = cfscriptTagMatch[3];
if (cfscriptBodyText) {
const cfscriptBodyStartOffset: number = textOffset + cfscriptTagMatch.index + prefixLen;
ranges.push(new Range(
document.positionAt(cfscriptBodyStartOffset),
document.positionAt(cfscriptBodyStartOffset + cfscriptBodyText.length)
));
}
}
return ranges;
}
/**
* Returns ranges for document context such as comments and strings
* @param document The document to check
* @param isScript Whether the document or given range is CFScript
* @param docRange Range within which to check
* @param fast Whether to choose the faster but less accurate method
*/
export function getDocumentContextRanges(document: TextDocument, isScript: boolean = false, docRange?: Range, fast: boolean = false): DocumentContextRanges {
if (fast) {
return { commentRanges: getCommentRangesByRegex(document, isScript, docRange) };
}
return getCommentAndStringRangesIterated(document, isScript, docRange);
}
/**
* Returns all of the ranges for comments based on regular expression searches
* @param document The document to check
* @param isScript Whether the document or given range is CFScript
* @param docRange Range within which to check
*/
function getCommentRangesByRegex(document: TextDocument, isScript: boolean = false, docRange?: Range): Range[] {
let commentRanges: Range[] = [];
let documentText: string;
let textOffset: number;
if (docRange && document.validateRange(docRange)) {
documentText = document.getText(docRange);
textOffset = document.offsetAt(docRange.start);
} else {
documentText = document.getText();
textOffset = 0;
}
if (isScript) {
let scriptBlockCommentMatch: RegExpExecArray = null;
while (scriptBlockCommentMatch = cfscriptBlockCommentPattern.exec(documentText)) {
const scriptBlockCommentText: string = scriptBlockCommentMatch[0];
const scriptBlockCommentStartOffset: number = textOffset + scriptBlockCommentMatch.index;
commentRanges.push(new Range(
document.positionAt(scriptBlockCommentStartOffset),
document.positionAt(scriptBlockCommentStartOffset + scriptBlockCommentText.length)
));
}
let scriptLineCommentMatch: RegExpExecArray = null;
while (scriptLineCommentMatch = cfscriptLineCommentPattern.exec(documentText)) {
const scriptLineCommentText = scriptLineCommentMatch[0];
const scriptLineCommentStartOffset = textOffset + scriptLineCommentMatch.index;
commentRanges.push(new Range(
document.positionAt(scriptLineCommentStartOffset),
document.positionAt(scriptLineCommentStartOffset + scriptLineCommentText.length)
));
}
} else {
let tagBlockCommentMatch: RegExpExecArray = null;
while (tagBlockCommentMatch = tagBlockCommentPattern.exec(documentText)) {
const tagBlockCommentText = tagBlockCommentMatch[0];
const tagBlockCommentStartOffset = textOffset + tagBlockCommentMatch.index;
commentRanges.push(new Range(
document.positionAt(tagBlockCommentStartOffset),
document.positionAt(tagBlockCommentStartOffset + tagBlockCommentText.length)
));
}
const cfScriptRanges: Range[] = getCfScriptRanges(document, docRange);
cfScriptRanges.forEach((range: Range) => {
const cfscriptCommentRanges: Range[] = getCommentRangesByRegex(document, true, range);
commentRanges = commentRanges.concat(cfscriptCommentRanges);
});
}
return commentRanges;
}
/**
* Returns all of the ranges for comments based on iteration. Much slower than regex, but more accurate since it ignores string contents.
* @param document The document to check
* @param isScript Whether the document or given range is CFScript
* @param docRange Range within which to check
*/
function getCommentAndStringRangesIterated(document: TextDocument, isScript: boolean = false, docRange?: Range): DocumentContextRanges {
let commentRanges: Range[] = [];
let stringRanges: Range[] = [];
let documentText: string = document.getText();
let textOffsetStart: number = 0;
let textOffsetEnd: number = documentText.length;
let previousPosition: Position;
if (docRange && document.validateRange(docRange)) {
textOffsetStart = document.offsetAt(docRange.start);
textOffsetEnd = document.offsetAt(docRange.end);
}
let commentContext: CommentContext = {
inComment: false,
activeComment: undefined,
commentType: undefined,
start: undefined
};
let lineText = "";
let stringContext: StringContext = {
inString: false,
activeStringDelimiter: undefined,
start: undefined,
embeddedCFML: false,
embeddedCFMLStartPosition: undefined
};
let tagContext: TagContext = {
inStartTag: false,
inEndTag: false,
name: undefined,
startOffset: undefined
};
const stringEmbeddedCFMLDelimiter: string = "#";
const tagOpeningChars: string = "<cf";
const tagClosingChar: string = ">";
let stringEmbeddedCFMLRanges: Range[] = [];
let cfScriptRanges: Range[] = [];
if (!isScript) {
cfScriptRanges = getCfScriptRanges(document, docRange);
}
// TODO: Account for code delimited by hashes within cfoutput, cfmail, cfquery, etc. blocks
for (let offset = textOffsetStart; offset < textOffsetEnd; offset++) {
let position: Position = document.positionAt(offset);
const characterAtPosition: string = documentText.charAt(offset);
if (previousPosition && position.line !== previousPosition.line) {
lineText = "";
}
lineText += characterAtPosition;
if (commentContext.inComment) {
// Check for end of comment
if (commentContext.commentType === CommentType.Line && position.line !== previousPosition.line) {
commentRanges.push(new Range(commentContext.start, previousPosition));
commentContext = {
inComment: false,
activeComment: undefined,
commentType: undefined,
start: undefined
};
} else if (commentContext.commentType === CommentType.Block && lineText.endsWith(commentContext.activeComment[1])) {
commentRanges.push(new Range(commentContext.start, document.positionAt(offset + 1)));
commentContext = {
inComment: false,
activeComment: undefined,
commentType: undefined,
start: undefined
};
}
} else if (stringContext.inString) {
if (characterAtPosition === stringEmbeddedCFMLDelimiter) {
if (stringContext.embeddedCFML) {
stringContext.embeddedCFML = false;
stringEmbeddedCFMLRanges.push(new Range(stringContext.embeddedCFMLStartPosition, document.positionAt(offset + 1)));
stringContext.embeddedCFMLStartPosition = undefined;
} else {
let hashEscaped = false;
let characterAtNextPosition: string;
try {
characterAtNextPosition = documentText.charAt(offset + 1);
hashEscaped = characterAtNextPosition === stringEmbeddedCFMLDelimiter;
}
catch (e) {
// Keep value
}
if (hashEscaped) {
offset++;
lineText += characterAtNextPosition;
position = document.positionAt(offset);
} else {
stringContext.embeddedCFML = true;
stringContext.embeddedCFMLStartPosition = position;
}
}
} else if (!stringContext.embeddedCFML && characterAtPosition === stringContext.activeStringDelimiter) {
let quoteEscaped = false;
let characterAtNextPosition: string;
try {
characterAtNextPosition = documentText.charAt(offset + 1);
quoteEscaped = characterAtNextPosition === stringContext.activeStringDelimiter;
}
catch (e) {
// Keep value
}
if (quoteEscaped) {
offset++;
lineText += characterAtNextPosition;
position = document.positionAt(offset);
} else {
stringRanges.push(new Range(stringContext.start, document.positionAt(offset + 1)));
stringContext = {
inString: false,
activeStringDelimiter: undefined,
start: undefined,
embeddedCFML: false
};
}
}
} else {
if (isScript) {
if (isStringDelimiter(characterAtPosition)) {
stringContext = {
inString: true,
activeStringDelimiter: characterAtPosition,
start: position,
embeddedCFML: false
};
} else if (lineText.endsWith(cfmlCommentRules.scriptLineComment)) {
commentContext = {
inComment: true,
activeComment: cfmlCommentRules.scriptLineComment,
commentType: CommentType.Line,
start: previousPosition
};
} else if (lineText.endsWith(cfmlCommentRules.scriptBlockComment[0])) {
commentContext = {
inComment: true,
activeComment: cfmlCommentRules.scriptBlockComment,
commentType: CommentType.Block,
start: previousPosition
};
}
} else if (lineText.endsWith(cfmlCommentRules.tagBlockComment[0])) {
commentContext = {
inComment: true,
activeComment: cfmlCommentRules.tagBlockComment,
commentType: CommentType.Block,
start: position.translate(0, 1 - cfmlCommentRules.tagBlockComment[0].length)
};
} else if (tagContext.inStartTag) {
if (characterAtPosition === tagClosingChar) {
tagContext = {
inStartTag: false,
inEndTag: false,
name: undefined,
startOffset: undefined
};
} else if (isStringDelimiter(characterAtPosition)) {
stringContext = {
inString: true,
activeStringDelimiter: characterAtPosition,
start: document.positionAt(offset),
embeddedCFML: false
};
}
} else if (lineText.endsWith(tagOpeningChars)) {
const tagName = document.getText(document.getWordRangeAtPosition(position));
tagContext = {
inStartTag: true,
inEndTag: false,
name: tagName,
startOffset: offset - 2
};
}
}
previousPosition = position;
}
if (cfScriptRanges.length > 0) {
// Remove tag comments found within CFScripts
commentRanges = commentRanges.filter((range: Range) => {
return !isInRanges(cfScriptRanges, range);
});
cfScriptRanges.forEach((range: Range) => {
if (!isInRanges(commentRanges, range)) {
const cfscriptContextRanges: DocumentContextRanges = getCommentAndStringRangesIterated(document, true, range);
commentRanges = commentRanges.concat(cfscriptContextRanges.commentRanges);
if (cfscriptContextRanges.stringRanges) {
stringRanges = stringRanges.concat(cfscriptContextRanges.stringRanges);
}
}
});
}
return { commentRanges, stringRanges, stringEmbeddedCfmlRanges: stringEmbeddedCFMLRanges };
}
/**
* Returns all of the ranges in which there is JavaScript
* @param documentStateContext The context information for the TextDocument to check
* @param range Optional range within which to check
*/
export function getJavaScriptRanges(documentStateContext: DocumentStateContext, range?: Range): Range[] {
const scriptTags: Tag[] = parseTags(documentStateContext, "script", range);
return scriptTags.map((tag: Tag) => {
return tag.bodyRange;
});
}
/**
* Returns all of the ranges in which there is CSS in style tags. Does not consider style attributes.
* @param documentStateContext The context information for the TextDocument to check
* @param range Optional range within which to check
*/
export function getCssRanges(documentStateContext: DocumentStateContext, range?: Range): Range[] {
const styleTags: Tag[] = parseTags(documentStateContext, "style", range);
return styleTags.map((tag: Tag) => {
return tag.bodyRange;
});
}
/**
* Returns all of the ranges in which tagged cfoutput is active.
* @param documentStateContext The context information for the TextDocument to check
* @param range Optional range within which to check
*/
export function getCfOutputRanges(documentStateContext: DocumentStateContext, range?: Range): Range[] {
const cfoutputTags: Tag[] = parseTags(documentStateContext, "cfoutput", range);
return cfoutputTags.map((tag: Tag) => {
return tag.bodyRange;
});
}
/**
* Returns whether the given position is within a cfoutput block
* @param documentStateContext The context information for the TextDocument to check
* @param position Position at which to check
*/
export function isInCfOutput(documentStateContext: DocumentStateContext, position: Position): boolean {
return isInRanges(getCfOutputRanges(documentStateContext), position);
}
/**
* Returns whether the given position is within a CFScript block
* @param document The document to check
* @param position Position at which to check
*/
export function isInCfScript(document: TextDocument, position: Position): boolean {
return isInRanges(getCfScriptRanges(document), position);
}
/**
* Returns whether the given position is in a CFScript context
* @param document The document to check
* @param position Position at which to check
*/
export function isPositionScript(document: TextDocument, position: Position): boolean {
return (isScriptComponent(document) || isInCfScript(document, position));
}
/**
* Returns whether the given position is within a JavaScript block
* @param documentStateContext The context information for the TextDocument to check
* @param position Position at which to check
*/
export function isInJavaScript(documentStateContext: DocumentStateContext, position: Position): boolean {
return isInRanges(getJavaScriptRanges(documentStateContext), position);
}
/**
* Returns whether the given position is within a JavaScript block
* @param documentStateContext The context information for the TextDocument to check
* @param position Position at which to check
*/
export function isInCss(documentStateContext: DocumentStateContext, position: Position): boolean {
return isInRanges(getCssRanges(documentStateContext), position);
}
/**
* Returns whether the given position is within a comment
* @param document The document to check
* @param position Position at which to check
* @param isScript Whether the document is CFScript
*/
export function isInComment(document: TextDocument, position: Position, isScript: boolean = false): boolean {
return isInRanges(getDocumentContextRanges(document, isScript).commentRanges, position);
}
/**
* Returns whether the given position is within a set of ranges
* @param ranges The set of ranges within which to check
* @param positionOrRange Position or range to check
* @param ignoreEnds Whether to ignore `start` and `end` in `ranges` when `positionOrRange` is `Position`
*/
export function isInRanges(ranges: Range[], positionOrRange: Position | Range, ignoreEnds: boolean = false): boolean {
return ranges.some((range: Range) => {
let isContained: boolean = range.contains(positionOrRange);
if (ignoreEnds) {
if (positionOrRange instanceof Position) {
isContained = isContained && !range.start.isEqual(positionOrRange)&& !range.end.isEqual(positionOrRange);
}
}
return isContained;
});
}
/**
* Returns an array of ranges inverted from given ranges
* @param document The document to check
* @param ranges Ranges to invert
*/
export function invertRanges(document: TextDocument, ranges: Range[]): Range[] {
let invertedRanges: Range[] = [];
const documentEndPosition: Position = document.positionAt(document.getText().length);
let previousEndPosition: Position = new Position(0, 0);
ranges.forEach((range: Range) => {
if (previousEndPosition.isEqual(range.start)) {
previousEndPosition = range.end;
return;
}
invertedRanges.push(new Range(
previousEndPosition,
range.start
));
});
if (!previousEndPosition.isEqual(documentEndPosition)) {
invertedRanges.push(new Range(
previousEndPosition,
documentEndPosition
));
}
return invertedRanges;
}
/**
* Returns if the given prefix is part of a continuing expression
* @param prefix Prefix to the current position
*/
export function isContinuingExpression(prefix: string): boolean {
return continuingExpressionPattern.test(prefix);
}
/**
* Given a character, gets its respective character pair
* @param character Either character in a character pair
*/
function getCharacterPair(character: string): CharacterPair | undefined {
return characterPairs.find((charPair: CharacterPair) => {
return (charPair[0] === character || charPair[1] === character);
});
}
/**
* Gets the opening character in a character pair
* @param closingChar The closing character in a pair
*/
function getOpeningChar(closingChar: string): string {
const characterPair: CharacterPair = getCharacterPair(closingChar);
if (!characterPair) {
return "";
}
return characterPair[0];
}
/**
* Gets whether the given character is a string delimiter
* @param char A character to check against string delimiters
*/
export function isStringDelimiter(char: string): boolean {
switch (char) {
case "'":
return true;
case '"':
return true;
default:
return false;
}
}
/**
* Determines the position at which the given opening character occurs after the given position immediately following the opening character
* @param documentStateContext The context information for the TextDocument to check
* @param startOffset A numeric offset representing the position in the document from which to start
* @param endOffset A numeric offset representing the last position in the document that should be checked
* @param char The character(s) for which to check
* @param includeChar Whether the returned position should include the character found
*/
export function getNextCharacterPosition(documentStateContext: DocumentStateContext, startOffset: number, endOffset: number, char: string | string[], includeChar: boolean = true): Position {
const document: TextDocument = documentStateContext.document;
const documentText: string = documentStateContext.sanitizedDocumentText;
let stringContext: StringContext = {
inString: false,
activeStringDelimiter: undefined,
start: undefined,
embeddedCFML: false
};
const embeddedCFMLDelimiter: string = "#";
const searchChar = Array.isArray(char) ? char : [char];
let pairContext = [
// braces
{
characterPair: characterPairs[0],
unclosedPairCount: 0
},
// brackets
{
characterPair: characterPairs[1],
unclosedPairCount: 0
},
// parens
{
characterPair: characterPairs[2],
unclosedPairCount: 0
}
];
const openingPairs: string[] = pairContext.map((pairItem) => pairItem.characterPair[0]).filter((openingChar) => !searchChar.includes(openingChar));
const closingPairs: string[] = pairContext.map((pairItem) => pairItem.characterPair[1]);
const incrementUnclosedPair = (openingChar: string): void => {
pairContext.filter((pairItem) => {
return openingChar === pairItem.characterPair[0];
}).forEach((pairItem) => {
pairItem.unclosedPairCount++;
});
};
const decrementUnclosedPair = (closingChar: string): void => {
pairContext.filter((pairItem) => {
return closingChar === pairItem.characterPair[1];
}).forEach((pairItem) => {
pairItem.unclosedPairCount--;
});
};
const hasNoUnclosedPairs = (): boolean => {
return pairContext.every((pairItem) => {
return pairItem.unclosedPairCount === 0;
});
};
for (let offset = startOffset; offset < endOffset; offset++) {
const characterAtPosition: string = documentText.charAt(offset);
if (stringContext.inString) {
if (characterAtPosition === embeddedCFMLDelimiter) {
stringContext.embeddedCFML = !stringContext.embeddedCFML;
} else if (!stringContext.embeddedCFML && characterAtPosition === stringContext.activeStringDelimiter) {
stringContext = {
inString: false,
activeStringDelimiter: undefined,
start: undefined,
embeddedCFML: false
};
}
} else if (isStringDelimiter(characterAtPosition)) {
stringContext = {
inString: true,
activeStringDelimiter: characterAtPosition,
start: document.positionAt(offset),
embeddedCFML: false
};
} else if (searchChar.includes(characterAtPosition) && hasNoUnclosedPairs()) {
if (includeChar) {
return document.positionAt(offset + 1);
} else {
return document.positionAt(offset);
}
} else if (openingPairs.includes(characterAtPosition)) {
incrementUnclosedPair(characterAtPosition);
} else if (closingPairs.includes(characterAtPosition)) {
decrementUnclosedPair(characterAtPosition);
}
}
return document.positionAt(endOffset);
}
/**
* Determines the position at which the given closing character occurs after the given position immediately following the opening character
* @param documentStateContext The context information for the TextDocument to check
* @param initialOffset A numeric offset representing the position in the document from which to start
* @param closingChar The character that denotes the closing
*/
export function getClosingPosition(documentStateContext: DocumentStateContext, initialOffset: number, closingChar: string): Position {
const openingChar = getOpeningChar(closingChar);
const document: TextDocument = documentStateContext.document;
const documentText: string = documentStateContext.sanitizedDocumentText;
let unclosedPairs = 0;
let stringContext: StringContext = {
inString: false,
activeStringDelimiter: undefined,
start: undefined,
embeddedCFML: false
};
const embeddedCFMLDelimiter: string = "#";
for (let offset = initialOffset; offset < documentText.length; offset++) {
const characterAtPosition: string = documentText.charAt(offset);
if (stringContext.inString) {
if (characterAtPosition === embeddedCFMLDelimiter) {
stringContext.embeddedCFML = !stringContext.embeddedCFML;
} else if (!stringContext.embeddedCFML && characterAtPosition === stringContext.activeStringDelimiter) {
stringContext = {
inString: false,
activeStringDelimiter: undefined,
start: undefined,
embeddedCFML: false
};
}
} else if (isStringDelimiter(characterAtPosition)) {
stringContext = {
inString: true,
activeStringDelimiter: characterAtPosition,
start: document.positionAt(offset),
embeddedCFML: false
};
} else if (characterAtPosition === openingChar) {
unclosedPairs++;
} else if (characterAtPosition === closingChar) {
if (unclosedPairs !== 0) {
unclosedPairs--;
} else {
return document.positionAt(offset + 1);
}
}
}
return document.positionAt(initialOffset);
}
/**
* Tests whether the given character can be part of a valid CFML identifier
* @param char Character to test
*/
export function isValidIdentifierPart(char: string): boolean {
return identPartPattern.test(char);
}
/**
* Tests whether the given word can be a valid CFML identifier
* @param word String to test
*/
export function isValidIdentifier(word: string): boolean {
return identPattern.test(word);
}
/**
* Returns the range of the word preceding the given position if it is a valid identifier or undefined if invalid
* @param document The document in which to check for the identifier
* @param position A position at which to start
*/
export function getPrecedingIdentifierRange(documentStateContext: DocumentStateContext, position: Position): Range | undefined {
let identRange: Range;
let charStr = "";
let iterator: BackwardIterator = new BackwardIterator(documentStateContext, position);
while (iterator.hasNext()) {
const ch: number = iterator.next();
charStr = String.fromCharCode(ch);
if (/\S/.test(charStr)) {
break;
}
}
if (isValidIdentifierPart(charStr)) {
const currentWordRange: Range = documentStateContext.document.getWordRangeAtPosition(iterator.getPosition());
const currentWord: string = documentStateContext.document.getText(currentWordRange);
if (isValidIdentifier(currentWord)) {
identRange = currentWordRange;
}
}
return identRange;
}
/**
* Gets an array of arguments including and preceding the currently selected argument
* @param iterator A BackwardIterator to use to read arguments
*/
export function getStartSigPosition(iterator: BackwardIterator): Position | undefined {
let parenNesting = 0;
const document: TextDocument = iterator.getDocumentStateContext().document;
const stringRanges: Range[] = iterator.getDocumentStateContext().stringRanges;
const stringEmbeddedCfmlRanges: Range[] = iterator.getDocumentStateContext().stringEmbeddedCfmlRanges;
while (iterator.hasNext()) {
const ch: number = iterator.next();
if (stringRanges) {
const position: Position = iterator.getPosition().translate(0, 1);
const stringRange: Range = stringRanges.find((range: Range) => {
return range.contains(position) && !range.end.isEqual(position);
});
if (stringRange && !(stringEmbeddedCfmlRanges && isInRanges(stringEmbeddedCfmlRanges, position, true))) {
iterator.setPosition(stringRange.start.translate(0, -1));
continue;
}
}
switch (ch) {
case LEFT_PAREN:
parenNesting--;
if (parenNesting < 0) {
let candidatePosition: Position = iterator.getPosition();
while (iterator.hasNext()) {
const nch: number = iterator.next();
const charStr = String.fromCharCode(nch);
if (/\S/.test(charStr)) {
const iterPos: Position = iterator.getPosition();
if (isValidIdentifierPart(charStr)) {
const nameRange = document.getWordRangeAtPosition(iterPos);
const name = document.getText(nameRange);
if (isValidIdentifier(name) && !stringArrayIncludesIgnoreCase(["function","if","for","while","switch","catch"], name)) {
return candidatePosition;
}
}
iterator.setPosition(iterPos.translate(0, 1));
parenNesting++;
break;
}
}
}
break;
case RIGHT_PAREN: parenNesting++; break;
case DOUBLE_QUOTE: case SINGLE_QUOTE:
// FIXME: If position is within string, this does not work
while (iterator.hasNext()) {
const nch: number = iterator.next();
// find the closing quote or double quote
// TODO: Ignore if escaped
if (ch === nch) {
break;
}
}
break;
}
}
return undefined;
} | the_stack |
'use strict';
import * as vscode from 'vscode';
import { BlockchainTreeItem } from './model/BlockchainTreeItem';
import { BlockchainExplorerProvider } from './BlockchainExplorerProvider';
import { WalletTreeItem } from './wallets/WalletTreeItem';
import { LocalWalletTreeItem } from './wallets/LocalWalletTreeItem';
import { FabricCertificate, Attribute, FabricWalletRegistry, FabricWalletRegistryEntry, IFabricWalletGenerator, IFabricWallet, LogType, FabricWalletGeneratorFactory, FabricNode, FabricEnvironmentRegistryEntry, FabricEnvironmentRegistry, FabricEnvironment, FabricIdentity, EnvironmentType } from 'ibm-blockchain-platform-common';
import { VSCodeBlockchainOutputAdapter } from '../logging/VSCodeBlockchainOutputAdapter';
import { IdentityTreeItem } from './model/IdentityTreeItem';
import { AdminIdentityTreeItem } from './model/AdminIdentityTreeItem';
import { TextTreeItem } from './model/TextTreeItem';
import { WalletGroupTreeItem } from './model/WalletGroupTreeItem';
import { ExplorerUtil } from '../util/ExplorerUtil';
import { EnvironmentFactory } from '../fabric/environments/EnvironmentFactory';
import { LocalMicroEnvironmentManager } from '../fabric/environments/LocalMicroEnvironmentManager';
import { LocalMicroEnvironment } from '../fabric/environments/LocalMicroEnvironment';
import { FabricWalletHelper } from '../fabric/FabricWalletHelper';
export class BlockchainWalletExplorerProvider implements BlockchainExplorerProvider {
// only for testing so can get the updated tree
public tree: Array<BlockchainTreeItem> = [];
// tslint:disable-next-line member-ordering
private _onDidChangeTreeData: vscode.EventEmitter<any | undefined> = new vscode.EventEmitter<any | undefined>();
// tslint:disable-next-line member-ordering
readonly onDidChangeTreeData: vscode.Event<any | undefined> = this._onDidChangeTreeData.event;
getTreeItem(element: BlockchainTreeItem): vscode.TreeItem {
return element;
}
async getChildren(element?: BlockchainTreeItem): Promise<BlockchainTreeItem[]> {
const outputAdapter: VSCodeBlockchainOutputAdapter = VSCodeBlockchainOutputAdapter.instance();
try {
if (element) {
if (element instanceof WalletTreeItem || element instanceof LocalWalletTreeItem) {
this.tree = await this.createIdentityTree(element);
}
if (element instanceof WalletGroupTreeItem) {
this.tree = await this.populateWallets(element.wallets);
}
} else {
// Get the wallets from the registry and create a wallet tree
this.tree = await this.createWalletTree();
}
} catch (error) {
outputAdapter.log(LogType.ERROR, `Error displaying Fabric Wallets: ${error.message}`, `Error displaying Fabric Wallets: ${error.message}`);
}
return this.tree;
}
async refresh(element?: BlockchainTreeItem): Promise<void> {
this._onDidChangeTreeData.fire(element);
}
private async createWalletTree(): Promise<BlockchainTreeItem[]> {
const tree: Array<BlockchainTreeItem> = [];
let walletRegistryEntries: FabricWalletRegistryEntry[] = await FabricWalletRegistry.instance().getAll();
walletRegistryEntries = await this.updateWalletEnvironmentGroups(walletRegistryEntries);
const newEntries: FabricWalletRegistryEntry[] = [];
// Filter out invalid wallets, or wallets without a wallet path
for (const _entry of walletRegistryEntries) {
try {
// Check the wallet is valid before attempting to display it
const walletGenerator: IFabricWalletGenerator = FabricWalletGeneratorFactory.getFabricWalletGenerator();
await walletGenerator.getWallet(_entry);
newEntries.push(_entry);
} catch (err) {
// ignore
}
}
walletRegistryEntries = newEntries;
const walletGroups: any[] = [];
const otherWallets: Array<FabricWalletRegistryEntry | FabricWalletRegistryEntry[]> = [];
let totalWallets: number = walletRegistryEntries.length;
// iterate through wallets and group them until there are none left
while (0 < totalWallets) {
const wallet: FabricWalletRegistryEntry = walletRegistryEntries[0];
if (!wallet.fromEnvironment && (!wallet.environmentGroups || wallet.environmentGroups.length < 1)) {
// group wallets that don't belong to environments
otherWallets.push(wallet);
// remove wallet from array as it's already been grouped
walletRegistryEntries.splice(0, 1);
totalWallets--;
} else {
// create new group for this wallet
const group: FabricWalletRegistryEntry[] = [wallet];
// flag to determine if this group should be pushed to otherWallets
let pushToOtherWallets: boolean = false;
if (wallet.environmentGroups) {
pushToOtherWallets = (wallet.environmentGroups.length > 1) ? true : false;
}
// search for wallets that also belong to this group
let otherGroupWallets: FabricWalletRegistryEntry[] = [];
if (!wallet.environmentGroups) {
otherGroupWallets = walletRegistryEntries.filter((entry: FabricWalletRegistryEntry, index: number) => {
if (index > 0 && entry.environmentGroups) {
if (wallet.fromEnvironment === entry.environmentGroups[0] || wallet.fromEnvironment === entry.fromEnvironment) {
if (!pushToOtherWallets) {
// if any wallets in the group have been used for another environment then we should push the whole group to otherWallets
pushToOtherWallets = (entry.environmentGroups.length > 1) ? true : false;
if (entry.environmentGroups.length > 1 || (entry.fromEnvironment && entry.fromEnvironment !== entry.environmentGroups[0])) {
pushToOtherWallets = true;
}
}
return true;
}
} else if (index > 0 && entry.fromEnvironment) {
return wallet.fromEnvironment === entry.fromEnvironment;
}
});
} else {
otherGroupWallets = walletRegistryEntries.filter((entry: FabricWalletRegistryEntry, index: number) => {
if (index > 0 && entry.environmentGroups) {
if (wallet.environmentGroups[0] === entry.environmentGroups[0]) {
if (!pushToOtherWallets) {
// if any wallets in the group have been used for another environment then we should push the whole group to otherWallets
pushToOtherWallets = (entry.environmentGroups.length > 1) ? true : false;
}
return true;
}
} else if (index > 0 && entry.fromEnvironment) {
return wallet.environmentGroups[0] === entry.fromEnvironment;
}
});
}
group.push(...otherGroupWallets);
pushToOtherWallets === true ? otherWallets.push(group) : walletGroups.push(group);
// remove wallets that have already been grouped
walletRegistryEntries = walletRegistryEntries.filter((entry: FabricWalletRegistryEntry) => {
return !group.includes(entry);
});
totalWallets = totalWallets - group.length;
}
}
// push the otherWallets group to the main wallet group array if it isn't empty
if (otherWallets.length > 0) {
walletGroups.push(otherWallets);
}
if (walletGroups.length === 0) {
tree.push(new TextTreeItem(this, 'No wallets found'));
} else {
const otherWalletsGroupName: string = 'Other/shared wallets';
for (const group of walletGroups) {
let groupName: string;
if (group[0].fromEnvironment) {
groupName = group[0].fromEnvironment;
} else if (group[0].environmentGroups && group[0].environmentGroups.length === 1) {
groupName = group[0].environmentGroups[0];
} else {
groupName = otherWalletsGroupName;
}
const groupTreeItem: WalletGroupTreeItem = new WalletGroupTreeItem(this, groupName, group, vscode.TreeItemCollapsibleState.Expanded);
if (groupName !== otherWalletsGroupName) {
groupTreeItem.iconPath = await ExplorerUtil.getGroupIcon(groupName);
}
tree.push(groupTreeItem);
}
}
return tree;
}
private async populateWallets(walletItems: Array<FabricWalletRegistryEntry | FabricWalletRegistryEntry[]>): Promise<Array<BlockchainTreeItem>> {
const tree: Array<BlockchainTreeItem> = [];
for (const walletItem of walletItems) {
// if we've got an array then it's a group of wallets, so push a WalletGroupTreeItem instead
if (Array.isArray(walletItem)) {
const groupName: string = walletItem[0].fromEnvironment ? walletItem[0].fromEnvironment : walletItem[0].environmentGroups[0];
const groupTreeItem: WalletGroupTreeItem = new WalletGroupTreeItem(this, groupName, walletItem, vscode.TreeItemCollapsibleState.Expanded);
groupTreeItem.iconPath = await ExplorerUtil.getGroupIcon(groupName);
tree.push(groupTreeItem);
} else {
// get identityNames in the wallet
const walletGenerator: IFabricWalletGenerator = FabricWalletGeneratorFactory.getFabricWalletGenerator();
const wallet: IFabricWallet = await walletGenerator.getWallet(walletItem);
let identityNames: string[];
if (walletItem.fromEnvironment) {
const environmentEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(walletItem.fromEnvironment);
if (environmentEntry.environmentType === EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT) {
const environment: LocalMicroEnvironment = EnvironmentFactory.getEnvironment(environmentEntry) as LocalMicroEnvironment;
const visibleIdentities: FabricIdentity[] = await environment.getVisibleIdentities(walletItem.name);
identityNames = visibleIdentities.map((identity: FabricIdentity) => {
return identity.name;
});
}
}
if (identityNames === undefined) {
identityNames = await wallet.getIdentityNames();
}
// Collapse if there are identities, otherwise the expanded tree takes up a lot of room in the panel
const treeState: vscode.TreeItemCollapsibleState = identityNames.length > 0 ? vscode.TreeItemCollapsibleState.Collapsed : vscode.TreeItemCollapsibleState.None; //
if (walletItem.managedWallet) {
tree.push(new LocalWalletTreeItem(this, walletItem.name, identityNames, treeState, walletItem));
} else {
tree.push(new WalletTreeItem(this, walletItem.name, identityNames, treeState, walletItem));
}
}
}
return tree;
}
private async createIdentityTree(walletTreeItem: WalletTreeItem | LocalWalletTreeItem): Promise<BlockchainTreeItem[]> {
const tree: Array<BlockchainTreeItem> = [];
// Populate the tree with the identity names
const fabricWalletGenerator: IFabricWalletGenerator = FabricWalletGeneratorFactory.getFabricWalletGenerator();
const wallet: IFabricWallet = await fabricWalletGenerator.getWallet(walletTreeItem.registryEntry);
let identities: FabricIdentity[];
if (walletTreeItem.registryEntry.fromEnvironment) {
const environmentEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(walletTreeItem.registryEntry.fromEnvironment);
if (environmentEntry.environmentType === EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT) {
identities = await FabricWalletHelper.getVisibleIdentities(environmentEntry, walletTreeItem.registryEntry);
}
}
if (identities === undefined) {
identities = await wallet.getIdentities();
}
for (const identity of identities) {
let isAdminIdentity: boolean = false;
if (walletTreeItem instanceof LocalWalletTreeItem) {
isAdminIdentity = true;
}
// Get attributes fcn
const certificate: FabricCertificate = new FabricCertificate(identity.cert);
const attributes: Attribute[] = certificate.getAttributes();
if (isAdminIdentity) {
// User can't delete this!
tree.push(new AdminIdentityTreeItem(this, identity.name, walletTreeItem.name, attributes, walletTreeItem.registryEntry));
} else {
tree.push(new IdentityTreeItem(this, identity.name, walletTreeItem.name, attributes, walletTreeItem.registryEntry));
}
}
return tree;
}
private async updateWalletEnvironmentGroups(walletRegistryEntries: FabricWalletRegistryEntry[]): Promise<FabricWalletRegistryEntry[]> {
const outputAdapter: VSCodeBlockchainOutputAdapter = VSCodeBlockchainOutputAdapter.instance();
const finalEntries: FabricWalletRegistryEntry[] = [];
let includeWallet: boolean;
for (const wallet of walletRegistryEntries) {
includeWallet = true;
if (wallet.environmentGroups) {
const updatedGroups: string [] = [];
for (const env of wallet.environmentGroups) {
if (await FabricEnvironmentRegistry.instance().exists(env)) {
try {
const fabricEnvironmentRegistryEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(env);
if (fabricEnvironmentRegistryEntry.environmentType === EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT) {
await LocalMicroEnvironmentManager.instance().ensureRuntime(fabricEnvironmentRegistryEntry.name, undefined, fabricEnvironmentRegistryEntry.numberOfOrgs);
}
const environment: FabricEnvironment = EnvironmentFactory.getEnvironment(fabricEnvironmentRegistryEntry);
const nodes: FabricNode[] = await environment.getNodes();
const associatedNodes: boolean = nodes.some((node: FabricNode) => {
return node.wallet === wallet.name;
});
if (associatedNodes) {
updatedGroups.push(env);
}
} catch (error) {
outputAdapter.log(LogType.ERROR, `Error displaying Fabric Wallets: ${error.message}`, `Error displaying Fabric Wallets: ${error.message}`);
includeWallet = false;
}
}
}
// if the arrays aren't the same length then something has changed - update the wallet registry entry
if (wallet.environmentGroups.length !== updatedGroups.length) {
wallet.environmentGroups = updatedGroups;
await FabricWalletRegistry.instance().update(wallet);
}
}
if (includeWallet) {
finalEntries.push(wallet);
}
}
return finalEntries;
}
} | the_stack |
import {browserWindowSize, makeId, px} from "../util";
import {IHtmlElement} from "./ui";
/**
* One item in a menu.
*/
export interface BaseMenuItem {
/**
* Text that is written on screen when menu is displayed.
*/
readonly text: string;
/**
* String that is displayed as a help popup.
*/
readonly help: string;
}
export interface MenuItem extends BaseMenuItem {
/**
* Action that is executed when the item is selected by the user.
*/
readonly action: (() => void) | null;
}
abstract class BaseMenu<MI extends BaseMenuItem> implements IHtmlElement {
public items: MI[];
/**
* Actual html representations corresponding to the submenu items.
* They are stored in the same order as the items.
*/
public outer: HTMLTableElement;
public tableBody: HTMLTableSectionElement;
public cells: HTMLTableDataCellElement[];
public selectedIndex: number; // -1 if no item is selected
protected constructor() {
this.items = [];
this.cells = [];
this.selectedIndex = -1;
this.outer = document.createElement("table");
this.outer.classList.add("menu", "hidden");
this.tableBody = this.outer.createTBody();
this.outer.onkeydown = (e) => this.keyAction(e);
}
protected addItems(mis: MI[]): void {
if (mis != null) {
for (const mi of mis)
this.addItem(mi, true);
}
}
public abstract setAction(mi: MI, enabled: boolean): void;
public keyAction(e: KeyboardEvent): void {
if (e.code === "ArrowDown" && this.selectedIndex < this.cells.length - 1) {
this.select(this.selectedIndex + 1);
} else if (e.code === "ArrowUp" && this.selectedIndex > 0) {
this.select(this.selectedIndex - 1);
} else if (e.code === "Enter" && this.selectedIndex >= 0) {
// emulate a mouse click on this cell
this.cells[this.selectedIndex].click();
} else if (e.code === "Escape") {
this.hide();
}
}
/**
* Find the position of an item based on its text.
* @param text Text string in the item.
*/
public find(text: string): number {
for (let i = 0; i < this.items.length; i++)
if (this.items[i].text === text)
return i;
return -1;
}
public getHTMLRepresentation(): HTMLElement {
return this.outer;
}
public hide(): void {
this.outer.classList.add("hidden");
}
public getCell(mi: MI): HTMLTableCellElement {
const index = this.find(mi.text);
if (index < 0)
throw new Error("Cannot find menu item");
return this.cells[index];
}
public addItem(mi: MI, enabled: boolean): HTMLTableDataCellElement {
const index = this.items.length;
this.items.push(mi);
const trow = this.tableBody.insertRow();
const cell = trow.insertCell(0);
this.cells.push(cell);
if (mi.text === "---")
cell.innerHTML = "<hr>";
else
cell.textContent = mi.text;
cell.id = makeId(mi.text);
cell.style.textAlign = "left";
if (mi.help != null)
cell.title = mi.help;
cell.classList.add("menuShadow");
cell.classList.add("menuItem");
cell.onmouseenter = () => this.select(index);
cell.onmouseleave = () => this.select(-1);
this.enable(mi.text, enabled);
return cell;
}
/**
* Highlight a menu item (based on mouse position on keyboard actions).
* @param {number} index Index of item to highlight.
* @param {boolean} selected True if the item is being selected.
*/
public markSelect(index: number, selected: boolean): void {
if (index >= 0 && index < this.cells.length) {
const cell = this.cells[index];
if (selected) {
cell.classList.add("selected");
this.outer.focus();
} else {
cell.classList.remove("selected");
}
}
}
public select(index: number): void {
if (this.selectedIndex >= 0)
this.markSelect(this.selectedIndex, false);
if (index < 0 || index >= this.cells.length)
index = -1; // no one
this.selectedIndex = index;
this.markSelect(this.selectedIndex, true);
}
public enableByIndex(index: number, enabled: boolean): void {
const cell = this.cells[index];
if (enabled)
cell.classList.remove("disabled");
else
cell.classList.add("disabled");
this.setAction(this.items[index], enabled);
}
public enableItem(mi: MI, enabled: boolean): void {
this.enable(mi.text, enabled);
}
/**
* Remove all elements from the menu.
*/
public clear(): void {
this.tableBody.remove();
this.items = [];
this.cells = [];
this.tableBody = this.outer.createTBody();
}
/**
* Mark a menu item as enabled or disabled. If disabled the action
* cannot be triggered.
* @param {string} text Text of the item which identifies the item.
* @param {boolean} enabled If true the menu item is enabled, else it is disabled.
*/
public enable(text: string, enabled: boolean): void {
const index = this.find(text);
if (index < 0)
throw new Error("Cannot find menu item " + text);
this.enableByIndex(index, enabled);
}
}
/**
* A context menu is displayed on right-click on some displayed element.
*/
export class ContextMenu extends BaseMenu<MenuItem> implements IHtmlElement {
protected foldOuts: FoldoutMenu[];
/**
* Create a context menu.
* @param parent HTML element where this is inserted.
* @param {MenuItem[]} mis List of menu items in the context menu.
*/
constructor(public readonly parent: Element, mis?: MenuItem[]) {
super();
this.foldOuts = [];
if (mis != null)
this.addItems(mis);
this.outer.classList.add("dropdown");
this.outer.classList.add("menu");
this.outer.onmouseleave = () => { this.hide(); };
parent.appendChild(this.getHTMLRepresentation());
this.hide();
}
// We use 5 to leave room for border and shadow
static readonly borderSize = 5;
public show(): void {
this.outer.classList.remove("hidden");
this.outer.tabIndex = 1; // necessary for keyboard events?
this.outer.focus();
}
public clear(): void {
super.clear();
for (const f of this.foldOuts)
f.clear();
this.foldOuts = [];
}
/**
* Display the menu.
*/
public showAtMouse(e: MouseEvent): void {
e.preventDefault();
// Spawn the menu at the mouse's location
let x = e.clientX - ContextMenu.borderSize;
let y = e.clientY - ContextMenu.borderSize;
this.showAt(x, y);
}
public showAt(x: number, y: number): void {
this.show();
const max = browserWindowSize();
if (this.outer.offsetWidth + x >= max.width)
x = max.width - this.outer.offsetWidth - ContextMenu.borderSize;
if (this.outer.offsetHeight + y >= max.height)
y = max.height - this.outer.offsetHeight - ContextMenu.borderSize;
if (y < 0)
y = 0;
this.move(x, y);
}
/**
* Place the menu at some specific position on the screen.
* @param {number} x Absolute x coordinate within browser window.
* @param {number} y Absolute y coordinate within browser window.
*/
public move(x: number, y: number): void {
this.outer.style.left = px(x);
this.outer.style.top = px(y);
}
public setAction(mi: MenuItem, enabled: boolean): void {
const index = this.find(mi.text);
const cell = this.cells[index];
if (mi.action != null && enabled) {
cell.onclick = () => {
this.hide();
mi.action!();
};
} else {
cell.onclick = () => this.hide();
}
}
public addExpandableItem(text: string, help: string): FoldoutMenu {
const fo = new FoldoutMenu(this);
this.foldOuts.push(fo);
const show = () => {
// Function executed when displaying the foldout menu.
// It computes the coordinates on the screen where the menu should
// be displayed.
const max = browserWindowSize();
let x = this.outer.offsetLeft + this.outer.offsetWidth;
let y = arrow.offsetTop + cell.offsetTop + this.outer.offsetTop - ContextMenu.borderSize;
fo.show(); // display to measure the sizes
if (x + fo.outer.offsetWidth > max.width)
// we want a bit of overlap, so there's no gap for the mouse.
// the gap would hide both menus
x = this.outer.offsetLeft - fo.outer.offsetWidth + ContextMenu.borderSize;
if (y + fo.outer.offsetHeight > max.height)
y = max.height - fo.outer.offsetHeight;
fo.showAt(x, y);
this.select(index);
};
const item: MenuItem = {
text,
help,
action: show
}
const index = this.cells.length;
const cell = this.addItem(item, true);
const arrow = document.createElement("span");
arrow.textContent = "▸";
arrow.classList.add("menuArrow");
cell.appendChild(arrow);
cell.onmouseenter = show;
cell.onmouseleave = () => {
fo.hide();
this.select(-1);
}
return fo;
}
}
export class FoldoutMenu extends ContextMenu {
constructor(protected parentMenu: ContextMenu) {
super(parentMenu.parent);
this.outer.onmouseenter = () => this.show();
}
addItem(mi: MenuItem, enabled: boolean): HTMLTableDataCellElement {
return super.addItem({
text: mi.text,
help: mi.help,
action: () => {
this.parentMenu.hide();
if (mi.action != null)
mi.action();
}
}, enabled);
}
public show(): void {
this.parentMenu.show();
super.show();
}
public showAt(x: number, y: number): void {
super.showAt(x, y);
this.parentMenu.show();
}
}
/**
* A sub-menu is a menu displayed when selecting an item
* from a topmenu.
*/
export class SubMenu extends BaseMenu<MenuItem> implements IHtmlElement {
/**
* Build a submenu.
* @param {MenuItem[]} mis List of items to display.
*/
constructor(mis: MenuItem[]) {
super();
this.addItems(mis);
}
public show(): void {
this.outer.classList.remove("hidden");
this.outer.tabIndex = 1; // necessary for keyboard events?
}
public setAction(mi: MenuItem, enabled: boolean): void {
const cell = this.getCell(mi);
if (mi.action != null && enabled)
cell.onclick = (e: MouseEvent) => { e.stopPropagation(); this.hide(); mi.action!(); };
else
cell.onclick = (e: MouseEvent) => { e.stopPropagation(); this.hide(); };
}
}
/**
* A topmenu is composed only of submenus.
* TODO: allow a topmenu to also have simple items.
*/
export interface TopMenuItem extends BaseMenuItem {
readonly subMenu: SubMenu;
}
/**
* A TopMenu is a two-level menu.
*/
export class TopMenu extends BaseMenu<TopMenuItem> {
/**
* Create a topmenu.
* @param {TopMenuItem[]} mis List of top menu items to display.
*/
constructor(mis: TopMenuItem[]) {
super();
this.outer.classList.add("topMenu");
this.outer.classList.remove("hidden");
this.tableBody.insertRow();
this.addItems(mis);
}
public hideSubMenus(): void {
this.items.forEach((mi) => mi.subMenu.hide());
}
public addItem(mi: TopMenuItem, enabled: boolean): HTMLTableDataCellElement {
const cell = this.tableBody.rows.item(0)!.insertCell();
cell.id = makeId(mi.text); // for testing
cell.textContent = mi.text;
cell.appendChild(mi.subMenu.getHTMLRepresentation());
cell.classList.add("menuItem");
if (mi.help != null)
cell.title = mi.help;
this.items.push(mi);
this.cells.push(cell);
this.setAction(mi, enabled);
return cell;
}
public setAction(mi: TopMenuItem, enabled: boolean): void {
const cell = this.getCell(mi);
cell.onclick = enabled ? () => {
this.hideSubMenus();
cell.classList.add("selected");
mi.subMenu.show();
} : () => {
this.hideSubMenus();
};
cell.onmouseleave = () => {
cell.classList.remove("selected");
this.hideSubMenus();
};
}
public getHTMLRepresentation(): HTMLElement {
return this.outer;
}
/**
* Find the position of an item
* @param text Text string in the item.
*/
public getSubmenu(text: string): SubMenu | null {
for (const item of this.items)
if (item.text === text)
return item.subMenu;
return null;
}
} | the_stack |
import { runInAction } from "mobx";
import { URL } from "url";
import {
commands,
env,
ExtensionContext,
ProgressLocation,
QuickPickItem,
Uri,
window,
workspace
} from "vscode";
import { EXTENSION_NAME } from "../constants";
import { duplicateGist, exportToRepo } from "../fileSystem/git";
import { openRepo } from "../repos/store/actions";
import { Gist, GistFile, GroupType, SortOrder, store } from "../store";
import {
changeDescription,
deleteGist,
forkGist,
getForks,
newGist,
refreshGist,
refreshGists,
starGist,
starredGists,
unstarGist
} from "../store/actions";
import { ensureAuthenticated, getApi, signIn } from "../store/auth";
import {
FollowedUserGistNode,
GistNode,
GistsNode,
StarredGistNode
} from "../tree/nodes";
import { createGistPadOpenUrl } from "../uriHandler";
import {
byteArrayToString,
closeGistFiles,
encodeDirectoryName,
fileNameToUri,
getGistDescription,
getGistLabel,
getGistWorkspaceId,
isGistWorkspace,
openGist,
openGistFiles,
sortGists,
updateGistTags,
withProgress
} from "../utils";
const isBinaryPath = require("is-binary-path");
const GIST_NAME_PATTERN = /(\/)?(?<owner>([a-z\d]+-)*[a-z\d]+)\/(?<id>[^\/]+)$/i;
export interface GistQuickPickItem extends QuickPickItem {
id?: string;
}
const newPublicGist = newGistInternal.bind(null, true);
const newSecretGist = newGistInternal.bind(null, false);
async function newGistInternal(isPublic: boolean = true) {
await ensureAuthenticated();
const title = "Create new " + (isPublic ? "" : "secret ") + "gist";
const totalSteps = 2;
let currentStep = 1;
const descriptionInputBox = window.createInputBox();
descriptionInputBox.title = title;
descriptionInputBox.prompt = "Enter an optional description for the new Gist";
descriptionInputBox.step = currentStep++;
descriptionInputBox.totalSteps = totalSteps;
descriptionInputBox.onDidAccept(() => {
descriptionInputBox.hide();
const description = descriptionInputBox.value;
const fileNameInputBox = window.createInputBox();
fileNameInputBox.title = title;
fileNameInputBox.prompt =
"Enter the files name(s) to seed the Gist with (can be a comma-separated list)";
fileNameInputBox.step = currentStep++;
fileNameInputBox.totalSteps = totalSteps;
fileNameInputBox.placeholder = "foo.md";
fileNameInputBox.onDidAccept(() => {
fileNameInputBox.hide();
const fileName = fileNameInputBox.value;
if (!fileName) {
fileNameInputBox.validationMessage =
"You must specify at least one filename in order to create a gist.";
// TODO: Have a regex check for valid input
return;
}
return window.withProgress(
{ location: ProgressLocation.Notification, title: "Creating Gist..." },
() => {
const files = fileName
.split(",")
.map((filename) => ({ filename: encodeDirectoryName(filename) }));
return newGist(files, isPublic, description);
}
);
});
fileNameInputBox.show();
});
descriptionInputBox.show();
}
const SIGN_IN_ITEM = "Sign in to view Gists...";
const CREATE_PUBLIC_GIST_ITEM = "$(gist-new) Create new public Gist...";
const CREATE_SECRET_GIST_ITEM = "$(gist-private) Create new secret Gist...";
const STARRED_GIST_ITEM = "$(star) View starred Gists...";
const CREATE_GIST_ITEMS = [
{ label: CREATE_PUBLIC_GIST_ITEM },
{ label: CREATE_SECRET_GIST_ITEM },
{ label: STARRED_GIST_ITEM }
];
interface IOpenGistOptions {
openAsWorkspace?: boolean;
forceNewWindow?: boolean;
node?: GistNode;
gistUrl?: string;
gistId?: string;
}
const getGistIdFromUrl = (gistUrl: string) => {
const url = new URL(gistUrl);
const { pathname } = url;
const pathnameComponents = pathname.split("/");
const id = pathnameComponents[pathnameComponents.length - 1];
return id;
};
async function openGistInternal(
options: IOpenGistOptions = { openAsWorkspace: false, forceNewWindow: false }
) {
const { node, openAsWorkspace, forceNewWindow, gistUrl, gistId } = options;
if (gistUrl || gistId) {
const id = gistId ? gistId : getGistIdFromUrl(gistUrl!); // (!) since the `gistId` is not set, means the `gistUrl` is set
return openGist(id, !!openAsWorkspace, !!forceNewWindow);
} else if (node) {
return openGist(node.gist.id, !!openAsWorkspace, !!forceNewWindow);
}
let gistItems: GistQuickPickItem[] = [];
if (store.isSignedIn) {
const gists = store.gists;
if (gists.length > 0) {
gistItems = gists.map((gist) => {
return <GistQuickPickItem>{
label: getGistLabel(gist),
description: getGistDescription(gist),
id: gist.id
};
});
}
gistItems.push(...CREATE_GIST_ITEMS);
} else {
gistItems = [{ label: SIGN_IN_ITEM }];
}
const list = window.createQuickPick();
list.placeholder = "Select the gist to open, or specify a gist URL or ID";
list.items = gistItems;
list.ignoreFocusOut = true;
list.onDidChangeValue((gistId) => {
list.items = gistId
? [{ label: gistId, id: gistId }, ...gistItems]
: gistItems;
});
const clipboardValue = await env.clipboard.readText();
if (GIST_NAME_PATTERN.test(clipboardValue)) {
list.value = clipboardValue;
list.items = [{ label: clipboardValue, id: clipboardValue }, ...gistItems];
}
list.onDidAccept(async () => {
const gist = <GistQuickPickItem>list.selectedItems[0] || list.value;
list.hide();
// The "id" property is only set on list items
// that are added in response to user input, as
// opposed to being part of the list of owned gists.
if (gist.id) {
let gistId = gist.id;
if (GIST_NAME_PATTERN.test(gist.id)) {
gistId = GIST_NAME_PATTERN.exec(gist.id)!.groups!.id;
}
openGist(gistId, !!openAsWorkspace);
} else {
switch (gist.label) {
case SIGN_IN_ITEM:
await signIn();
await openGistInternal();
return;
case CREATE_PUBLIC_GIST_ITEM:
return await newPublicGist();
case CREATE_SECRET_GIST_ITEM:
return await newSecretGist();
case STARRED_GIST_ITEM:
return await starredGistsInternal();
default:
}
}
});
list.show();
}
async function starredGistsInternal() {
await ensureAuthenticated();
const gists = await starredGists();
const items = sortGists(gists).map((g) => ({
label: getGistLabel(g),
description: getGistDescription(g),
id: g.id
}));
if (items.length === 0) {
const message = `You don't have any starred Gists`;
return window.showInformationMessage(message);
}
const selected = await window.showQuickPick(items, {
placeHolder: "Select the Gist you'd like to open"
});
if (selected) {
openGistFiles(selected.id);
}
}
export async function registerGistCommands(context: ExtensionContext) {
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.changeGistDescription`,
async (node?: GistNode) => {
await ensureAuthenticated();
if (node) {
const description = await window.showInputBox({
prompt: "Specify the description for this Gist",
value: node.gist.description
});
if (!description) {
return;
}
await changeDescription(node.gist.id, description);
}
}
)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.cloneRepository`,
async (node: GistNode) => {
commands.executeCommand("git.clone", node.gist.git_pull_url);
}
)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.copyGistUrl`,
async (node: GistNode) => {
// Note: The "html_url" property doesn't include the Gist's owner
// in it, and the API doesn't support that URL format
const url = `https://gist.github.com/${node.gist.owner!.login}/${
node.gist.id
}`;
env.clipboard.writeText(url);
}
)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.copyGistPadUrl`,
async (node: GistNode) => {
const url = createGistPadOpenUrl(node.gist.id);
env.clipboard.writeText(url);
}
)
);
const DELETE_RESPONSE = "Delete";
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.deleteGist`,
async (targetNode?: GistNode, multiSelectNodes?: GistNode[]) => {
await ensureAuthenticated();
if (targetNode) {
const suffix = multiSelectNodes
? "selected gists"
: `"${targetNode.label}" gist`;
const response = await window.showInformationMessage(
`Are you sure you want to delete the ${suffix}?`,
DELETE_RESPONSE
);
if (response !== DELETE_RESPONSE) {
return;
}
const nodes = multiSelectNodes || [targetNode];
await runInAction(async () => {
for (const node of nodes) {
await deleteGist(node.gist.id);
await closeGistFiles(node.gist);
}
});
} else if (isGistWorkspace()) {
const response = await window.showInformationMessage(
"Are you sure you want to delete the opened Gist?",
DELETE_RESPONSE
);
if (response !== DELETE_RESPONSE) {
return;
}
const gistId = getGistWorkspaceId();
deleteGist(gistId);
commands.executeCommand("workbench.action.closeFolder");
} else {
const gists = store.gists;
if (gists.length === 0) {
return window.showInformationMessage(
"You don't have any Gists to delete"
);
}
const items = gists.map((g) => ({
label: getGistLabel(g),
description: getGistDescription(g),
id: g.id
}));
const gist = await window.showQuickPick(items, {
placeHolder: "Select the Gist to delete..."
});
if (!gist) {
return;
}
await withProgress("Deleting gist...", async () => {
await deleteGist(gist.id);
await closeGistFiles(gists.find((gist) => gist.id === gist.id)!);
});
}
}
)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.forkGist`,
async (node?: StarredGistNode | FollowedUserGistNode) => {
await ensureAuthenticated();
let gistId: string | undefined;
if (node) {
gistId = node.gist.id;
} else if (isGistWorkspace()) {
gistId = getGistWorkspaceId();
} else {
// TODO: Display the list of starred gists
gistId = await window.showInputBox({
prompt: "Enter the Gist ID to fork"
});
if (!gistId) {
return;
}
}
await window.withProgress(
{ location: ProgressLocation.Notification, title: "Forking Gist..." },
() => forkGist(gistId!)
);
}
)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.viewForks`,
async (node?: StarredGistNode | FollowedUserGistNode) => {
if (node) {
const forks = await getForks(node.gist.id);
if (forks.length === 0) {
return window.showInformationMessage(
"This gist doesn't have any forks."
);
}
const getDescription = (gist: Gist) => {
const isModified = gist.created_at !== gist.updated_at;
return `${getGistDescription(gist)}${isModified ? " $(edit)" : ""}`;
};
const items = sortGists(forks).map((g) => ({
label: g.owner.login,
description: getDescription(g),
id: g.id
}));
const selected = await window.showQuickPick(items, {
placeHolder: "Select the forked gist you'd like to open..."
});
if (selected) {
openGistFiles(selected.id);
}
}
}
)
);
context.subscriptions.push(
commands.registerCommand(`${EXTENSION_NAME}.newPublicGist`, newPublicGist)
);
context.subscriptions.push(
commands.registerCommand(`${EXTENSION_NAME}.newSecretGist`, newSecretGist)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.openGist`,
(node?: GistNode | GistsNode) => {
// We expose the "Open Gist" command on the "Your Gists" node
// for productivity purposes, but that node doesn't contain
// a gist, and so if the user is coming in from there, then
// don't pass on the tree node object to the open gist method.
const gistNode =
node instanceof GistNode ||
node instanceof StarredGistNode ||
node instanceof FollowedUserGistNode
? node
: undefined;
openGistInternal({ node: gistNode });
}
)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.openGistInBrowser`,
async (node: GistNode) => {
env.openExternal(Uri.parse(node.gist.html_url));
}
)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.openGistInNbViewer`,
async (node: GistNode) => {
const url = `https://nbviewer.jupyter.org/gist/${node.gist.owner.login}/${node.gist.id}`;
env.openExternal(Uri.parse(url));
}
)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.openGistWorkspace`,
(node?: GistNode) => {
openGistInternal({ node, openAsWorkspace: true });
}
)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.openGistNewWindow`,
(node?: GistNode) => {
openGistInternal({ node, openAsWorkspace: true, forceNewWindow: true });
}
)
);
context.subscriptions.push(
commands.registerCommand(`${EXTENSION_NAME}.refreshGists`, refreshGists)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.sortGistsAlphabetically`,
() => {
store.sortOrder = SortOrder.alphabetical;
}
)
);
context.subscriptions.push(
commands.registerCommand(`${EXTENSION_NAME}.sortGistsByUpdatedTime`, () => {
store.sortOrder = SortOrder.updatedTime;
})
);
context.subscriptions.push(
commands.registerCommand(`${EXTENSION_NAME}.groupGists`, () => {
store.groupType = GroupType.tagAndType;
})
);
context.subscriptions.push(
commands.registerCommand(`${EXTENSION_NAME}.ungroupGists`, () => {
store.groupType = GroupType.none;
})
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.starredGists`,
starredGistsInternal
)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.exportToRepo`,
async (node: GistNode) => {
if (!store.canCreateRepos) {
return window.showErrorMessage(
'The token you used to login doesn\'t include the "repo" scope.'
);
}
const repoName = await window.showInputBox({
prompt: "Specify the name of the repository to create",
value: node.gist.description || ""
});
if (!repoName) {
return;
}
let repoUri, fullName;
await withProgress("Exporting to repository...", async () => {
const api = await getApi();
const name = repoName.replace(/\s/g, "-").replace(/[^\w\d-_]/g, "");
const response = await api.post("/user/repos", {
name,
description: node.gist.description,
private: !node.gist.public
});
repoUri = Uri.parse(response.body.html_url);
fullName = `${store.login}/${name}`;
// TODO: Accomodate scenarios where the end-user
// doesn't have Git installed
await exportToRepo(node.gist.id, name);
await openRepo(fullName, true);
});
if (
await window.showInformationMessage(
`Gist successfully exported to "${fullName}".`,
"Open in browser"
)
) {
// @ts-ignore
return env.openExternal(repoUri);
}
}
)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.unstarGist`,
async (
targetNode: StarredGistNode,
multiSelectNodes?: StarredGistNode[]
) => {
await ensureAuthenticated();
const nodes = multiSelectNodes || [targetNode];
for (const node of nodes) {
unstarGist(node.gist.id);
}
}
)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.starGist`,
async (
targetNode: GistNode | FollowedUserGistNode,
multiSelectNodes?: GistNode[] | FollowedUserGistNode[]
) => {
await ensureAuthenticated();
const nodes = multiSelectNodes || [targetNode];
for (const node of nodes) {
starGist(node.gist);
}
}
)
);
context.subscriptions.push(
commands.registerCommand(
`${EXTENSION_NAME}.duplicateGist`,
async (node: GistNode) => {
await ensureAuthenticated();
const description = await window.showInputBox({
prompt: "Enter an optional description for the new Gist",
value: node.gist.description
});
await window.withProgress(
{
location: ProgressLocation.Notification,
title: "Duplicating Gist..."
},
async () => {
const includesBinaryFile = Object.keys(node.gist.files).some(
isBinaryPath
);
if (includesBinaryFile) {
// Create a new gist with a "placeholder" file,
// since gists aren't allowed to be empty.
const gist = await newGist(
[{ filename: "placeholder", content: "" }],
node.gist.public,
description,
false
);
await duplicateGist(node.gist.id, gist.id);
// Since the created gist doesn't include the files
// that were pushed via git, we need to refresh it
// in our local Mobx store and then update the tags
await refreshGist(gist.id);
await updateGistTags(gist);
} else {
const files: GistFile[] = [];
for (const filename of Object.keys(node.gist.files)) {
const content = byteArrayToString(
await workspace.fs.readFile(
fileNameToUri(node.gist.id, filename)
)
);
files.push({
filename,
content
});
}
await newGist(files, node.gist.public, description);
}
}
);
}
)
);
} | the_stack |
import * as moment from 'moment-timezone';
import { Observable, Subject } from 'rxjs';
import agent from '@egjs/agent';
import { IOptions } from './scatter-chart.class';
import { ScatterChartSizeCoordinateManager } from './scatter-chart-size-coordinate-manager.class';
export class ScatterChartMouseManager {
private browserName: string;
elementAxisWrapper: HTMLElement;
elementXAxisLabelWrapper: HTMLElement;
elementXAxisLabel: HTMLElement;
elementYAxisLabelWrapper: HTMLElement;
elementYAxisLabel: HTMLElement;
elementDragWrapper: HTMLElement;
elementDragArea: HTMLElement;
private outDragArea: Subject<any>;
onDragArea$: Observable<any>;
constructor(
private options: IOptions,
private coordinateManager: ScatterChartSizeCoordinateManager,
private elementContainer: HTMLElement
) {
this.browserName = agent().browser.name;
this.outDragArea = new Subject();
this.onDragArea$ = this.outDragArea.asObservable();
const padding = this.coordinateManager.getPadding();
const areaWidth = this.coordinateManager.getWidth() - padding.left - padding.right;
const areaHeight = this.coordinateManager.getHeight() - padding.top - padding.bottom;
const redLineWidth = 10;
this.initWrapperElement(areaWidth, areaHeight);
this.initXLabelElement(areaHeight, redLineWidth);
this.initYLabelElement(padding.left, redLineWidth);
this.initDragElement();
this.initEvent();
}
private initWrapperElement(areaWidth: number, areaHeight: number): void {
this.elementAxisWrapper = document.createElement('div');
this.elementAxisWrapper.setAttribute('style', `
top: ${this.coordinateManager.getTopPadding()}px;
left: ${this.coordinateManager.getLeftPadding()}px;
width: ${areaWidth}px;
height: ${areaHeight}px;
cursor: crosshair;
z-index: 600;
position: absolute;
user-select: none;
background-color: rgba(0,0,0,0);
`);
this.elementAxisWrapper.setAttribute('class', 'overlay');
this.elementContainer.appendChild(this.elementAxisWrapper);
}
private initXLabelElement(areaHeight: number, redLineWidth: number): void {
this.elementXAxisLabelWrapper = document.createElement('div');
this.elementXAxisLabelWrapper.draggable = false;
this.elementXAxisLabelWrapper.setAttribute('style', `
top: ${areaHeight + redLineWidth}px;
left: 0px;
color: #FFF;
width: 80px;
display: none;
position: absolute;
text-align: center;
background: #000;
user-select: none;
font-family: monospace;
margin-left: ${-(56 / 2)}px;
` + this.options.axisLabelStyle);
this.elementXAxisLabel = document.createElement('span');
const elementXLine = document.createElement('div');
elementXLine.setAttribute('style', `
top: ${-redLineWidth}px;
left: 27px;
height: ${redLineWidth}px;
position: absolute;
border-left: 1px solid red;
`);
this.elementXAxisLabelWrapper.appendChild(this.elementXAxisLabel);
this.elementXAxisLabelWrapper.appendChild(elementXLine);
this.elementAxisWrapper.appendChild(this.elementXAxisLabelWrapper);
}
private initYLabelElement(paddingLeft: number, redLineWidth: number): void {
this.elementYAxisLabelWrapper = document.createElement('div');
this.elementYAxisLabelWrapper.draggable = false;
this.elementYAxisLabelWrapper.setAttribute('style', `
top: 0px;
left: ${-(paddingLeft - 2)}px;
color: #fff;
width: ${paddingLeft - 2 - redLineWidth}px;
display: none;
position: absolute;
margin-top: ${-redLineWidth}px;
text-align: right;
background: #000;
font-family: monospace;
padding-right: 3px;
vertical-align: middle;
` + this.options.axisLabelStyle);
this.elementYAxisLabel = document.createElement('span');
const elementYLine = document.createElement('div');
elementYLine.setAttribute('style', `
top: 9px;
right: -10px;
width: ${redLineWidth}px;
position: absolute;
border-top: 1px solid red;
`);
this.elementYAxisLabelWrapper.appendChild(this.elementYAxisLabel);
this.elementYAxisLabelWrapper.appendChild(elementYLine);
this.elementAxisWrapper.appendChild(this.elementYAxisLabelWrapper);
}
private initDragElement(): void {
this.elementDragWrapper = document.createElement('div');
this.elementDragWrapper.setAttribute('style', `
touch-action: none;
top: 0px;
left: 0px;
width: ${this.coordinateManager.getWidth()}px;
height: ${this.coordinateManager.getHeight()}px;
cursor: crosshair;
z-index: 601;
position: absolute;
background-color: rgba(0,0,0,0);
`);
this.elementDragArea = document.createElement('div');
this.elementDragArea.setAttribute('style', `
width: 0px;
height: 0px;
display: none;
position: absolute;
border: 1px solid #469AE4;
background-color: rgba(237, 242, 248, 0.5);
`);
this.elementDragWrapper.appendChild(this.elementDragArea);
this.elementContainer.appendChild(this.elementDragWrapper);
}
private initEvent() {
const padding = this.coordinateManager.getPadding();
const areaWidth = this.coordinateManager.getWidth();
const areaHeight = this.coordinateManager.getHeight();
const axisArea = {
leftRevision: this.coordinateManager.getBubbleHalfSize() + padding.left,
width: areaWidth - this.coordinateManager.getBubbleHalfSize() + padding.left - padding.right,
topRevision: padding.top,
height: areaHeight - padding.top - padding.bottom - this.coordinateManager.getBubbleHalfSize()
};
let startDrag = false;
let dragStartX = 0;
let dragStartY = 0;
let calculatedOffsetX = 0;
let calculatedOffsetY = 0;
let previousDragX = -1;
let previousDragY = -1;
let previousClientX = 0;
let previousClientY = 0;
function forceMouseUp(userMouseUp: boolean) {
startDrag = false;
this.elementDragArea.style.display = 'none';
if (userMouseUp) {
const fromX = (calculatedOffsetX >= dragStartX ? dragStartX : calculatedOffsetX) - axisArea.leftRevision;
const toX = (calculatedOffsetX >= dragStartX ? calculatedOffsetX : dragStartX) - axisArea.leftRevision;
const fromY = (calculatedOffsetY >= dragStartY ? calculatedOffsetY : dragStartY) - axisArea.topRevision;
const toY = (calculatedOffsetY >= dragStartY ? dragStartY : calculatedOffsetY) - axisArea.topRevision;
this.outDragArea.next({
x: {
from: Math.max(fromX, 0),
to: Math.min(toX, axisArea.width)
},
y: {
// y값은 from과 to를 뒤집어서 보내야 함.
from: Math.max(axisArea.height - fromY, 0),
to: Math.min(axisArea.height - toY, axisArea.height)
}
});
}
this.elementDragArea.style.top = '0px';
this.elementDragArea.style.left = '0px';
this.elementDragArea.style.width = '0px';
this.elementDragArea.style.height = '0px';
previousDragX = -1;
previousDragY = -1;
}
function preventDefault(e: any) {
e.preventDefault();
}
function disableScroll() {
document.body.addEventListener('touchmove', preventDefault, { passive: false });
}
function enableScroll() {
document.body.removeEventListener('touchmove', preventDefault);
}
['mousedown', 'touchstart'].forEach((eventName: string) => {
this.elementDragWrapper.addEventListener(eventName, (event: MouseEvent | TouchEvent) => {
const isTouch = event.type.startsWith('touch');
let x, y;
if (isTouch) {
disableScroll();
const touchEvent = event as TouchEvent;
const clientRect = (touchEvent.target as HTMLElement).offsetParent.getBoundingClientRect();
previousClientX = touchEvent.touches[0].clientX;
previousClientY = touchEvent.touches[0].clientY;
x = previousClientX - clientRect.left;
y = previousClientY - clientRect.top;
} else if (this.browserName === 'safari') {
const mouseEvent = event as MouseEvent;
const clientRect = (mouseEvent.target as HTMLElement).offsetParent.getBoundingClientRect();
x = previousClientX - clientRect.left;
y = previousClientY - clientRect.top;
} else {
const mouseEvent = event as MouseEvent;
x = mouseEvent.offsetX;
y = mouseEvent.offsetY;
}
startDrag = true;
dragStartX = calculatedOffsetX = x;
dragStartY = calculatedOffsetY = y;
this.elementDragArea.style.display = 'block';
this.elementDragArea.style.top = dragStartY + 'px';
this.elementDragArea.style.left = dragStartX + 'px';
if (isTouch === false) {
event.preventDefault();
}
});
});
['mouseup', 'touchend'].forEach((eventName: string) => {
this.elementDragWrapper.addEventListener(eventName, (event: MouseEvent | TouchEvent) => {
const isTouch = event.type.startsWith('touch');
forceMouseUp.call(this, true);
if (isTouch === false) {
event.preventDefault();
} else {
enableScroll();
}
});
});
['mousemove', 'touchmove'].forEach((eventName: string) => {
this.elementDragWrapper.addEventListener(eventName, (event: MouseEvent | TouchEvent) => {
const isTouch = event.type.startsWith('touch');
let offsetX, offsetY;
if (isTouch) {
const touchEvent = event as TouchEvent;
offsetX = touchEvent.touches[0].clientX - previousClientX;
offsetY = touchEvent.touches[0].clientY - previousClientY;
previousClientX = touchEvent.touches[0].clientX;
previousClientY = touchEvent.touches[0].clientY;
} else if (this.browserName === 'safari') {
const mouseEvent = event as MouseEvent;
offsetX = mouseEvent.clientX - previousClientX;
offsetY = mouseEvent.clientY - previousClientY;
previousClientX = mouseEvent.clientX;
previousClientY = mouseEvent.clientY;
} else {
const mouseEvent = event as MouseEvent;
offsetX = mouseEvent.movementX;
offsetY = mouseEvent.movementY;
}
calculatedOffsetX += offsetX;
calculatedOffsetY += offsetY;
if (startDrag) {
this.checkAxisLabel(calculatedOffsetX, calculatedOffsetY, axisArea);
if (previousDragX !== calculatedOffsetX) {
if (calculatedOffsetX <= areaWidth) {
if (calculatedOffsetX >= dragStartX) {
this.elementDragArea.style.left = dragStartX + 'px';
this.elementDragArea.style.width = (calculatedOffsetX - dragStartX) + 'px';
} else {
this.elementDragArea.style.left = calculatedOffsetX + 'px';
this.elementDragArea.style.width = (dragStartX - calculatedOffsetX) + 'px';
}
previousDragX = calculatedOffsetX;
}
}
if (previousDragY !== calculatedOffsetY) {
if (calculatedOffsetY <= areaHeight) {
if (calculatedOffsetY >= dragStartY) {
this.elementDragArea.style.top = dragStartY + 'px';
this.elementDragArea.style.height = (calculatedOffsetY - dragStartY) + 'px';
} else {
this.elementDragArea.style.top = calculatedOffsetY + 'px';
this.elementDragArea.style.height = (dragStartY - calculatedOffsetY) + 'px';
}
previousDragY = calculatedOffsetY;
}
}
} else {
this.checkAxisLabel(offsetX, offsetY, axisArea);
}
if (isTouch === false) {
event.preventDefault();
}
});
});
this.elementDragWrapper.addEventListener('mouseleave', (event: MouseEvent) => {
forceMouseUp.call(this, false);
this.hideAxisLabel();
event.preventDefault();
return false;
});
}
private checkAxisLabel(offsetX: number, offsetY: number, axisArea: any): void {
if (!this.options.showMouseGuideLine) {
return;
}
const x = offsetX - axisArea.leftRevision;
const y = offsetY - axisArea.topRevision;
if (x >= 0 && x <= axisArea.width || y >= 0 && y <= axisArea.height) {
if (x >= 0 && x <= axisArea.width) {
this.showXAxisLabel();
} else {
this.hideXAxisLabel();
}
if (y >= 0 && y <= axisArea.height) {
this.showYAxisLabel();
} else {
this.hideYAxisLabel();
}
this.setAndMoveAxisLabel(x, y);
} else {
this.hideAxisLabel();
}
// if (x >= 0 && x <= axisArea.width && y >= 0 && y <= axisArea.height) {
// this.showAxisLabel();
// this.setAndMoveAxisLabel(x, y);
// } else {
// this.hideAxisLabel();
// }
}
private setAndMoveAxisLabel(x: number, y: number): void {
const height = this.coordinateManager.getHeight();
const padding = this.coordinateManager.getPadding();
const bubbleHalfSize = this.coordinateManager.getBubbleHalfSize();
const xLabel = moment(this.coordinateManager.parseMouseXToXData(x - bubbleHalfSize)).tz(this.options.timezone).format(this.options.dateFormat[1]);
const yLabel = this.coordinateManager.parseMouseYToYData(height - y - padding.bottom - padding.top - bubbleHalfSize);
this.elementXAxisLabel.textContent = xLabel;
this.elementYAxisLabel.textContent = yLabel.toLocaleString();
this.elementXAxisLabelWrapper.style.left = (x + bubbleHalfSize) + 'px';
this.elementYAxisLabelWrapper.style.top = (y + bubbleHalfSize) + 'px';
}
showXAxisLabel(): void {
this.elementXAxisLabelWrapper.style.display = 'block';
}
showYAxisLabel(): void {
this.elementYAxisLabelWrapper.style.display = 'block';
}
showAxisLabel(): void {
this.showXAxisLabel();
this.showYAxisLabel();
}
hideXAxisLabel(): void {
this.elementXAxisLabelWrapper.style.display = 'none';
}
hideYAxisLabel(): void {
this.elementYAxisLabelWrapper.style.display = 'none';
}
hideAxisLabel(): void {
this.hideXAxisLabel();
this.hideYAxisLabel();
}
// triggerDrag(welFakeSelectBox) {
// var oDragAreaPosition = this._adjustSelectBoxForChart(welFakeSelectBox);
// this._oCallback.onSelect(oDragAreaPosition, this._parseCoordinatesToXY(oDragAreaPosition));
// }
// _adjustSelectBoxForChart(welSelectBox) {
// var oPadding = this._oSCManager.getPadding();
// var bubbleSize = this._oSCManager.getBubbleSize();
// var nMinTop = oPadding.top + bubbleSize;
// var nMinLeft = oPadding.left + bubbleSize;
// var nMaxRight = this._oSCManager.getWidth() - oPadding.right - bubbleSize;
// var nMaxBottom = this._oSCManager.getHeight() - oPadding.bottom - bubbleSize;
// var nLeft = parseInt(welSelectBox.css("left"), 10);
// var nRight = nLeft + welSelectBox.width();
// var nTop = parseInt(welSelectBox.css("top"), 10);
// var nBottom = nTop + welSelectBox.height();
// nTop = Math.max(nTop, nMinTop);
// nLeft = Math.max(nLeft, nMinLeft);
// nRight = Math.min(nRight, nMaxRight);
// nBottom = Math.min(nBottom, nMaxBottom);
// var oNextInfo = {
// "top": nTop,
// "left": nLeft,
// "width": nRight - nLeft,
// "height": nBottom - nTop
// };
// welSelectBox.animate(oNextInfo, 200);
// return oNextInfo;
// }
// _parseCoordinatesToXY(oPosition) {
// var oPadding = this._oSCManager.getPadding();
// var bubbleSize = this._oSCManager.getBubbleSize();
// return {
// "fromX": this._oSCManager.parseMouseXToXData(oPosition.left - oPadding.left - bubbleSize),
// "toX": this._oSCManager.parseMouseXToXData(oPosition.left + oPosition.width - oPadding.left - bubbleSize),
// "fromY": this._oSCManager.parseMouseYToYData(this._oSCManager.getHeight() - (oPadding.bottom + bubbleSize) - (oPosition.top + oPosition.height)),
// "toY": this._oSCManager.parseMouseYToYData(this._oSCManager.getHeight() - (oPadding.bottom + bubbleSize) - oPosition.top)
// };
// }
} | the_stack |
import { GraphQLID, GraphQLInputType, GraphQLList, GraphQLNonNull } from 'graphql';
import { ZonedDateTime } from 'js-joda';
import { CalcMutationsOperator, Field } from '../../model';
import {
BinaryOperationQueryNode,
BinaryOperator,
LiteralQueryNode,
MergeObjectsQueryNode,
ObjectQueryNode,
QueryNode,
SetFieldQueryNode,
UnaryOperationQueryNode,
UnaryOperator
} from '../../query-tree';
import {
getAddChildEntitiesFieldName,
getRemoveChildEntitiesFieldName,
getReplaceChildEntitiesFieldName,
getUpdateChildEntitiesFieldName
} from '../../schema/names';
import { GraphQLOffsetDateTime, serializeForStorage } from '../../schema/scalars/offset-date-time';
import { AnyValue, PlainObject } from '../../utils/utils';
import { CreateChildEntityInputType, CreateObjectInputType } from '../create-input-types';
import { createFieldNode } from '../field-nodes';
import { FieldContext } from '../query-node-object-type';
import { TypedInputFieldBase, TypedInputObjectType } from '../typed-input-object-type';
import { UpdateChildEntityInputType, UpdateEntityExtensionInputType, UpdateObjectInputType } from './input-types';
export interface UpdateInputFieldContext extends FieldContext {
currentEntityNode: QueryNode;
}
export interface UpdateInputField extends TypedInputFieldBase<UpdateInputField> {
readonly field: Field;
getProperties(value: AnyValue, context: UpdateInputFieldContext): ReadonlyArray<SetFieldQueryNode>;
collectAffectedFields(value: AnyValue, fields: Set<Field>, context: FieldContext): void;
appliesToMissingFields(): boolean;
}
export class DummyUpdateInputField implements UpdateInputField {
readonly deprecationReason: string | undefined;
constructor(
readonly field: Field,
readonly name: string,
readonly inputType: GraphQLInputType | TypedInputObjectType<UpdateInputField>,
opts: {
readonly deprecationReason?: string;
} = {}
) {
this.deprecationReason = opts.deprecationReason;
}
appliesToMissingFields(): boolean {
return false;
}
collectAffectedFields(value: AnyValue, fields: Set<Field>, context: FieldContext): void {}
getProperties(value: AnyValue, context: UpdateInputFieldContext): ReadonlyArray<SetFieldQueryNode> {
return [];
}
}
export class UpdateFilterInputField implements UpdateInputField {
readonly name: string;
readonly description: string;
constructor(public readonly field: Field, public readonly inputType: GraphQLInputType) {
this.name = this.field.name;
this.description = `The \`${this.field.name}\` of the \`${field.declaringType.name}\` to be updated (does not change the \`${this.field.name}\`).`;
}
appliesToMissingFields() {
return false;
}
getProperties(context: FieldContext) {
return [];
}
collectAffectedFields() {
// this field is not updated, so don't put it in here - it will occur as regular read access, though.
return [];
}
}
export class BasicUpdateInputField implements UpdateInputField {
constructor(
public readonly field: Field,
public readonly inputType: GraphQLInputType | UpdateObjectInputType,
public readonly name = field.name,
public readonly description = field.description,
public readonly deprecationReason?: string
) {}
getProperties(value: AnyValue, context: FieldContext): ReadonlyArray<SetFieldQueryNode> {
value = this.coerceValue(value, context);
return [new SetFieldQueryNode(this.field, new LiteralQueryNode(value))];
}
protected coerceValue(value: AnyValue, context: FieldContext): AnyValue {
if (
this.field.type.isScalarType &&
this.field.type.graphQLScalarType === GraphQLOffsetDateTime &&
value instanceof ZonedDateTime
) {
return serializeForStorage(value);
}
return value;
}
collectAffectedFields(value: AnyValue, fields: Set<Field>, context: FieldContext) {
fields.add(this.field);
}
appliesToMissingFields() {
return false;
}
}
export class BasicListUpdateInputField extends BasicUpdateInputField {
protected coerceValue(value: AnyValue, context: FieldContext): AnyValue {
// null is not a valid list value - if the user specified it, coerce it to [] to not have a mix of [] and
// null in the database
let listValue = Array.isArray(value) ? value : [];
return listValue.map(itemValue => super.coerceValue(itemValue, context));
}
}
export class CalcMutationInputField extends BasicUpdateInputField {
constructor(
field: Field,
inputType: GraphQLInputType,
public readonly operator: CalcMutationsOperator,
private readonly prefix: string
) {
super(field, inputType, prefix + field.name);
}
getProperties(value: AnyValue, context: UpdateInputFieldContext): ReadonlyArray<SetFieldQueryNode> {
const currentValueNode = createFieldNode(this.field, context.currentEntityNode);
value = this.coerceValue(value, context);
return [new SetFieldQueryNode(this.field, this.getValueNode(currentValueNode, new LiteralQueryNode(value)))];
}
private getValueNode(currentNode: QueryNode, operandNode: QueryNode): QueryNode {
const rawValue = new BinaryOperationQueryNode(currentNode, BinaryOperator[this.operator], operandNode);
if (this.field.type.isScalarType && this.field.type.fixedPointDecimalInfo) {
const factor = new LiteralQueryNode(10 ** this.field.type.fixedPointDecimalInfo.digits);
return new BinaryOperationQueryNode(
new UnaryOperationQueryNode(
new BinaryOperationQueryNode(rawValue, BinaryOperator.MULTIPLY, factor),
UnaryOperator.ROUND
),
BinaryOperator.DIVIDE,
factor
);
}
return rawValue;
}
}
export class UpdateValueObjectInputField extends BasicUpdateInputField {
constructor(field: Field, public readonly objectInputType: CreateObjectInputType) {
super(field, objectInputType.getInputType());
}
protected coerceValue(value: AnyValue, context: FieldContext): AnyValue {
value = super.coerceValue(value, context);
if (value == undefined) {
return value;
}
return this.objectInputType.prepareValue(value as PlainObject, context);
}
collectAffectedFields(value: AnyValue, fields: Set<Field>, context: FieldContext) {
super.collectAffectedFields(value, fields, context);
if (value == undefined) {
return;
}
this.objectInputType.collectAffectedFields(value as PlainObject, fields, context);
}
}
export class UpdateValueObjectListInputField extends BasicUpdateInputField {
constructor(field: Field, public readonly objectInputType: CreateObjectInputType) {
super(field, new GraphQLList(new GraphQLNonNull(objectInputType.getInputType())));
}
protected coerceValue(value: AnyValue, context: FieldContext): AnyValue {
value = super.coerceValue(value, context);
if (value === null) {
// null is not a valid list value - if the user specified it, coerce it to [] to not have a mix of [] and
// null in the database
return [];
}
if (value === undefined) {
return undefined;
}
if (!Array.isArray(value)) {
throw new Error(`Expected value for "${this.name}" to be an array, but is "${typeof value}"`);
}
return value.map(value => this.objectInputType.prepareValue(value, context));
}
collectAffectedFields(value: AnyValue, fields: Set<Field>, context: FieldContext) {
super.collectAffectedFields(value, fields, context);
if (value == undefined) {
return;
}
if (!Array.isArray(value)) {
throw new Error(`Expected value for "${this.name}" to be an array, but is "${typeof value}"`);
}
value.forEach(value => this.objectInputType.collectAffectedFields(value, fields, context));
}
}
export class UpdateEntityExtensionInputField implements UpdateInputField {
readonly name: string;
readonly description: string | undefined;
readonly inputType: GraphQLInputType;
constructor(public readonly field: Field, public readonly objectInputType: UpdateEntityExtensionInputType) {
this.name = field.name;
this.description =
(field.description ? field.description + '\n\n' : '') +
"This field is an entity extension and thus is never 'null' - passing 'null' here does not change the field value.";
this.inputType = objectInputType.getInputType();
}
getProperties(value: AnyValue, context: UpdateInputFieldContext) {
// setting to null is the same as setting to {} - does not change anything (entity extensions can't be null)
if (value == null || Object.keys(value as object).length === 0) {
return [];
}
return [new SetFieldQueryNode(this.field, this.getValueNode(value as PlainObject, context))];
}
private getValueNode(value: PlainObject, context: UpdateInputFieldContext) {
// this function wraps the field in a conditional node to fall back to {} on null values
// it also unwraps the given node if it is a conditional node because (null).field == null
const currentValueNode = createFieldNode(this.field, context.currentEntityNode);
return new MergeObjectsQueryNode([
currentValueNode,
new ObjectQueryNode(
this.objectInputType.getProperties(value, { ...context, currentEntityNode: currentValueNode })
)
]);
}
appliesToMissingFields() {
return false;
}
collectAffectedFields(value: AnyValue, fields: Set<Field>, context: UpdateInputFieldContext) {
fields.add(this.field);
if (value != undefined) {
this.objectInputType.collectAffectedFields(value as PlainObject, fields, context);
}
}
}
export abstract class AbstractChildEntityInputField implements UpdateInputField {
readonly description: string;
protected constructor(public readonly field: Field, public readonly name: string, description: string) {
this.description = description + (this.field.description ? '\n\n' + this.field.description : '');
}
abstract readonly inputType: GraphQLInputType;
appliesToMissingFields() {
return false;
}
getProperties(context: FieldContext) {
// the fields can't be set like this because multiple input fields affect the same child entity list
// instead, this property is computed in UpdateObjectInputType.getChildEntityProperties().
return [];
}
collectAffectedFields(value: AnyValue, fields: Set<Field>, context: FieldContext) {
fields.add(this.field);
}
}
export class ReplaceChildEntitiesInputField extends AbstractChildEntityInputField {
public readonly inputType: GraphQLInputType;
constructor(field: Field, public readonly createInputType: CreateChildEntityInputType) {
super(
field,
getReplaceChildEntitiesFieldName(field.name),
`Deletes all \`${field.type.pluralName}\` objects in list of \`${field.name}\` and replaces it with the specified objects.\n\nCannot be combined with the add/update/delete fields for the same child entity list.`
);
this.inputType = new GraphQLList(new GraphQLNonNull(createInputType.getInputType()));
}
collectAffectedFields(value: AnyValue, fields: Set<Field>, context: FieldContext) {
super.collectAffectedFields(value, fields, context);
if (value != undefined) {
this.createInputType.collectAffectedFields(value as PlainObject, fields, context);
}
}
}
export class AddChildEntitiesInputField extends AbstractChildEntityInputField {
public readonly inputType: GraphQLInputType;
constructor(field: Field, public readonly createInputType: CreateChildEntityInputType) {
super(
field,
getAddChildEntitiesFieldName(field.name),
`Adds new \`${field.type.pluralName}\` to the list of \`${field.name}\``
);
this.inputType = new GraphQLList(new GraphQLNonNull(createInputType.getInputType()));
}
collectAffectedFields(value: AnyValue, fields: Set<Field>, context: FieldContext) {
super.collectAffectedFields(value, fields, context);
if (value != undefined) {
this.createInputType.collectAffectedFields(value as PlainObject, fields, context);
}
}
}
export class UpdateChildEntitiesInputField extends AbstractChildEntityInputField {
public readonly inputType: GraphQLInputType;
constructor(field: Field, public readonly updateInputType: UpdateChildEntityInputType) {
super(
field,
getUpdateChildEntitiesFieldName(field.name),
`Updates \`${field.type.pluralName}\` in the list of \`${field.name}\``
);
this.inputType = new GraphQLList(new GraphQLNonNull(updateInputType.getInputType()));
}
collectAffectedFields(value: AnyValue, fields: Set<Field>, context: FieldContext) {
super.collectAffectedFields(value, fields, context);
if (value != undefined) {
this.updateInputType.collectAffectedFields(value as PlainObject, fields, context);
}
}
}
export class RemoveChildEntitiesInputField extends AbstractChildEntityInputField {
public readonly inputType: GraphQLInputType;
constructor(field: Field) {
super(
field,
getRemoveChildEntitiesFieldName(field.name),
`Deletes \`${field.type.pluralName}\` by ids in the list of \`${field.name}\``
);
this.inputType = new GraphQLList(new GraphQLNonNull(GraphQLID));
}
} | the_stack |
import { expect } from "chai";
import { Point2d, Point3d, Range3d, Vector3d } from "@itwin/core-geometry";
import {
ColorDef, ImageBuffer, ImageBufferFormat, QParams3d, QPoint3dList, RenderMaterial, RenderMode, RenderTexture, TextureMapping,
} from "@itwin/core-common";
import { RenderGraphic } from "../../../render/RenderGraphic";
import { createRenderPlanFromViewport } from "../../../render/RenderPlan";
import { TextureTransparency } from "../../../render/RenderTexture";
import { IModelApp } from "../../../IModelApp";
import { IModelConnection } from "../../../IModelConnection";
import { SpatialViewState } from "../../../SpatialViewState";
import { ScreenViewport } from "../../../Viewport";
import { Target } from "../../../render/webgl/Target";
import { Primitive } from "../../../render/webgl/Primitive";
import { RenderPass } from "../../../render/webgl/RenderFlags";
import { MeshGraphic, SurfaceGeometry } from "../../../render/webgl/Mesh";
import { MeshArgs } from "../../../render/primitives/mesh/MeshPrimitives";
import { MeshParams } from "../../../render/primitives/VertexTable";
import { createBlankConnection } from "../../createBlankConnection";
function createMesh(transparency: number, mat?: RenderMaterial | RenderTexture): RenderGraphic {
const args = new MeshArgs();
args.colors.initUniform(ColorDef.from(255, 0, 0, transparency));
if (mat instanceof RenderMaterial) {
args.material = mat;
args.texture = args.material.textureMapping?.texture;
} else {
args.texture = mat;
}
if (args.texture)
args.textureUv = [ new Point2d(0, 1), new Point2d(1, 1), new Point2d(0, 0), new Point2d(1, 0) ];
const points = [ new Point3d(0, 0, 0), new Point3d(1, 0, 0), new Point3d(0, 1, 0), new Point3d(1, 1, 0) ];
args.points = new QPoint3dList(QParams3d.fromRange(Range3d.createXYZXYZ(0, 0, 0, 1, 1, 1)));
for (const point of points)
args.points.add(point);
args.vertIndices = [0, 1, 2, 2, 1, 3];
args.isPlanar = true;
const params = MeshParams.create(args);
return IModelApp.renderSystem.createMesh(params)!;
}
describe("Surface transparency", () => {
let imodel: IModelConnection;
let viewport: ScreenViewport;
let opaqueTexture: RenderTexture;
let translucentTexture: RenderTexture;
let opaqueMaterial: RenderMaterial;
let translucentMaterial: RenderMaterial;
const viewDiv = document.createElement("div");
viewDiv.style.width = viewDiv.style.height = "100px";
document.body.appendChild(viewDiv);
before(async () => {
await IModelApp.startup();
imodel = createBlankConnection();
const opaqueImage = ImageBuffer.create(new Uint8Array([255, 255, 255]), ImageBufferFormat.Rgb, 1);
opaqueTexture = IModelApp.renderSystem.createTexture({
ownership: { iModel: imodel, key: imodel.transientIds.next },
image: { source: opaqueImage, transparency: TextureTransparency.Opaque },
})!;
expect(opaqueTexture).not.to.be.undefined;
const translucentImage = ImageBuffer.create(new Uint8Array([255, 255, 255, 127]), ImageBufferFormat.Rgba, 1);
translucentTexture = IModelApp.renderSystem.createTexture({
ownership: { iModel: imodel, key: imodel.transientIds.next },
image: { source: translucentImage, transparency: TextureTransparency.Translucent },
})!;
expect(translucentTexture).not.to.be.undefined;
opaqueMaterial = createMaterial(1);
translucentMaterial = createMaterial(0.5);
});
beforeEach(() => {
const view = SpatialViewState.createBlank(imodel, new Point3d(), new Vector3d(1, 1, 1));
view.viewFlags = view.viewFlags.withRenderMode(RenderMode.SmoothShade);
viewport = ScreenViewport.create(viewDiv, view);
});
afterEach(() => {
viewport.dispose();
});
after(async () => {
if (imodel)
await imodel.close();
await IModelApp.shutdown();
});
function createMaterial(alpha?: number, texture?: RenderTexture, textureWeight?: number): RenderMaterial {
const params = new RenderMaterial.Params();
params.alpha = alpha;
if (texture)
params.textureMapping = new TextureMapping(texture, new TextureMapping.Params({ textureWeight }));
const material = IModelApp.renderSystem.createMaterial(params, imodel);
expect(material).not.to.be.undefined;
return material!;
}
type SetupFunc = (view: SpatialViewState) => RenderGraphic;
function expectRenderPass(pass: RenderPass.Translucent | RenderPass.OpaquePlanar, setup: SetupFunc): void {
const graphic = setup(viewport.view as SpatialViewState);
const mesh = graphic as MeshGraphic;
expect(mesh).instanceof(MeshGraphic);
const primitive = (mesh as any)._primitives[0] as Primitive;
expect(primitive).instanceof(Primitive);
expect(primitive.cachedGeometry).instanceof(SurfaceGeometry);
const plan = createRenderPlanFromViewport(viewport);
viewport.target.changeRenderPlan(plan);
expect(primitive.getRenderPass(viewport.target as Target)).to.equal(pass);
}
function expectOpaque(setup: SetupFunc): void {
expectRenderPass(RenderPass.OpaquePlanar, setup);
}
function expectTranslucent(setup: SetupFunc): void {
expectRenderPass(RenderPass.Translucent, setup);
}
it("uses base transparency", () => {
expectOpaque(() => createMesh(0));
expectTranslucent(() => createMesh(255));
expectTranslucent(() => createMesh(127));
});
it("uses material transparency if overridden", () => {
expectOpaque(() => createMesh(0, opaqueMaterial));
expectTranslucent(() => createMesh(127, translucentMaterial));
expectOpaque(() => createMesh(127, opaqueMaterial));
expectTranslucent(() => createMesh(0, translucentMaterial));
});
it("uses base transparency if not overridden by material", () => {
const noAlphaMaterial = createMaterial();
expectOpaque(() => createMesh(0, noAlphaMaterial));
expectTranslucent(() => createMesh(127, noAlphaMaterial));
});
it("uses base transparency if materials are disabled", () => {
viewport.viewFlags = viewport.viewFlags.with("materials", false);
expectOpaque(() => createMesh(0, opaqueMaterial));
expectOpaque(() => createMesh(0, translucentMaterial));
expectTranslucent(() => createMesh(127, opaqueMaterial));
expectTranslucent(() => createMesh(127, translucentMaterial));
});
it("uses combination of material and texture transparency", () => {
const m1 = createMaterial(1, opaqueTexture);
const m2 = createMaterial(0.5, opaqueTexture);
const m3 = createMaterial(0.5, translucentTexture);
const m4 = createMaterial(1, translucentTexture);
expectOpaque(() => createMesh(0, m1));
expectOpaque(() => createMesh(127, m1));
expectTranslucent(() => createMesh(0, m2));
expectTranslucent(() => createMesh(127, m2));
expectTranslucent(() => createMesh(0, m3));
expectTranslucent(() => createMesh(127, m3));
expectTranslucent(() => createMesh(0, m4));
expectTranslucent(() => createMesh(127, m4));
});
it("ignores texture transparency if textures are disabled", () => {
viewport.viewFlags = viewport.viewFlags.with("textures", false);
const m1 = createMaterial(1, opaqueTexture);
const m2 = createMaterial(0.5, opaqueTexture);
const m3 = createMaterial(0.5, translucentTexture);
const m4 = createMaterial(1, translucentTexture);
expectOpaque(() => createMesh(0, m1));
expectOpaque(() => createMesh(127, m1));
expectTranslucent(() => createMesh(0, m2));
expectTranslucent(() => createMesh(127, m2));
expectTranslucent(() => createMesh(0, m3));
expectTranslucent(() => createMesh(127, m3));
expectOpaque(() => createMesh(0, m4));
expectOpaque(() => createMesh(127, m4));
expectOpaque(() => createMesh(0, opaqueTexture));
expectTranslucent(() => createMesh(127, opaqueTexture));
expectOpaque(() => createMesh(0, translucentTexture));
expectTranslucent(() => createMesh(127, translucentTexture));
});
it("ignores material and texture transparency if both view flags are disabled", () => {
viewport.viewFlags = viewport.viewFlags.copy({ textures: false, materials: false });
const materials = [
createMaterial(1, opaqueTexture),
createMaterial(0.5, opaqueTexture),
createMaterial(0.5, translucentTexture),
createMaterial(1, translucentTexture),
];
for (const material of materials) {
expectOpaque(() => createMesh(0, material));
expectTranslucent(() => createMesh(127, material));
}
});
it("uses combination of element and texture transparency if not overridden by material", () => {
const opaque = createMaterial(undefined, opaqueTexture);
const trans = createMaterial(undefined, translucentTexture);
expectOpaque(() => createMesh(0, opaque));
expectOpaque(() => createMesh(0, opaqueTexture));
expectTranslucent(() => createMesh(127, opaque));
expectTranslucent(() => createMesh(127, opaqueTexture));
expectTranslucent(() => createMesh(0, trans));
expectTranslucent(() => createMesh(127, trans));
expectTranslucent(() => createMesh(0, translucentTexture));
expectTranslucent(() => createMesh(127, translucentTexture));
});
it("uses combination of element and texture transparency if materials are disabled", () => {
viewport.viewFlags = viewport.viewFlags.with("materials", false);
const m1 = createMaterial(1, opaqueTexture);
const m2 = createMaterial(0.5, opaqueTexture);
const m3 = createMaterial(1, translucentTexture);
const m4 = createMaterial(0.5, translucentTexture);
expectOpaque(() => createMesh(0, m1));
expectTranslucent(() => createMesh(127, m1));
expectOpaque(() => createMesh(0, m2));
expectTranslucent(() => createMesh(127, m2));
expectTranslucent(() => createMesh(0, m3));
expectTranslucent(() => createMesh(127, m3));
expectTranslucent(() => createMesh(0, m4));
expectTranslucent(() => createMesh(127, m4));
});
it("always applies to glyph text unless reading pixels", () => {
const img = ImageBuffer.create(new Uint8Array([255, 255, 255, 127]), ImageBufferFormat.Rgba, 1);
const tx = IModelApp.renderSystem.createTexture({
type: RenderTexture.Type.Glyph,
ownership: { iModel: imodel, key: imodel.transientIds.next },
image: { source: img, transparency: TextureTransparency.Translucent },
});
expect(tx).not.to.be.undefined;
expectTranslucent(() => createMesh(0, tx));
expectTranslucent(() => createMesh(127, tx));
viewport.viewFlags = viewport.viewFlags.copy({ textures: false, materials: false });
expectTranslucent(() => createMesh(0, tx));
expectTranslucent(() => createMesh(127, tx));
viewport.viewFlags = viewport.viewFlags.withRenderMode(RenderMode.Wireframe);
expectTranslucent(() => createMesh(0, tx));
expectTranslucent(() => createMesh(127, tx));
viewport.viewFlags = viewport.viewFlags.withRenderMode(RenderMode.HiddenLine);
expectTranslucent(() => createMesh(0, tx));
expectTranslucent(() => createMesh(127, tx));
(viewport.target as any)._isReadPixelsInProgress = true;
expect((viewport.target as Target).isReadPixelsInProgress).to.be.true;
expectOpaque(() => createMesh(0, tx));
expectOpaque(() => createMesh(127, tx));
});
}); | the_stack |
import chai = require('chai')
const sinonChai = require('sinon-chai')
const expect = chai.expect
chai.use(sinonChai)
const validateConfig = require('../../lib/startup/validateConfig')
const { checkUnambiguousMandatorySpecialProducts, checkUniqueSpecialOnProducts, checkYamlSchema, checkMinimumRequiredNumberOfProducts, checkUnambiguousMandatorySpecialMemories, checkMinimumRequiredNumberOfMemories, checkUniqueSpecialOnMemories, checkSpecialMemoriesHaveNoUserAssociated, checkNecessaryExtraKeysOnSpecialProducts } = require('../../lib/startup/validateConfig')
describe('configValidation', () => {
describe('checkUnambiguousMandatorySpecialProducts', () => {
it('should accept a valid config', () => {
const products = [
{
name: 'Apple Juice',
useForChristmasSpecialChallenge: true
},
{
name: 'Orange Juice',
urlForProductTamperingChallenge: 'foobar'
},
{
name: 'Melon Juice',
fileForRetrieveBlueprintChallenge: 'foobar',
exifForBlueprintChallenge: ['OpenSCAD']
},
{
name: 'Rippertuer Special Juice',
keywordsForPastebinDataLeakChallenge: ['bla', 'blubb']
}
]
expect(checkUnambiguousMandatorySpecialProducts(products)).to.equal(true)
})
it('should fail if multiple products are configured for the same challenge', () => {
const products = [
{
name: 'Apple Juice',
useForChristmasSpecialChallenge: true
},
{
name: 'Melon Bike',
useForChristmasSpecialChallenge: true
},
{
name: 'Orange Juice',
urlForProductTamperingChallenge: 'foobar'
},
{
name: 'Melon Juice',
fileForRetrieveBlueprintChallenge: 'foobar',
exifForBlueprintChallenge: ['OpenSCAD']
}
]
expect(checkUnambiguousMandatorySpecialProducts(products)).to.equal(false)
})
it('should fail if a required challenge product is missing', () => {
const products = [
{
name: 'Apple Juice',
useForChristmasSpecialChallenge: true
},
{
name: 'Orange Juice',
urlForProductTamperingChallenge: 'foobar'
}
]
expect(checkUnambiguousMandatorySpecialProducts(products)).to.equal(false)
})
})
describe('checkNecessaryExtraKeysOnSpecialProducts', () => {
it('should accept a valid config', () => {
const products = [
{
name: 'Apple Juice',
useForChristmasSpecialChallenge: true
},
{
name: 'Orange Juice',
urlForProductTamperingChallenge: 'foobar'
},
{
name: 'Melon Juice',
fileForRetrieveBlueprintChallenge: 'foobar',
exifForBlueprintChallenge: ['OpenSCAD']
},
{
name: 'Rippertuer Special Juice',
keywordsForPastebinDataLeakChallenge: ['bla', 'blubb']
}
]
expect(checkNecessaryExtraKeysOnSpecialProducts(products)).to.equal(true)
})
it('should fail if product has no exifForBlueprintChallenge', () => {
const products = [
{
name: 'Apple Juice',
useForChristmasSpecialChallenge: true
},
{
name: 'Orange Juice',
urlForProductTamperingChallenge: 'foobar'
},
{
name: 'Melon Juice',
fileForRetrieveBlueprintChallenge: 'foobar'
},
{
name: 'Rippertuer Special Juice',
keywordsForPastebinDataLeakChallenge: ['bla', 'blubb']
}
]
expect(checkNecessaryExtraKeysOnSpecialProducts(products)).to.equal(false)
})
})
describe('checkUniqueSpecialOnProducts', () => {
it('should accept a valid config', () => {
const products = [
{
name: 'Apple Juice',
useForChristmasSpecialChallenge: true
},
{
name: 'Orange Juice',
urlForProductTamperingChallenge: 'foobar'
},
{
name: 'Melon Juice',
fileForRetrieveBlueprintChallenge: 'foobar',
exifForBlueprintChallenge: ['OpenSCAD']
},
{
name: 'Rippertuer Special Juice',
keywordsForPastebinDataLeakChallenge: ['bla', 'blubb']
}
]
expect(checkUniqueSpecialOnProducts(products)).to.equal(true)
})
it('should fail if a product is configured for multiple challenges', () => {
const products = [
{
name: 'Apple Juice',
useForChristmasSpecialChallenge: true,
urlForProductTamperingChallenge: 'foobar'
}
]
expect(checkUniqueSpecialOnProducts(products)).to.equal(false)
})
})
describe('checkMinimumRequiredNumberOfProducts', () => {
it('should accept a valid config', () => {
const products = [
{
name: 'Apple Juice'
},
{
name: 'Orange Juice'
},
{
name: 'Melon Juice'
},
{
name: 'Rippertuer Special Juice'
}
]
expect(checkMinimumRequiredNumberOfProducts(products)).to.equal(true)
})
it('should fail if less than 4 products are configured', () => {
const products = [
{
name: 'Apple Juice'
},
{
name: 'Orange Juice'
},
{
name: 'Melon Juice'
}
]
expect(checkMinimumRequiredNumberOfProducts(products)).to.equal(false)
})
})
describe('checkUnambiguousMandatorySpecialMemories', () => {
it('should accept a valid config', () => {
const memories = [
{
image: 'bla.png',
geoStalkingMetaSecurityQuestion: 42,
geoStalkingMetaSecurityAnswer: 'foobar'
},
{
image: 'blubb.png',
geoStalkingVisualSecurityQuestion: 43,
geoStalkingVisualSecurityAnswer: 'barfoo'
}
]
expect(checkUnambiguousMandatorySpecialMemories(memories)).to.equal(true)
})
it('should fail if multiple memories are configured for the same challenge', () => {
const memories = [
{
image: 'bla.png',
geoStalkingMetaSecurityQuestion: 42,
geoStalkingMetaSecurityAnswer: 'foobar'
},
{
image: 'blubb.png',
geoStalkingVisualSecurityQuestion: 43,
geoStalkingVisualSecurityAnswer: 'barfoo'
},
{
image: 'lalala.png',
geoStalkingMetaSecurityQuestion: 46,
geoStalkingMetaSecurityAnswer: 'foobarfoo'
}
]
expect(checkUnambiguousMandatorySpecialMemories(memories)).to.equal(false)
})
it('should fail if a required challenge memory is missing', () => {
const memories = [
{
image: 'bla.png',
geoStalkingMetaSecurityQuestion: 42,
geoStalkingMetaSecurityAnswer: 'foobar'
}
]
expect(checkUnambiguousMandatorySpecialMemories(memories)).to.equal(false)
})
it('should fail if memories have mixed up the required challenge keys', () => {
const memories = [
{
image: 'bla.png',
geoStalkingMetaSecurityQuestion: 42,
geoStalkingVisualSecurityAnswer: 'foobar'
},
{
image: 'blubb.png',
geoStalkingVisualSecurityQuestion: 43,
geoStalkingMetaSecurityAnswer: 'barfoo'
}
]
expect(checkUnambiguousMandatorySpecialMemories(memories)).to.equal(false)
})
})
describe('checkThatThereIsOnlyOneMemoryPerSpecial', () => {
it('should accept a valid config', () => {
const memories = [
{
image: 'bla.png',
geoStalkingMetaSecurityQuestion: 42,
geoStalkingMetaSecurityAnswer: 'foobar'
},
{
image: 'blubb.png',
geoStalkingVisualSecurityQuestion: 43,
geoStalkingVisualSecurityAnswer: 'barfoo'
}
]
expect(checkUniqueSpecialOnMemories(memories)).to.equal(true)
})
it('should fail if a memory is configured for multiple challenges', () => {
const memories = [
{
image: 'bla.png',
caption: 'Bla',
geoStalkingMetaSecurityQuestion: 42,
geoStalkingMetaSecurityAnswer: 'foobar',
geoStalkingVisualSecurityQuestion: 43,
geoStalkingVisualSecurityAnswer: 'barfoo'
}
]
expect(checkUniqueSpecialOnMemories(memories)).to.equal(false)
})
})
describe('checkSpecialMemoriesHaveNoUserAssociated', () => {
it('should accept a valid config', () => {
const memories = [
{
image: 'bla.png',
geoStalkingMetaSecurityQuestion: 42,
geoStalkingMetaSecurityAnswer: 'foobar'
},
{
image: 'blubb.png',
geoStalkingVisualSecurityQuestion: 43,
geoStalkingVisualSecurityAnswer: 'barfoo'
}
]
expect(checkSpecialMemoriesHaveNoUserAssociated(memories)).to.equal(true)
})
it('should accept a config where the default users are associated', () => {
const memories = [
{
user: 'john',
image: 'bla.png',
geoStalkingMetaSecurityQuestion: 42,
geoStalkingMetaSecurityAnswer: 'foobar'
},
{
user: 'emma',
image: 'blubb.png',
geoStalkingVisualSecurityQuestion: 43,
geoStalkingVisualSecurityAnswer: 'barfoo'
}
]
expect(checkSpecialMemoriesHaveNoUserAssociated(memories)).to.equal(true)
})
it('should fail if a memory is linked to another user', () => {
const memories = [
{
user: 'admin',
image: 'bla.png',
caption: 'Bla',
geoStalkingMetaSecurityQuestion: 42,
geoStalkingMetaSecurityAnswer: 'foobar'
}
]
expect(checkSpecialMemoriesHaveNoUserAssociated(memories)).to.equal(false)
})
})
describe('checkMinimumRequiredNumberOfMemories', () => {
it('should accept a valid config', () => {
const memories = [
{
image: 'bla.png',
user: 'admin'
},
{
image: 'blubb.png',
user: 'bjoern'
}
]
expect(checkMinimumRequiredNumberOfMemories(memories)).to.equal(true)
})
it('should fail if less than 2 memories are configured', () => {
const memories = [
{
image: 'bla.png',
user: 'admin'
}
]
expect(checkMinimumRequiredNumberOfMemories(memories)).to.equal(false)
})
})
it(`should accept the active config from config/${process.env.NODE_ENV}.yml`, () => {
expect(validateConfig({ exitOnFailure: false })).to.equal(true)
})
it('should fail if the config is invalid', () => {
expect(validateConfig({ products: [], exitOnFailure: false })).to.equal(false)
})
it('should accept a config with valid schema', () => {
const config = {
application: {
domain: 'juice-b.ox',
name: 'OWASP Juice Box',
welcomeBanner: {
showOnFirstStart: false
}
},
hackingInstructor: {
avatarImage: 'juicyEvilWasp.png'
}
}
expect(checkYamlSchema(config)).to.equal(true)
})
it('should fail for a config with schema errors', () => {
const config = {
application: {
domain: 42,
id: 'OWASP Juice Box',
welcomeBanner: {
showOnFirstStart: 'yes'
}
},
hackingInstructor: {
avatarImage: true
}
}
expect(checkYamlSchema(config)).to.equal(false)
})
}) | the_stack |
* @module CartesianGeometry
*/
import { CurveCurveApproachType, CurveLocationDetail, CurveLocationDetailPair } from "../curve/CurveLocationDetail";
import { AxisOrder, BeJSONFunctions, Geometry } from "../Geometry";
import { SmallSystem } from "../numerics/Polynomials";
import { Matrix3d } from "./Matrix3d";
import { Plane3dByOriginAndUnitNormal } from "./Plane3dByOriginAndUnitNormal";
import { Vector2d } from "./Point2dVector2d";
import { Point3d, Vector3d } from "./Point3dVector3d";
import { Range1d, Range3d } from "./Range";
import { Transform } from "./Transform";
import { XYAndZ } from "./XYZProps";
/** A Ray3d contains
* * an origin point.
* * a direction vector. The vector is NOT required to be normalized.
* * an optional weight (number).
* @public
*/
export class Ray3d implements BeJSONFunctions {
/** The ray origin */
public origin: Point3d;
/** The ray direction. This is commonly (but not always) a unit vector. */
public direction: Vector3d;
/** Numeric annotation. */
public a?: number; // optional, e.g. weight.
// constructor captures references !!!
private constructor(origin: Point3d, direction: Vector3d) {
this.origin = origin;
this.direction = direction;
this.a = undefined;
}
private static _create(x: number, y: number, z: number, u: number, v: number, w: number) {
return new Ray3d(Point3d.create(x, y, z), Vector3d.create(u, v, w));
}
/** Create a ray on the x axis. */
public static createXAxis(): Ray3d { return Ray3d._create(0, 0, 0, 1, 0, 0); }
/** Create a ray on the y axis. */
public static createYAxis(): Ray3d { return Ray3d._create(0, 0, 0, 0, 1, 0); }
/** Create a ray on the z axis. */
public static createZAxis(): Ray3d { return Ray3d._create(0, 0, 0, 0, 0, 1); }
/** Create a ray with all zeros. */
public static createZero(result?: Ray3d): Ray3d {
if (result) {
result.origin.setZero();
result.direction.setZero();
return result;
}
return new Ray3d(Point3d.createZero(), Vector3d.createZero());
}
/** Test for nearly equal rays. */
public isAlmostEqual(other: Ray3d): boolean {
return this.origin.isAlmostEqual(other.origin) && this.direction.isAlmostEqual(other.direction);
}
/** Create a ray from origin and direction. */
public static create(origin: Point3d, direction: Vector3d, result?: Ray3d): Ray3d {
if (result) {
result.set(origin, direction);
return result;
}
return new Ray3d(origin.clone(), direction.clone());
}
/**
* Given a homogeneous point and its derivative components, construct a Ray3d with cartesian coordinates and derivatives.
* @param weightedPoint `[x,y,z,w]` parts of weighted point.
* @param weightedDerivative `[x,y,z,w]` derivatives
* @param result
*/
public static createWeightedDerivative(weightedPoint: Float64Array, weightedDerivative: Float64Array, result?: Ray3d): Ray3d | undefined {
const w = weightedPoint[3];
const dw = weightedDerivative[3];
const x = weightedPoint[0];
const y = weightedPoint[1];
const z = weightedPoint[2];
const dx = weightedDerivative[0] * w - weightedPoint[0] * dw;
const dy = weightedDerivative[1] * w - weightedPoint[1] * dw;
const dz = weightedDerivative[2] * w - weightedPoint[2] * dw;
if (Geometry.isSmallMetricDistance(w))
return undefined;
const divW = 1.0 / w;
const divWW = divW * divW;
return Ray3d.createXYZUVW(x * divW, y * divW, z * divW, dx * divWW, dy * divWW, dz * divWW, result);
}
/** Create from coordinates of the origin and direction. */
public static createXYZUVW(originX: number, originY: number, originZ: number, directionX: number, directionY: number, directionZ: number, result?: Ray3d): Ray3d {
if (result) {
result.getOriginRef().set(originX, originY, originZ);
result.getDirectionRef().set(directionX, directionY, directionZ);
return result;
}
return new Ray3d(Point3d.create(originX, originY, originZ), Vector3d.create(directionX, directionY, directionZ));
}
/** Capture origin and direction in a new Ray3d. */
public static createCapture(origin: Point3d, direction: Vector3d): Ray3d {
return new Ray3d(origin, direction);
}
/** Create from (clones of) origin, direction, and numeric weight. */
public static createPointVectorNumber(origin: Point3d, direction: Vector3d, a: number, result?: Ray3d): Ray3d {
if (result) {
result.origin.setFrom(origin);
result.direction.setFrom(direction);
result.a = a;
return result;
}
result = new Ray3d(origin.clone(), direction.clone());
result.a = a;
return result;
}
/** Create from origin and target. The direction vector is the full length (non-unit) vector from origin to target. */
public static createStartEnd(origin: Point3d, target: Point3d, result?: Ray3d): Ray3d {
if (result) {
result.origin.setFrom(origin);
result.direction.setStartEnd(origin, target);
return result;
}
return new Ray3d(origin, Vector3d.createStartEnd(origin, target));
}
/** Return a reference to the ray's origin. */
public getOriginRef(): Point3d { return this.origin; }
/** Return a reference to the ray's direction vector. */
public getDirectionRef(): Vector3d { return this.direction; }
/** copy coordinates from origin and direction. */
public set(origin: Point3d, direction: Vector3d): void {
this.origin.setFrom(origin);
this.direction.setFrom(direction);
}
/** Clone the ray. */
public clone(result?: Ray3d): Ray3d {
if (result) {
result.set(this.origin.clone(), this.direction.clone());
return result;
}
return new Ray3d(this.origin.clone(), this.direction.clone());
}
/** Create a clone and return the transform of the clone. */
public cloneTransformed(transform: Transform): Ray3d {
return new Ray3d(transform.multiplyPoint3d(this.origin), transform.multiplyVector(this.direction));
}
/** Create a clone and return the inverse transform of the clone. */
public cloneInverseTransformed(transform: Transform): Ray3d | undefined {
const origin = transform.multiplyInversePoint3d(this.origin);
const direction = transform.matrix.multiplyInverseXYZAsVector3d(this.direction.x, this.direction.y, this.direction.z);
if (undefined !== origin && undefined !== direction)
return new Ray3d(origin, direction);
return undefined;
}
/** Apply a transform in place. */
public transformInPlace(transform: Transform) {
transform.multiplyPoint3d(this.origin, this.origin);
transform.multiplyVector(this.direction, this.direction);
}
/** Copy data from another ray. */
public setFrom(source: Ray3d): void { this.set(source.origin, source.direction); }
/** * fraction 0 is the ray origin.
* * fraction 1 is at the end of the direction vector when placed at the origin.
* @returns Return a point at fractional position along the ray.
*/
public fractionToPoint(fraction: number, result?: Point3d): Point3d { return this.origin.plusScaled(this.direction, fraction, result); }
/** Return the dot product of the ray's direction vector with a vector from the ray origin to the space point. */
public dotProductToPoint(spacePoint: Point3d): number { return this.direction.dotProductStartEnd(this.origin, spacePoint); }
/**
* Return the fractional coordinate (along the direction vector) of the spacePoint projected to the ray.
*/
public pointToFraction(spacePoint: Point3d): number {
return Geometry.safeDivideFraction(this.direction.dotProductStartEnd(this.origin, spacePoint), this.direction.magnitudeSquared(), 0);
}
/**
*
* Return the spacePoint projected onto the ray.
*/
public projectPointToRay(spacePoint: Point3d): Point3d {
return this.origin.plusScaled(this.direction, this.pointToFraction(spacePoint));
}
/** Return a transform for rigid axes
* at ray origin with z in ray direction. If the direction vector is zero, axes default to identity (from createHeadsUpTriad)
*/
public toRigidZFrame(): Transform | undefined {
const axes = Matrix3d.createRigidHeadsUp(this.direction, AxisOrder.ZXY);
return Transform.createOriginAndMatrix(this.origin, axes);
}
/**
* Convert {origin:[x,y,z], direction:[u,v,w]} to a Ray3d.
*/
public setFromJSON(json?: any) {
if (!json) {
this.origin.set(0, 0, 0);
this.direction.set(0, 0, 1);
return;
}
this.origin.setFromJSON(json.origin);
this.direction.setFromJSON(json.direction);
}
/**
* try to scale the direction vector to a given magnitude.
* @returns Returns false if ray direction is a zero vector.
*/
public trySetDirectionMagnitudeInPlace(magnitude: number = 1.0): boolean {
if (this.direction.tryNormalizeInPlace()) {
this.direction.scaleInPlace(magnitude);
return true;
}
this.direction.setZero();
this.a = 0.0;
return false;
}
/**
* * If parameter `a` is clearly nonzero and the direction vector can be normalized,
* * save the parameter `a` as the optional `a` member of the ray.
* * normalize the ray's direction vector
* * If parameter `a` is nearly zero,
* * Set the `a` member to zero
* * Set the ray's direction vector to zero.
* @param a area to be saved.
*/
// input a ray and "a" understood as an area.
// if a is clearly nonzero metric squared and the vector can be normalized, install those and return true.
// otherwise set ray.z to zero and zero the vector of the ray and return false.
public tryNormalizeInPlaceWithAreaWeight(a: number): boolean {
const tolerance = Geometry.smallMetricDistanceSquared;
this.a = a;
if (Math.abs(a) > tolerance && this.direction.tryNormalizeInPlace(tolerance))
return true;
this.direction.setZero();
this.a = 0.0;
return false;
}
/**
* Convert an Angle to a JSON object.
* @return {*} [origin,normal]
*/
public toJSON(): any { return { origin: this.origin.toJSON(), direction: this.direction.toJSON() }; }
/** Create a new ray from json object. See `setFromJSON` for json structure; */
public static fromJSON(json?: any) {
const result = Ray3d.createXAxis();
result.setFromJSON(json);
return result;
}
/** return distance from the ray to point in space */
public distance(spacePoint: Point3d): number {
const uu = this.direction.magnitudeSquared();
const uv = this.dotProductToPoint(spacePoint);
const aa = Geometry.inverseMetricDistanceSquared(uu);
if (aa)
return Math.sqrt(this.origin.distanceSquared(spacePoint) - uv * uv * aa);
else
return Math.sqrt(this.origin.distanceSquared(spacePoint));
}
/**
* Return the intersection of the unbounded ray with a plane.
* Stores the point of intersection in the result point given as a parameter,
* and returns the parameter along the ray where the intersection occurs.
* Returns undefined if the ray and plane are parallel or coplanar.
*/
public intersectionWithPlane(plane: Plane3dByOriginAndUnitNormal, result?: Point3d): number | undefined {
const vectorA = Vector3d.createStartEnd(plane.getOriginRef(), this.origin);
const uDotN = this.direction.dotProduct(plane.getNormalRef());
const nDotN = this.direction.magnitudeSquared();
const aDotN = vectorA.dotProduct(plane.getNormalRef());
const division = Geometry.conditionalDivideFraction(-aDotN, uDotN);
if (undefined === division)
return undefined;
const division1 = Geometry.conditionalDivideFraction(nDotN, uDotN);
if (undefined === division1)
return undefined;
if (result) {
this.origin.plusScaled(this.direction, division, result);
}
return division;
}
/**
* * Find intersection of the ray with a Range3d.
* * return the range of fractions (on the ray) which are "inside" the range.
* * Note that a range is always returned; if there is no intersection it is indicated by the test `result.sNull`
*/
public intersectionWithRange3d(range: Range3d, result?: Range1d): Range1d {
if (range.isNull)
return Range1d.createNull(result);
const interval = Range1d.createXX(-Geometry.largeCoordinateResult, Geometry.largeCoordinateResult, result);
if (interval.clipLinearMapToInterval(this.origin.x, this.direction.x, range.low.x, range.high.x)
&& interval.clipLinearMapToInterval(this.origin.y, this.direction.y, range.low.y, range.high.y)
&& interval.clipLinearMapToInterval(this.origin.z, this.direction.z, range.low.z, range.high.z))
return interval;
return interval;
}
/** Construct a vector from `ray.origin` to target point.
* * return the part of the vector that is perpendicular to `ray.direction`.
* * i.e. return the shortest vector from the ray to the point.
*/
public perpendicularPartOfVectorToTarget(targetPoint: XYAndZ, result?: Vector3d): Vector3d {
const vectorV = Vector3d.createStartEnd(this.origin, targetPoint);
const uu = this.direction.magnitudeSquared();
const uv = this.direction.dotProductStartEnd(this.origin, targetPoint);
const fraction = Geometry.safeDivideFraction(uv, uu, 0.0);
return vectorV.plusScaled(this.direction, -fraction, result);
}
/** Determine if two rays intersect, are fully overlapped, parallel but no coincident, or skew
* * Return a CurveLocationDetailPair which
* * contains fraction and point on each ray.
* * has (in the CurveLocationDetailPair structure, as member approachType) annotation indicating one of these relationships
* * CurveCurveApproachType.Intersection -- the rays have a simple intersection, at fractions indicated in detailA and detailB
* * CurveCurveApproachType.PerpendicularChord -- there is pair of where the rays have closest approach. The rays are skew in space.
* * CurveCurveApproachType.CoincidentGeometry -- the rays are the same unbounded line in space. The fractions and points are a representative single common point.
* * CurveCurveApproachType.Parallel -- the rays are parallel (and not coincident). The two points are at the minimum distance
*/
public static closestApproachRay3dRay3d(rayA: Ray3d, rayB: Ray3d): CurveLocationDetailPair {
const intersectionFractions = Vector2d.create();
let fractionA, fractionB;
let pointA, pointB;
let pairType;
if (SmallSystem.ray3dXYZUVWClosestApproachUnbounded(
rayA.origin.x, rayA.origin.y, rayA.origin.z, rayA.direction.x, rayA.direction.y, rayA.direction.z,
rayB.origin.x, rayB.origin.y, rayB.origin.z, rayB.direction.x, rayB.direction.y, rayB.direction.z, intersectionFractions)) {
fractionA = intersectionFractions.x;
fractionB = intersectionFractions.y;
pointA = rayA.fractionToPoint(fractionA);
pointB = rayB.fractionToPoint(fractionB);
pairType = pointA.isAlmostEqualMetric(pointB) ? CurveCurveApproachType.Intersection : CurveCurveApproachType.PerpendicularChord;
} else {
fractionB = 0.0;
fractionA = rayA.pointToFraction(rayB.origin);
pointA = rayA.fractionToPoint(fractionA);
pointB = rayB.fractionToPoint(fractionB);
pairType = pointA.isAlmostEqualMetric(pointB) ? CurveCurveApproachType.CoincidentGeometry : CurveCurveApproachType.ParallelGeometry;
}
const pair = CurveLocationDetailPair.createCapture(
CurveLocationDetail.createRayFractionPoint(rayA, fractionA, rayA.fractionToPoint(fractionA)),
CurveLocationDetail.createRayFractionPoint(rayB, fractionB, rayB.fractionToPoint(fractionB)));
pair.approachType = pairType;
return pair;
}
} | the_stack |
import { domInfoHelper, domTypes } from '../dom/exports'
import { resize } from '../../ObservableApi/observableApi';
import { mutationObserver as mutation } from '../../ObservableApi/mutationObserver';
//Make sure the enum is identical as C# AntDesign.Placement enum
export enum Placement {
TopLeft = 0,
TopCenter = 1,
Top = 2,
TopRight = 3,
Left = 4,
LeftTop = 5,
LeftBottom = 6,
Right = 7,
RightTop = 8,
RightBottom = 9,
BottomLeft = 10,
BottomCenter = 11,
Bottom = 12,
BottomRight = 13
}
//Make sure the enum is identical as C# AntDesign.TriggerBoundyAdjustMode enum
export enum TriggerBoundyAdjustMode {
None = 0,
InView = 1,
InScroll = 2
}
type verticalPosition = {
top?: number,
bottom?: number
}
type horizontalPosition = {
left?: number,
right?: number
}
export type overlayConstraints = {
verticalOffset: number,
horizontalOffset: number,
arrowPointAtCenter: boolean
}
export type coordinates = {
top?: number,
bottom?: number,
left?: number,
right?: number
}
export type overlayPosition = {
top?: number,
bottom?: number,
left?: number,
right?: number,
zIndex: number,
placement?: Placement,
}
export class Overlay {
private static appliedStylePositionMap: Map<Placement,
{ horizontal: "left" | "right", vertical: "top" | "bottom", class: string }> =
new Map([
[Placement.TopLeft, { horizontal: "left", vertical: "bottom", class: "topLeft" }],
[Placement.TopCenter, { horizontal: "left", vertical: "bottom", class: "topCenter" }],
[Placement.Top, { horizontal: "left", vertical: "bottom", class: "top" }],
[Placement.TopRight, { horizontal: "right", vertical: "bottom", class: "topRight" }],
[Placement.Left, { horizontal: "right", vertical: "top", class: "left" }],
[Placement.LeftTop, { horizontal: "right", vertical: "top", class: "leftTop" }],
[Placement.LeftBottom, { horizontal: "right", vertical: "bottom", class: "leftBottom" }],
[Placement.Right, { horizontal: "left", vertical: "top", class: "right" }],
[Placement.RightTop, { horizontal: "left", vertical: "top", class: "rightTop" }],
[Placement.RightBottom, { horizontal: "left", vertical: "bottom", class: "rightBottom" }],
[Placement.BottomLeft, { horizontal: "left", vertical: "top", class: "bottomLeft" }],
[Placement.BottomCenter, { horizontal: "left", vertical: "top", class: "bottomCenter" }],
[Placement.Bottom, { horizontal: "left", vertical: "top", class: "bottom" }],
[Placement.BottomRight, { horizontal: "right", vertical: "top", class: "bottomRight" }],
]);
private static reverseVerticalPlacementMap: Map<Placement, Function> =
new Map([
[Placement.TopLeft, (position: string) => Placement.BottomLeft],
[Placement.TopCenter, (position: string) => Placement.BottomCenter],
[Placement.Top, (position: string) => Placement.Bottom],
[Placement.TopRight, (position: string) => Placement.BottomRight],
[Placement.Left, (position: string) => position === "top" ? Placement.LeftBottom : Placement.LeftTop],
[Placement.LeftTop, (position: string) => Placement.LeftBottom],
[Placement.LeftBottom, (position: string) => Placement.LeftTop],
[Placement.Right, (position: string) => position === "top" ? Placement.RightBottom : Placement.RightTop],
[Placement.RightTop, (position: string) => Placement.RightBottom],
[Placement.RightBottom, (position: string) => Placement.RightTop],
[Placement.BottomLeft, (position: string) => Placement.TopLeft],
[Placement.BottomCenter, (position: string) => Placement.TopCenter],
[Placement.Bottom, (position: string) => Placement.Top],
[Placement.BottomRight, (position: string) => Placement.TopRight]
]);
private static reverseHorizontalPlacementMap: Map<Placement, Function> =
new Map([
[Placement.TopLeft, (position: string) => Placement.TopRight],
[Placement.TopCenter, (position: string) => position === "left" ? Placement.TopRight : Placement.TopLeft],
[Placement.Top, (position: string) => position === "left" ? Placement.TopRight : Placement.TopLeft],
[Placement.TopRight, (position: string) => Placement.TopLeft],
[Placement.Left, (position: string) => Placement.Right],
[Placement.LeftTop, (position: string) => Placement.RightTop],
[Placement.LeftBottom, (position: string) => Placement.RightBottom],
[Placement.Right, (position: string) => Placement.Left],
[Placement.RightTop, (position: string) => Placement.LeftBottom],
[Placement.RightBottom, (position: string) => Placement.LeftTop],
[Placement.BottomLeft, (position: string) => Placement.BottomRight],
[Placement.BottomCenter, (position: string) => position === "left" ? Placement.BottomRight : Placement.BottomLeft],
[Placement.Bottom, (position: string) => position === "left" ? Placement.BottomRight : Placement.BottomLeft],
[Placement.BottomRight, (position: string) => Placement.BottomLeft]
]);
private static arrowCenterPlacementMatch: Map<Placement, Placement> =
new Map([
[Placement.TopLeft, Placement.Top],
[Placement.TopCenter, Placement.TopCenter],
[Placement.Top, Placement.Top],
[Placement.TopRight, Placement.Top],
[Placement.Left, Placement.Left],
[Placement.LeftTop, Placement.Left],
[Placement.LeftBottom, Placement.Left],
[Placement.Right, Placement.Right],
[Placement.RightTop, Placement.Right],
[Placement.RightBottom, Placement.Right],
[Placement.BottomLeft, Placement.Bottom],
[Placement.BottomCenter, Placement.BottomCenter],
[Placement.Bottom, Placement.Bottom],
[Placement.BottomRight, Placement.Bottom]
]);
private blazorId: string;
public overlay: HTMLDivElement;
private container: HTMLElement;
private trigger: HTMLElement;
private overlayInfo: domTypes.domInfo;
private containerInfo: domTypes.domInfo;
private triggerInfo: domTypes.domInfo;
private containerBoundarySize: coordinates;
private bodyBoundarySize: coordinates;
private placement: Placement;
private recentPlacement: Placement;
private initialPlacement?: Placement;
private triggerPrefixCls: string;
private boundyAdjustMode: TriggerBoundyAdjustMode
public position: overlayPosition;
public sanitizedPosition: overlayPosition;
private overlayPreset: domTypes.position;
private verticalCalculation:
(triggerPosition: number, triggerHeight: number, container: domTypes.domInfo,
trigger: domTypes.domInfo, overlayHeight: number, constraints: overlayConstraints)
=> verticalPosition;
private horizontalCalculation:
(triggerPosition: number, triggerWidth: number, container: domTypes.domInfo,
trigger: domTypes.domInfo, overlayWidth: number, constraints: overlayConstraints)
=> horizontalPosition;
private overlayConstraints: overlayConstraints;
private duringInit = true;
private selectedVerticalPosition: "top" | "bottom";
private selectedHorizontalPosition: "left" | "right";
private calculationsToPerform: Set<"horizontal"|"vertical">;
private triggerPosition: coordinates & { absoluteTop?: number, absoluteLeft?: number, height?: number, width?: number } = { };
private isContainerBody: boolean;
private isContainerOverBody = false;
private isTriggerFixed: boolean; //refers to trigger or any of its parent having "position:fixed"
private lastScrollPosition: number; //used only if isTriggerFixed === true
private scrollbarSize: {
horizontalHeight: number,
verticalWidth: number
}
constructor(blazorId: string,
overlay: HTMLDivElement, container: HTMLElement, trigger: HTMLElement, placement: Placement,
triggerBoundyAdjustMode: TriggerBoundyAdjustMode, triggerIsWrappedInDiv: boolean, triggerPrefixCls: string,
overlayConstraints: overlayConstraints) {
this.blazorId = blazorId;
this.overlay = overlay;
//containerInfo & scrollbars have to be obtained here, because after
//removal of classes, the overlay goes to left: -9999 what causes artificial
//scrollbars and viewport dimensions are changing
this.containerInfo = domInfoHelper.getInfo(container);
this.container = container;
this.isContainerBody = container === document.body;
this.calculateScrollBarSizes()
if (!this.isContainerBody) {
this.isContainerOverBody = domInfoHelper.findAncestorWithZIndex(this.container) > 0;
}
this.overlay.style.cssText = this.overlay.style.cssText.replace("display: none;", "");
this.overlay.style.top = "0px"; //reset to prevent scrollbars if do not exist
this.removeHiddenClass()
//The trigger is actually wrapping div, which can have its own dimensions (coming from styles).
//So, first valid HTML element is picked and if there is none, the wrapping div is set as trigger.
//Triggers are always wrapped in div if the <ChildElement> instead of <Unbound> is used.
this.trigger = Overlay.getFirstValidChild(trigger, triggerIsWrappedInDiv);
this.triggerPrefixCls = triggerPrefixCls;
if (overlayConstraints.arrowPointAtCenter){
this.placement = Overlay.arrowCenterPlacementMatch.get(placement);
} else {
this.placement = placement;
}
this.initialPlacement = this.placement;
this.boundyAdjustMode = triggerBoundyAdjustMode;
this.overlayConstraints = overlayConstraints;
this.position = { zIndex: 0 };
this.selectedHorizontalPosition = Overlay.appliedStylePositionMap.get(this.placement).horizontal;
this.selectedVerticalPosition = Overlay.appliedStylePositionMap.get(this.placement).vertical;
this.verticalCalculation = Overlay.setVerticalCalculation(this.placement, this.selectedVerticalPosition);
this.horizontalCalculation = Overlay.setHorizontalCalculation(this.placement, this.selectedHorizontalPosition);
this.isTriggerFixed = domInfoHelper.isFixedPosition(this.trigger);
this.observe();
}
static getFirstValidChild(element: HTMLElement, triggerIsWrappedInDiv: boolean): HTMLElement {
if (triggerIsWrappedInDiv)
{
for(let i = 0; i < element.childNodes.length; i++) {
const childElement = element.childNodes[i] as HTMLElement;
if (childElement.innerHTML)
return childElement;
}
}
return element
}
static setVerticalCalculation(placement: Placement, position: "top" | "bottom") {
if (position === "top") {
switch (placement) {
case Placement.LeftTop:
case Placement.RightTop:
return function(triggerTop: number, triggerHeight: number, container: domTypes.domInfo, trigger: domTypes.domInfo, overlayHeight: number, constraints: overlayConstraints) {
return {
top: triggerTop,
bottom: Overlay.reversePositionValue(triggerTop, container.scrollHeight, overlayHeight)
};
};
case Placement.BottomLeft:
case Placement.BottomCenter:
case Placement.Bottom:
case Placement.BottomRight:
return function(triggerTop: number, triggerHeight: number, container: domTypes.domInfo, trigger: domTypes.domInfo, overlayHeight: number, constraints: overlayConstraints) {
const position: verticalPosition = {
top: triggerTop + triggerHeight + constraints.verticalOffset,
};
position.bottom = Overlay.reversePositionValue(position.top, container.scrollHeight, overlayHeight)
return position;
};
case Placement.Left:
case Placement.Right:
return function(triggerTop: number, triggerHeight: number, container: domTypes.domInfo, trigger: domTypes.domInfo, overlayHeight: number, constraints: overlayConstraints) {
const position: verticalPosition = {
top: triggerTop + (triggerHeight / 2) - (overlayHeight / 2)
};
position.bottom = Overlay.reversePositionValue(position.top, container.scrollHeight, overlayHeight)
return position;
};
}
}
if (position === "bottom") {
switch (placement) {
case Placement.TopLeft:
case Placement.TopCenter:
case Placement.Top:
case Placement.TopRight:
return function(triggerBottom: number, triggerHeight: number, container: domTypes.domInfo, trigger: domTypes.domInfo, overlayHeight: number, constraints: overlayConstraints) {
const position: verticalPosition = {
bottom: triggerBottom + triggerHeight + constraints.verticalOffset,
};
position.top = Overlay.reversePositionValue(position.bottom, container.scrollHeight, overlayHeight);
return position;
};
case Placement.LeftBottom:
case Placement.RightBottom:
return function(triggerBottom: number, triggerHeight: number, container: domTypes.domInfo, trigger: domTypes.domInfo, overlayHeight: number, constraints: overlayConstraints) {
const position: verticalPosition = {
bottom: triggerBottom,
top: Overlay.reversePositionValue(triggerBottom, container.scrollHeight, overlayHeight)
};
return position;
};
}
}
//fallback - should not happen, but to avoid crashing scenarios, revert to BottomLeft
console.log("Error: setVerticalCalculation did not match, nothing selected!!! Fallback.", placement, position);
return Overlay.setVerticalCalculation(Placement.BottomLeft, "top");
}
static setHorizontalCalculation(placement: Placement, position: "left" | "right") {
if (position === "left") {
switch (placement) {
case Placement.TopLeft:
case Placement.BottomLeft:
return function(triggerLeft: number, triggerWidth: number, container: domTypes.domInfo, trigger: domTypes.domInfo, overlayWidth: number, constraints: overlayConstraints) {
return {
left: triggerLeft,
right: Overlay.reversePositionValue(triggerLeft, container.scrollWidth, overlayWidth)
};
};
case Placement.Right:
case Placement.RightTop:
case Placement.RightBottom:
return function(triggerLeft: number, triggerWidth: number, container: domTypes.domInfo, trigger: domTypes.domInfo, overlayWidth: number, constraints: overlayConstraints) {
const position: horizontalPosition = {
left: triggerLeft + triggerWidth + constraints.horizontalOffset
};
position.right = Overlay.reversePositionValue(position.left, container.scrollWidth, overlayWidth)
return position;
};
case Placement.TopCenter:
case Placement.Top:
case Placement.BottomCenter:
case Placement.Bottom:
return function(triggerLeft: number, triggerWidth: number, container: domTypes.domInfo, trigger: domTypes.domInfo, overlayWidth: number, constraints: overlayConstraints) {
const position: horizontalPosition = {
left: triggerLeft + (triggerWidth / 2) - (overlayWidth / 2)
};
position.right = Overlay.reversePositionValue(position.left, container.scrollWidth, overlayWidth)
return position;
};
}
}
if (position === "right") {
switch (placement) {
case Placement.TopRight:
case Placement.BottomRight:
return function(triggerRight: number, triggerWidth: number, container: domTypes.domInfo, trigger: domTypes.domInfo, overlayWidth: number, constraints: overlayConstraints) {
let position: horizontalPosition = {
right: triggerRight,
left: Overlay.reversePositionValue(triggerRight, container.scrollWidth, overlayWidth)
};
return position;
};
case Placement.Left:
case Placement.LeftTop:
case Placement.LeftBottom:
return function(triggerRight: number, triggerWidth: number, container: domTypes.domInfo, trigger: domTypes.domInfo, overlayWidth: number, constraints: overlayConstraints) {
const position: horizontalPosition = {
right: triggerRight + triggerWidth + constraints.horizontalOffset
};
position.left = Overlay.reversePositionValue(position.right, container.scrollWidth, overlayWidth)
return position;
};
}
}
//fallback - should not happen, but to avoid crashing scenarios, revert to BottomLeft
console.log("Error: setHorizontalCalculation did not match, nothing selected!!! Fallback.", placement, position);
return Overlay.setVerticalCalculation(Placement.BottomLeft, "top");
}
/**
* Calculates reversed position. So for given left will return right,
* for top => bottom, etc.
* @param the value that needs to be reversed (left in scenario: left => right)
* @param for horizontal (left, right) container width & for vertical (top, bottom) container height
* @param for horizontal (left, right) overlay width & for vertical (top, bottom) overlay height
* @returns number
*/
static reversePositionValue(position: number, containerDimension: number, overlayDimension: number) {
return containerDimension - position - overlayDimension;
}
private removeHiddenClass() {
let end = this.overlay.className.indexOf("-hidden");
let start = this.overlay.className.lastIndexOf(" ", end)
if (start >= 0) {
let className = this.overlay.className.substr(start + 1, end);
if (className !== "") {
this.overlay.classList.remove(className);
}
}
}
private calculateScrollBarSizes() {
if (this.isContainerBody) {
this.scrollbarSize = {
horizontalHeight: window.innerHeight - document.documentElement.clientHeight,
verticalWidth: window.innerWidth - document.documentElement.clientWidth
}
}
else {
this.scrollbarSize = {
horizontalHeight: this.container.offsetHeight - this.container.clientHeight,
verticalWidth: this.container.offsetWidth - this.container.clientWidth
}
}
}
private observe() {
resize.create(`container-${this.blazorId}`, this.resizing.bind(this), false);
resize.observe(`container-${this.blazorId}`, this.container);
resize.observe(`container-${this.blazorId}`, this.trigger);
mutation.create(`trigger-${this.blazorId}`, this.mutating.bind(this), false);
mutation.observe(`trigger-${this.blazorId}`, this.trigger, {
attributes: true,
characterData: false,
childList: false,
subtree: false,
attributeOldValue: false,
characterDataOldValue: false
});
if (this.isContainerBody) {
window.addEventListener("scroll", this.onScroll.bind(this));
}
else {
this.container.addEventListener("scroll", this.onScroll.bind(this));
}
}
private onScroll() {
if (this.isTriggerFixed) {
if (this.lastScrollPosition !== window.pageYOffset) {
const diff = window.pageYOffset - this.lastScrollPosition; //positive -> down, negative -> up
this.position.top += diff;
this.position.bottom = Overlay.reversePositionValue(this.position.top, this.containerInfo.scrollHeight, this.overlayInfo.clientHeight);
if (this.selectedVerticalPosition === "top") {
this.sanitizedPosition.top = this.position.top;
this.overlay.style.top = this.sanitizedPosition.top + "px";
} else {
this.sanitizedPosition.bottom = this.getAdjustedBottom();
this.overlay.style.bottom = this.sanitizedPosition.bottom + "px";
}
this.lastScrollPosition = window.pageYOffset;
}
} else {
//Commented out code is a non-optimized calculation only if overlay stops fitting during scroll
//It misses active check for initialPlacement being different to current placement
// this.getKeyElementDimensions(false);
// this.containerBoundarySize = this.getContainerBoundarySize();
// if (!this.overlayFitsContainer("horizontal", this.position.left, this.position.right)
// || !this.overlayFitsContainer("vertical", this.position.top, this.position.bottom)) {
// this.calculatePosition(true, false, this.overlayPreset)
// }
this.calculatePosition(true, false, this.overlayPreset);
}
}
private resizing(entries, observer) {
//prevents from recalculation right on the spot during constructor run
if (this.duringInit) {
this.duringInit = false;
return;
}
this.calculatePosition(true, false, this.overlayPreset);
}
private lastStyleMutation = "";
/**
* Mutation observer will fire whenever trigger style changes. This is first and foremost
* to monitor position/size changes, so overlay can adjust itself to the new position.
* @param mutations
* @returns
*/
private mutating(mutations) {
if (this.duringInit) {
this.duringInit = false;
return;
}
if (this.lastStyleMutation !== this.trigger.style.cssText) {
this.lastStyleMutation = this.trigger.style.cssText;
this.calculatePosition(true, false, this.overlayPreset);
}
}
public dispose(): void {
resize.dispose(`container-${this.blazorId}`);
mutation.dispose(`trigger-${this.blazorId}`);
if (this.container.contains(this.overlay)) {
this.container.removeChild(this.overlay);
}
if (this.isContainerBody) {
window.removeEventListener("scroll", this.onScroll);
}
else {
this.container.removeEventListener("scroll", this.onScroll);
}
}
public calculatePosition(applyLocation: boolean, firstTime = false, overlayPreset?: domTypes.position): overlayPosition {
//check if hidden, if yes, no need to recalculate (only if not first time)
if (!firstTime && !this.overlay.offsetParent) {
return;
}
//trigger no longer visible, hide
if (!overlayPreset && !this.trigger.offsetParent) {
if (!this.overlay.classList.contains(this.triggerPrefixCls + "-hidden")) {
this.overlay.classList.add(this.triggerPrefixCls + "-hidden");
}
return this.position;
}
this.lastScrollPosition = window.pageYOffset;
this.recentPlacement = this.placement;
this.overlayPreset = overlayPreset;
this.getKeyElementDimensions(firstTime);
this.restoreInitialPlacement();
//add a very basic check - if overlay width exceeds container width, left defaults to 0
this.calculationsToPerform = this.getNominalPositions();
if (this.calculationsToPerform.size > 0) {
this.adjustToContainerBoundaries();
}
this.sanitizeCalculatedPositions();
//first positioning is applied by blazor - without it, a flicker is visible
if (applyLocation) {
this.applyLocation();
}
return this.sanitizedPosition;
}
/**
* All variants of positions are stored during calculations, but only key positions are
* returned (so only left or right and only top or bottom).
* Also, bottom & right positions need to be recalculated, due to the fact that during
* calculations:
* - bottom is represented as a value counting from top
* - right is represented as a value counting from left
* Browsers use different reference for bottom & right.
*/
private sanitizeCalculatedPositions() {
this.sanitizedPosition = { ...this.position};
this.sanitizedPosition.zIndex = domInfoHelper.getMaxZIndex();
this.sanitizedPosition.placement = this.placement;
if (this.selectedHorizontalPosition === "left") {
this.sanitizedPosition.right = null;
}
else {
this.sanitizedPosition.left = null;
this.sanitizedPosition.right = this.getAdjustedRight();
}
if (this.selectedVerticalPosition === "top") {
this.sanitizedPosition.bottom = null;
}
else {
this.sanitizedPosition.top = null;
this.sanitizedPosition.bottom = this.getAdjustedBottom();
}
}
/**
* Gets first calculations of the overlay. For each direction, there is a single scenario
* when it is immediately known that no further calculation is needed:
* - for vertical direction - when overlay's height is larger than container vertical boundaries
* - for vertical direction - when overlay's width is larger than container horizontal boundaries
* These scenarios are ignored, when boundyAdjustMode === TriggerBoundyAdjustMode.None
* @returns collection containing directions that will be calculable (not final)
*/
private getNominalPositions(): Set<"horizontal"|"vertical"> {
this.containerBoundarySize = this.getContainerBoundarySize();
const height = this.containerBoundarySize.bottom - this.containerBoundarySize.top;
const width = this.containerBoundarySize.right - this.containerBoundarySize.left;
const directionsToCalculate = new Set<"horizontal"|"vertical">();
if (this.boundyAdjustMode != TriggerBoundyAdjustMode.None && width < this.overlayInfo.clientWidth && this.isContainerBody) {
if (this.selectedHorizontalPosition === "left") {
this.position.left = 0;
} else {
this.position.right = 0;
}
} else {
const horizontalPosition = this.getHorizontalPosition();
this.position.left = horizontalPosition.left;
this.position.right = horizontalPosition.right;
directionsToCalculate.add("horizontal");
}
//same for height exceeding container height - top defaults to 0
if (this.boundyAdjustMode != TriggerBoundyAdjustMode.None && height < this.overlayInfo.clientHeight && this.isContainerBody) {
if (this.selectedVerticalPosition === "top") {
this.position.top = 0;
} else {
this.position.bottom = 0;
}
} else {
const verticalPosition = this.getVerticalPosition();
this.position.top = verticalPosition.top;
this.position.bottom = verticalPosition.bottom;
directionsToCalculate.add("vertical");
}
return directionsToCalculate;
}
/**
* Restore initial placement (and following connected variables & functions) on calculation.
* This never kicks in on first calculation. This is done because the overlay should always
* try to position itself to the initial placement. So on every recalculation initial settings
* (used during object creation) are reloaded.
*/
private restoreInitialPlacement() {
if (this.placement !== this.initialPlacement) {
this.placement = this.initialPlacement;
this.selectedHorizontalPosition = Overlay.appliedStylePositionMap.get(this.placement).horizontal;
this.selectedVerticalPosition = Overlay.appliedStylePositionMap.get(this.placement).vertical;
this.verticalCalculation = Overlay.setVerticalCalculation(this.placement, this.selectedVerticalPosition);
this.horizontalCalculation = Overlay.setHorizontalCalculation(this.placement, this.selectedHorizontalPosition);
}
}
/**
* Very basic logging, useful during debugging.
* @param extraMessage
*/
/* istanbul ignore next */
private logToConsole(extraMessage = "") {
console.log(extraMessage + " Overlay position:", this.position,
"Input",
{
blazorId: this.blazorId,
container: {
info: this.containerInfo,
parentInfo: {
clientHeight: this.container.parentElement.clientHeight,
clientWidth: this.container.parentElement.clientWidth,
scrollLeft: this.container.parentElement.scrollLeft,
scrollTop: this.container.parentElement.scrollTop
},
containerId: this.container.id,
containerBoundarySize: this.containerBoundarySize,
},
trigger: {
absoluteTop: this.triggerInfo.absoluteTop,
absoluteLeft: this.triggerInfo.absoluteLeft,
clientHeight: this.triggerInfo.clientHeight,
clientWidth: this.triggerInfo.clientWidth,
offsetHeight: this.triggerInfo.offsetHeight,
offsetWidth: this.triggerInfo.offsetWidth,
boundyAdjustMode: this.boundyAdjustMode,
//triggerType: this.triggerType,
triggerHtml: this.trigger.outerHTML,
triggerPrefixCls: this.triggerPrefixCls
},
overlay: {
clientHeight: this.overlayInfo.clientHeight,
clientWidth: this.overlayInfo.clientWidth,
offsetHeight: this.overlayInfo.offsetHeight,
offsetWidth: this.overlayInfo.offsetWidth,
class: this.overlay.className,
appliedCssPosition: {
overlay_style_top: this.overlay.style.top,
overlay_style_bottom: this.overlay.style.bottom,
overlay_style_left: this.overlay.style.left,
overlay_style_right: this.overlay.style.right
}
},
window: {
innerHeight: window.innerHeight,
innerWidth: window.innerWidth,
pageXOffset: window.pageXOffset,
pageYOffset: window.pageYOffset,
},
documentElement: {
clientHeight: document.documentElement.clientHeight,
clientWidth: document.documentElement.clientWidth,
containerIsBody: this.isContainerBody,
},
scrollbars: this.scrollbarSize,
overlayPreset: this.overlayPreset,
overlayConstraints: this.overlayConstraints,
position: this.position,
sanitizedPosition: this.sanitizedPosition,
placment: {
initialPlacement: this.initialPlacement,
recentPlacement: this.recentPlacement,
placement: this.placement,
selectedHorizontalPosition: this.selectedHorizontalPosition,
selectedVerticalPosition: this.selectedVerticalPosition
}
}
);
}
/**
* Right in the class is calculated with assumption that it is just reversed Left.
* This works well for containers that are not body. When in body, then different Right
* calculation is executed. Example:
* In a document of width of 5000px, the first Left = 0 and the first Right = 0 as well
* (and respectively, max Left = 5000 and max Right = 5000). However, browsers are behaving
* differently. Left indeed is 0 until the document width (5000). Right however is different.
* Right = 0 means the point of original viewport most Right. So, if you viewport is 1000px
* wide, Right = 0 will mean same as Left = 1000. So to reach Left = 5000, Right has to
* be equal to -4000.
* @returns number - right position
*/
private getAdjustedRight(): number {
if (this.isContainerBody) {
return this.position.right - (this.containerInfo.scrollWidth - window.innerWidth)
- this.scrollbarSize.verticalWidth;
}
return this.position.right;
}
/**
* Bottom in the class is calculated with assumption that it is just reversed Top.
* This works well for containers that are not body. When in body, then different Bottom
* calculation is executed. Example:
* In a document of height of 5000px, the first Top = 0 and the first Bottom = 0 as well
* (and respectively, max Top = 5000 and max Bottom = 5000). However, browsers are behaving
* differently. Top indeed is 0 until the document height (5000). Bottom however is different.
* Bottom = 0 means the point of original viewport most bottom. So, if you viewport is 1000px
* in height, Bottom = 0 will mean same as Top = 1000. So to reach Top = 5000, Bottom has to
* be equal to -4000.
* @returns number - bottom position
*/
private getAdjustedBottom(): number {
if (this.isContainerBody) {
return this.position.bottom - (this.containerInfo.scrollHeight - window.innerHeight)
- this.scrollbarSize.horizontalHeight;
}
return this.position.bottom;
}
private applyLocation() {
if (this.selectedHorizontalPosition === "left") {
this.overlay.style.left = this.sanitizedPosition.left + "px";
this.overlay.style.right = "unset";
} else {
this.overlay.style.right = this.sanitizedPosition.right + "px";
this.overlay.style.left = "unset";
}
if (this.selectedVerticalPosition === "top") {
this.overlay.style.top = this.sanitizedPosition.top + "px";
this.overlay.style.bottom = "unset";
} else {
this.overlay.style.bottom = this.sanitizedPosition.bottom + "px";
this.overlay.style.top = "unset";
}
this.applyPlacement();
}
private applyPlacement() {
if (this.recentPlacement !== this.placement) {
let currentPlacement: string;
const stringMach = `${this.triggerPrefixCls}-placement-`;
const start = this.overlay.className.indexOf(stringMach);
const end = this.overlay.className.indexOf(" ", start + stringMach.length);
if (start >= 0) {
currentPlacement = this.overlay.className.substr(start, end-start);
} else {
currentPlacement = Overlay.appliedStylePositionMap.get(this.initialPlacement).class;
}
let newPlacement = stringMach + Overlay.appliedStylePositionMap.get(this.placement).class;
this.overlay.classList.replace(currentPlacement, newPlacement);
}
}
/**
* Loads all important dimensions of the key elements (container of the trigger, trigger & overlay)
* into domType.domInfo structures. This could be accessed directly, except absolute positions.
* Also simplifies mocking.
* @param firstTime - if this method is called first time, then no need to load information on
* container, as it was already loaded in the constructor. This is due to the fact that first time,
* when overlay is added it has default left set to -9999 which causes the scrollbars to
* appear (which will be gone by the time overlay becomes visible). Scrollbars change
* dimensions, so often calculations were incorrect.
*/
private getKeyElementDimensions(firstTime: boolean) {
if (!firstTime) {
this.containerInfo = domInfoHelper.getInfo(this.container);
this.calculateScrollBarSizes()
}
this.triggerInfo = domInfoHelper.getInfo(this.trigger);
this.overlayInfo = domInfoHelper.getInfo(this.overlay);
}
/**
* Calculates trigger top & bottom positions and trigger height and
* uses these to return nominal position values depending on placement and
* expected attachment point (top/bottom)
* @returns verticalPosition
*/
private getVerticalPosition(): verticalPosition {
let position: verticalPosition;
//usually first offsetHeight is taken, as the measurement contains the borders
this.triggerPosition.height = this.triggerInfo.offsetHeight != 0 ? this.triggerInfo.offsetHeight
: this.triggerInfo.clientHeight;
if (this.overlayPreset) {
this.triggerPosition.top = this.triggerInfo.absoluteTop + this.overlayPreset.y;
this.triggerPosition.height = 0;
} else {
this.triggerPosition.top = this.containerInfo.scrollTop + this.triggerInfo.absoluteTop
- this.containerInfo.absoluteTop - this.containerInfo.clientTop;
}
this.triggerPosition.absoluteTop = this.triggerInfo.absoluteTop;
if (this.selectedVerticalPosition === "top"){
position = this.verticalCalculation(this.triggerPosition.top, this.triggerPosition.height, this.containerInfo,
this.triggerInfo, this.overlayInfo.clientHeight, this.overlayConstraints);
}
else { //bottom
this.triggerPosition.bottom = this.containerInfo.scrollHeight - this.triggerPosition.top - this.triggerPosition.height;
position = this.verticalCalculation(this.triggerPosition.bottom, this.triggerPosition.height, this.containerInfo,
this.triggerInfo, this.overlayInfo.clientHeight, this.overlayConstraints);
}
return position;
}
/**
* Calculates trigger left & right positions and trigger width and
* uses these to return nominal position values depending on placement and
* expected attachment point (left/right)
* @returns verticalPosition
*/
private getHorizontalPosition(): horizontalPosition {
let position: horizontalPosition;
//usually first offsetHeight is taken, as the measurement contains the borders
this.triggerPosition.width = this.triggerInfo.offsetWidth != 0 ? this.triggerInfo.offsetWidth : this.triggerInfo.clientWidth;
//let triggerLeft: number;
if (this.overlayPreset) {
this.triggerPosition.left = this.triggerInfo.absoluteLeft + this.overlayPreset.x;
this.triggerPosition.width = 0;
} else {
this.triggerPosition.left = this.containerInfo.scrollLeft + this.triggerInfo.absoluteLeft
- this.containerInfo.absoluteLeft - this.containerInfo.clientLeft;
}
this.triggerPosition.absoluteLeft = this.triggerInfo.absoluteLeft;
if (this.selectedHorizontalPosition === "left"){
position = this.horizontalCalculation(this.triggerPosition.left, this.triggerPosition.width, this.containerInfo,
this.triggerInfo, this.overlayInfo.clientWidth, this.overlayConstraints);
}
else { //right
this.triggerPosition.right = this.containerInfo.scrollWidth - this.triggerPosition.left - this.triggerPosition.width;
position = this.horizontalCalculation(this.triggerPosition.right, this.triggerPosition.width, this.containerInfo,
this.triggerInfo, this.overlayInfo.clientWidth, this.overlayConstraints);
}
return position;
}
/**
* Responsible for calling logic that handles situation when calculated overlay position
* is causing overlay to be partially rendered invisible. The goal is to adjust placement
* in such a way, so the overlay is fully visible.
* @returns void
*/
private adjustToContainerBoundaries() {
if (this.boundyAdjustMode === TriggerBoundyAdjustMode.None) {
return;
}
if (this.calculationsToPerform.has("vertical")) {
this.adjustVerticalToContainerBoundaries();
}
if (this.calculationsToPerform.has("horizontal")) {
this.adjustHorizontalToContainerBoundaries();
}
}
private setBodyBoundayrSize() {
const window = domInfoHelper.getWindow();
const scroll = domInfoHelper.getScroll();
this.bodyBoundarySize = {
top : scroll.y,
left: scroll.x,
right: window.innerWidth + scroll.x,
bottom: window.innerHeight + scroll.y
};
}
/**
* Retrieves information on current logical viewport (visible area). For
* InView this means actual viewport area (what you see in the browser - either the
* body or the scrolled to area in a container) or for InScroll this means total
* area of the container (or body).
* @returns coordinates - absolute values measuring from top = 0 and left = 0 (first
* pixels of the container)
*/
private getContainerBoundarySize(): coordinates {
if (this.boundyAdjustMode === TriggerBoundyAdjustMode.InScroll) {
if (!this.isContainerBody) {
this.setBodyBoundayrSize();
}
return {
left: 0,
right: this.containerInfo.scrollWidth,
top: 0,
bottom: this.containerInfo.scrollHeight
};
}
this.setBodyBoundayrSize();
if (this.isContainerBody) {
return this.bodyBoundarySize;
} else {
//special care is needed when evaluating viewport of the container
const parentIsInsignificant = this.container.parentElement.clientHeight === 0
|| this.container.parentElement.clientWidth === 0;
const verticalScrollBasedOnParent = !parentIsInsignificant
&& this.container.parentElement.clientHeight < this.containerInfo.clientHeight;
const horizontalScrollBasedOnParent = !parentIsInsignificant
&& this.container.parentElement.clientWidth < this.containerInfo.clientWidth;
let clientHeight: number;
let clientWidth: number;
let scrollTop: number;
let scrollLeft: number;
if (verticalScrollBasedOnParent) {
clientHeight = this.container.parentElement.clientHeight;
scrollTop = this.container.parentElement.scrollTop;
} else {
clientHeight = this.containerInfo.clientHeight;
scrollTop = this.containerInfo.scrollTop;
}
if (horizontalScrollBasedOnParent) {
clientWidth = this.container.parentElement.clientWidth;clientWidth;
scrollLeft = this.container.parentElement.scrollLeft;
} else {
clientWidth = this.containerInfo.clientWidth;
scrollLeft = this.containerInfo.scrollLeft;
}
return {
top : scrollTop,
bottom: scrollTop + clientHeight,
left: scrollLeft,
right: scrollLeft + clientWidth
};
}
}
/**
* Returns how much height of the overlay is visible in current viewport
*/
private getOverlayVisibleHeight(visibleIn: "container" | "body"): number {
let boundary: coordinates;
let top: number;
if (visibleIn === "container") {
boundary = this.containerBoundarySize;
top = this.triggerPosition.top;
} else {
boundary = this.bodyBoundarySize;
top = this.triggerPosition.absoluteTop;
}
if (this.selectedVerticalPosition === "top") {
return boundary.bottom - (top + this.triggerPosition.height);
} else {
return top - boundary.top;
}
}
/**
* Returns how much width of the overlay is visible in current viewport
*/
private getOverlayVisibleWidth(visibleIn: "container" | "body"): number {
let boundary: coordinates;
let left: number;
if (visibleIn === "container") {
boundary = this.containerBoundarySize;
left = this.triggerPosition.left;
} else {
boundary = this.bodyBoundarySize;
left = this.triggerPosition.absoluteLeft;
}
if (this.selectedHorizontalPosition === "left") {
return boundary.right - (left + this.triggerPosition.width);
} else {
return left - boundary.left;
}
}
/**
* Checks if current position actually fits in the container and if not, then reverses
* the placement. Then calculates which already calculated placements has the largest horizontal
* area of the overlay visible and picks the calculation with largest area.
*/
private adjustHorizontalToContainerBoundaries() {
if (!this.overlayFitsContainer("horizontal", this.position.left, this.position.right)) {
const positionCache: overlayPosition = { ...this.position };
const selectedPositionCache = this.selectedHorizontalPosition;
const placementCache = this.placement;
const horizontalCalculationCache = this.horizontalCalculation;
const visibleWidthBeforeAdjustment = this.getOverlayVisibleWidth("container");
let visibleWidthInBodyBeforeAdjustment: number;
if (this.isContainerOverBody) {
visibleWidthInBodyBeforeAdjustment = this.getOverlayVisibleWidth("body");
} else {
visibleWidthInBodyBeforeAdjustment = visibleWidthBeforeAdjustment
};
this.getHorizontalAdjustment();
const visibleWidthAfterAdjustment = this.getOverlayVisibleWidth("container");
let visibleWidthInBodyAfterAdjustment: number;
if (this.isContainerOverBody) {
visibleWidthInBodyAfterAdjustment = this.getOverlayVisibleWidth("body");
} else {
visibleWidthInBodyAfterAdjustment = visibleWidthAfterAdjustment
};
if (
!(visibleWidthInBodyBeforeAdjustment < visibleWidthInBodyAfterAdjustment
&& visibleWidthInBodyAfterAdjustment > 0
&& visibleWidthInBodyAfterAdjustment - visibleWidthInBodyBeforeAdjustment >= 0)
||
!(visibleWidthBeforeAdjustment < visibleWidthAfterAdjustment && visibleWidthAfterAdjustment > 0)) {
this.position = positionCache;
this.selectedHorizontalPosition = selectedPositionCache;
this.placement = placementCache;
this.horizontalCalculation = horizontalCalculationCache;
}
}
}
/**
* Checks if current position actually fits in the container and if not, then reverses
* the placement. Then calculates which already calculated placements has the largest vertical
* area of the overlay visible and picks the calculation with largest area.
*/
private adjustVerticalToContainerBoundaries() {
if (!this.overlayFitsContainer("vertical", this.position.top, this.position.bottom)) {
const positionCache: overlayPosition = { ...this.position };
const selectedPositionCache = this.selectedVerticalPosition;
const placementCache = this.placement;
const verticalCalculationCache = this.verticalCalculation;
const visibleHeightBeforeAdjustment = this.getOverlayVisibleHeight("container");
let visibleHeightInBodyBeforeAdjustment: number;
if (this.isContainerOverBody) {
visibleHeightInBodyBeforeAdjustment = this.getOverlayVisibleHeight("body");
} else {
visibleHeightInBodyBeforeAdjustment = visibleHeightBeforeAdjustment
};
this.getVerticalAdjustment();
const visibleHeightAfterAdjustment = this.getOverlayVisibleHeight("container");
let visibleHeightInBodyAfterAdjustment: number;
if (this.isContainerOverBody) {
visibleHeightInBodyAfterAdjustment = this.getOverlayVisibleHeight("body");
} else {
visibleHeightInBodyAfterAdjustment = visibleHeightAfterAdjustment
};
if (
!(visibleHeightInBodyBeforeAdjustment < visibleHeightInBodyAfterAdjustment
&& visibleHeightInBodyAfterAdjustment > 0
&& visibleHeightInBodyAfterAdjustment - visibleHeightInBodyBeforeAdjustment >= 0)
||
!(visibleHeightBeforeAdjustment < visibleHeightAfterAdjustment && visibleHeightAfterAdjustment > 0)) {
this.position = positionCache;
this.selectedVerticalPosition = selectedPositionCache;
this.placement = placementCache;
this.verticalCalculation = verticalCalculationCache;
}
}
}
private overlayFitsContainer(type: "horizontal" | "vertical", start: number, end: number): boolean {
if (type === "horizontal") {
const endExpressedAsLeft = start + this.overlayInfo.clientWidth;
return this.containerBoundarySize.left <= start
&& start <= this.containerBoundarySize.right //overlay left is between container left and right
&& this.containerBoundarySize.left <= endExpressedAsLeft
&& endExpressedAsLeft <= this.containerBoundarySize.right //and overlay right is between container left and right
}
const endExpressedAsTop = start + this.overlayInfo.clientHeight;
return this.containerBoundarySize.top <= start
&& start <= this.containerBoundarySize.bottom //overlay top is between container top and bottom
&& this.containerBoundarySize.top <= endExpressedAsTop
&& endExpressedAsTop <= this.containerBoundarySize.bottom //and overlay bottom is between container top and bottom
}
/**
* Applies basic adjustment - switches verticaly placement (top -> bottom & bottom -> top)
* and recalculates based on the newly set placement
*/
private getVerticalAdjustment() {
this.placement = Overlay.reverseVerticalPlacementMap.get(this.placement)(this.selectedVerticalPosition);
this.selectedVerticalPosition = Overlay.appliedStylePositionMap.get(this.placement).vertical;
this.verticalCalculation = Overlay.setVerticalCalculation(this.placement, this.selectedVerticalPosition);
const verticalPosition = this.getVerticalPosition();
this.position.top = verticalPosition.top;
this.position.bottom = verticalPosition.bottom;
}
/**
* Applies basic adjustment - switches horizontal placement (left -> right & right -> left)
* and recalculates based on the newly set placement
*/
private getHorizontalAdjustment() {
this.placement = Overlay.reverseHorizontalPlacementMap.get(this.placement)(this.selectedHorizontalPosition);
this.selectedHorizontalPosition = Overlay.appliedStylePositionMap.get(this.placement).horizontal;
this.horizontalCalculation = Overlay.setHorizontalCalculation(this.placement, this.selectedHorizontalPosition);
const horizontalPosition = this.getHorizontalPosition();
this.position.left = horizontalPosition.left;
this.position.right = horizontalPosition.right;
}
} | the_stack |
import { IIterator, IIterable, ArrayExt } from '@lumino/algorithm';
import {
Datastore,
IServerAdapter,
Schema,
Table,
Record
} from '@lumino/datastore';
import { IDisposable } from '@lumino/disposable';
import { ISignal } from '@lumino/signaling';
import { Message } from '@lumino/messaging';
export type DatastoreFn = ((transaction: Datastore.Transaction) => void) | null;
/**
* A patch store.
*/
export class TransactionStore {
/**
* Construct a new patch store.
*/
constructor() {
this._transactions = {};
this._order = [];
this._undoStack = [];
this._redoStack = [];
}
/**
* Returns the current undo stack
*/
get undoStack(): string[] {
return this._undoStack;
}
/**
* Returns the current redo stack
*/
get redoStack(): string[] {
return this._redoStack;
}
/**
* Add a transaction to the patch store.
*
* @param - the transaction to add to the store.
*
* @returns - whether it was successfully added.
*/
add(transaction: Datastore.Transaction): boolean {
if (
Object.prototype.hasOwnProperty.call(this._transactions, transaction.id)
) {
return false;
}
this._transactions[transaction.id] = transaction;
this._order.push(transaction.id);
const count = this._cemetery[transaction.id];
if (count === undefined) {
this._cemetery[transaction.id] = 1;
} else {
this._cemetery[transaction.id] = count + 1;
}
this._undoStack.push(transaction.id);
return true;
}
/**
* Get a transaction by id.
*
* @param transactionId - the id of the transaction.
*
* @returns - the transaction, or undefined if it can't be found.
*/
get(transactionId: string): Datastore.Transaction | undefined {
return this._transactions[transactionId];
}
/**
* Handle a transaction undo.
*
* @param transactionId - the ID of the transaction to undo.
*
* #### Notes
* This has no effect on the content of the transaction. Instead, it
* updates its undo count in the internal cemetery, determining whether
* the transaction should be applied at any given time.
*/
undo(transactionId: string): void {
const count = this._cemetery[transactionId];
if (count === undefined) {
this._cemetery[transactionId] = -1;
} else {
this._cemetery[transactionId] = count - 1;
}
ArrayExt.removeLastOf(this._undoStack, transactionId);
this._redoStack.push(transactionId);
}
/**
* Handle a transaction redo.
*
* @param transactionId - the ID of the transaction to redo.
*
* #### Notes
* This has no effect on the content of the transaction. Instead, it
* updates its undo count in the internal cemetery, determining whether
* the transaction should be applied at any given time.
*/
redo(transactionId: string): void {
const count = this._cemetery[transactionId];
if (count === undefined) {
this._cemetery[transactionId] = 0;
} else {
this._cemetery[transactionId] = count + 1;
}
ArrayExt.removeLastOf(this._redoStack, transactionId);
this._undoStack.push(transactionId);
}
/**
* Get the entire history for the transaction store.
*
* @returns - an array of transactions representing the whole history.
*/
getHistory(): Datastore.Transaction[] {
const history = [];
for (const id of this._order) {
const count = this._cemetery[id] || 0;
if (count > 0) {
history.push(this._transactions[id]);
}
}
return history;
}
get cemetery(): { [id: string]: number } {
return this._cemetery;
}
/**
* Get the most recent transaction (newly added or redone).
*
* @returns - the transaction, or undefined if there aren't any.
*/
getLastTransaction(): Datastore.Transaction | undefined {
if (this._undoStack.length === 0) {
return undefined;
}
const id = this._undoStack[this._undoStack.length - 1];
return this.get(id);
}
/**
* Get the most recent undone transaction.
*
* @returns - the transaction, or undefined if there aren't any.
*/
getLastUndo(): Datastore.Transaction | undefined {
if (this._redoStack.length === 0) {
return undefined;
}
const id = this._redoStack[this._redoStack.length - 1];
return this.get(id);
}
private _order: string[];
private _transactions: { [id: string]: Datastore.Transaction };
private _cemetery: { [id: string]: number } = {};
private _undoStack: string[];
private _redoStack: string[];
}
/**
* A class providing minimal adapter functionality for undoing and redoing.
*
* ### Notes
* Does not support broadcasting or multiple users.
*/
export class DummyAdapter implements IServerAdapter {
/**
* Construct a new adapter.
*
* @param transactionStore - the TransactionStore to use, or undefined.
*/
constructor(transactionStore?: TransactionStore) {
this._transactionStore =
transactionStore !== undefined
? transactionStore
: new TransactionStore();
}
/**
* Adds each transaction to the TransactionStore.
*
* ### Notes
* This method is supposed to broadcast each transaction to collaborators in
* a "real" adapter. Here, it just acts as a convenient way to run some code
* every time a new transaction occurs.
*/
broadcast(transaction: Datastore.Transaction): void {
this._transactionStore.add(transaction);
}
/**
* Whether the adapter has been disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* Disposes of the resources held by the adapter.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
this._transactionStore = null;
this._onRemoteTransaction = null;
this._onUndo = null;
this._onRedo = null;
this._isDisposed = true;
}
/**
* A callback for when a remote transaction is recieved by the adapter (no op).
*/
get onRemoteTransaction(): DatastoreFn {
return this._onRemoteTransaction;
}
set onRemoteTransaction(fn: DatastoreFn) {
this._onRemoteTransaction = fn;
}
/**
* A callback for when an undo request is recieved by the adapter.
*/
get onUndo(): DatastoreFn {
return this._onUndo;
}
set onUndo(fn: DatastoreFn) {
this._onUndo = fn;
}
/**
* A callback for when a redo request is recieved by the adapter.
*/
get onRedo(): DatastoreFn {
return this._onRedo;
}
set onRedo(fn: DatastoreFn) {
this._onRedo = fn;
}
/**
* Handles an undo message.
*
* @param id - the ID of the transaction to undo.
*
* ### Notes
* This function should only be called by the Datastore.
*/
async undo(id: string): Promise<void> {
if (this.onUndo) {
const transaction = this._transactionStore.get(id);
if (transaction === undefined) {
return;
}
this.onUndo(transaction);
this._transactionStore.undo(id);
}
}
/**
* Handles a redo message.
*
* @param id
*
* ### Notes
* This function should only be called by the Datastore.
*/
async redo(id: string): Promise<void> {
if (this.onRedo) {
const transaction = this._transactionStore.get(id);
if (transaction === undefined) {
return;
}
this.onRedo(transaction);
this._transactionStore.redo(id);
}
}
private _isDisposed: boolean;
private _transactionStore: TransactionStore | null;
private _onRemoteTransaction: DatastoreFn;
private _onUndo: DatastoreFn;
private _onRedo: DatastoreFn;
}
/**
* A convenient Datastore wrapper for non-collaborative work where a local
* database with undo, redo, or serialization functionality is needed.
*/
export class Litestore implements IDisposable, IIterable<Table<Schema>> {
/**
* Constructs a new Litestore.
*
* @param options - The options for creating the Litestore. The adapter will
* be overwritten by a new DummyAdapter.
*/
constructor(options: Datastore.IOptions) {
this._transactionStore = new TransactionStore();
this._adapter = new DummyAdapter(this._transactionStore);
this._dataStore = Datastore.create({ ...options, adapter: this._adapter });
}
/**
* The unique id of the store.
*/
get id(): number {
return this._dataStore.id;
}
/**
* A signal emitted when changes are made to the store.
*
* ### Notes
* The payload represents the sert of local changes that were made
* to bring the store to its current state.
*/
get changed(): ISignal<Datastore, Datastore.IChangedArgs> {
return this._dataStore.changed;
}
/**
* Whether the store has been disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* Whether a transaction is currently in progress.
*/
get inTransaction(): boolean {
return this._dataStore.inTransaction;
}
/**
* The current version of the store.
*
* ### Notes
* This version is automatically increased for each transaction to
* the store. However, it might not increase linearly
* (i.e. it might make jumps).
*/
get version(): number {
return this._dataStore.version;
}
/**
* The dummy adapter for the store.
*/
get adapter(): IServerAdapter {
return this._adapter;
}
/**
* The transaction cemetery used by the TransactionStore.
*/
get cemetery(): { [id: string]: number } {
return this._transactionStore.cemetery;
}
get transactionStore(): TransactionStore {
return this._transactionStore;
}
/**
* Get a transaction by id.
*
* @param transactionId - the id of the transaction.
*
* @returns - the transaction, or undefined if it can't be found.
*/
getTransaction(transactionId: string): Datastore.Transaction | undefined {
return this._transactionStore.get(transactionId);
}
/**
* Get the entire history for the transaction store.
*
* @returns - an array of transactions representing the whole history.
*/
getHistory(): Datastore.Transaction[] {
return this._transactionStore.getHistory();
}
/**
* Get the most recent transaction (newly added or redone).
*
* @returns - the transaction, or undefined if there aren't any.
*/
getLastTransaction(): Datastore.Transaction | undefined {
return this._transactionStore.getLastTransaction();
}
/**
* Get the most recent undone transaction.
*
* @returns - the transaction, or undefined if there aren't any.
*/
getLastUndo(): Datastore.Transaction | undefined {
return this._transactionStore.getLastUndo();
}
/**
* Begin a new transaction in the store.
*
* @returns - the id of the new transaction.
*
* @throws - an exception if a transaction is already in progress.
*
* #### Notes
* This will allow the state of the store to be mutated
* thorugh the `update` method on the individual tables.
*
* After the updates are completed, `endTransaction` should
* be called.
*/
beginTransaction(): string {
return this._dataStore.beginTransaction();
}
/**
* Completes a transaction.
*
* @returns - the ID of the last transaction, or undefined if it was empty.
*
* #### Notes
* This completes a transaction previously started with
* `beginTransaction`. If a change has occurred, the
* `changed` signal will be emitted.
*/
endTransaction(): string | undefined {
this._dataStore.endTransaction();
const transaction = this.getLastTransaction();
if (transaction === undefined) {
return undefined;
}
return transaction.id;
}
/**
* Get the table for a particular schema.
*
* @param schema - the schema of interest.
*
* @returns - the table for the specified schema.
*
* @throws - an exception if no table exists for the given schema.
*/
get<S extends Schema>(schema: S): Table<S> {
return this._dataStore.get(schema);
}
/**
* Create an iterator over all the tables of the datastore.
*
* @returns - an iterator.
*/
iter(): IIterator<Table<Schema>> {
return this._dataStore.iter();
}
/**
* Handle a message using the Datastore.
*/
processMessage(msg: Message): void {
this._dataStore.processMessage(msg);
}
/**
* Disposes of the resources held by the store.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
this._adapter.dispose();
this._dataStore.dispose();
this._transactionStore = null;
this._isDisposed = true;
}
/**
* Undo a transaction that was previoulsy applied.
*
* @param transactionId - the ID of the transaction to undo, or undefined
* to undo the last transaction.
*
* @returns - a promise which resolves when the action is complete.
*
* @throws - an exception if `undo` is called during a transaction.
*
* #### Notes
* If changes are made, the `changed` signal will be emitted before
* the promise resolves.
*/
undo(transactionId?: string): Promise<void> {
let promise: Promise<void>;
if (transactionId === undefined) {
const lastTransaction = this._transactionStore.getLastTransaction();
if (lastTransaction === undefined) {
return;
}
promise = this._dataStore.undo(lastTransaction.id);
} else {
promise = this._dataStore.undo(transactionId);
}
return promise;
}
/**
* Redo a transaction that was previously applied.
*
* @param transactionId - the ID of the transaction to redo, or undefined
* to redo the last transaction.
*
* @returns - a promise which resolves when the action is complete.
*
* @throws - an exception if `undo` is called during a transaction.
*
* #### Notes
* If changes are made, the `changed` signal will be emitted before
* the promise resolves.
*/
redo(transactionId?: string): Promise<void> {
let promise: Promise<void>;
if (transactionId === undefined) {
const lastUndo = this._transactionStore.getLastUndo();
if (lastUndo === undefined) {
return;
}
promise = this._dataStore.redo(lastUndo.id);
} else {
promise = this._dataStore.redo(transactionId);
}
return promise;
}
/**
* Serialize the state of the store to a string.
*
* @returns - the serialized state.
*/
toString(): string {
return this._dataStore.toString();
}
/**
* Get a given table by its location.
*
* @param loc - the table location ({schema}).
*
* @returns - the table.
*/
getTable<S extends Schema>(loc: Datastore.TableLocation<S>): Table<S> {
return Datastore.getTable(this._dataStore, loc);
}
/**
* Get a record by its location.
*
* @param loc - the record location ({schema, record}).
*
* @returns - the record.
*/
getRecord<S extends Schema>(
loc: Datastore.RecordLocation<S>
): Record.Value<S> | undefined {
return Datastore.getRecord(this._dataStore, loc);
}
/**
* Get a field by its location.
*
* @param loc - the field location ({schema, record, field}).
*
* @returns - the field.
*/
getField<S extends Schema, F extends keyof S['fields']>(
loc: Datastore.FieldLocation<S, F>
): S['fields'][F]['ValueType'] {
return Datastore.getField(this._dataStore, loc);
}
/**
* Update a table.
*
* @param loc - the table location ({schema}).
*
* @param update - the update to the table.
*
* #### Notes
* This does not begin a transaction, so usage of this function should be
* combined with `beginTransaction`/`endTransaction`, or `withTransaction`.
*/
updateTable<S extends Schema>(
loc: Datastore.TableLocation<S>,
update: Table.Update<S>
): void {
Datastore.updateTable(this._dataStore, loc, update);
}
/**
* Update a record.
*
* @param loc - the record location ({schema, record}).
*
* @param update - the update to the record.
*
* #### Notes
* This does not begin a transaction, so usage of this function should be
* combined with `beginTransaction`/`endTransaction`, or `withTransaction`.
*/
updateRecord<S extends Schema>(
loc: Datastore.RecordLocation<S>,
update: Record.Update<S>
): void {
Datastore.updateRecord(this._dataStore, loc, update);
}
/**
* Update a field in a table.
*
* @param loc - the field location ({schema, record, field}).
*
* @param update - the update to the field (new field value).
*
* #### Notes
* This does not begin a transaction, so usage of this function should be
* combined with `beginTransaction`/`endTransaction`, or `withTransaction`.
*/
updateField<S extends Schema, F extends keyof S['fields']>(
loc: Datastore.FieldLocation<S, F>,
update: S['fields'][F]['UpdateType']
): void {
Datastore.updateField(this._dataStore, loc, update);
}
/**
* Listen to changes in a table. Changes to other tables are ignored.
*
* @param loc - the table location ({schema}).
*
* @param slot - a callback function to invoke when the table changes.
*
* @returns - an `IDisposable` that can be disposed to remove the listener.
*/
listenTable<S extends Schema>(
loc: Datastore.TableLocation<S>,
slot: (source: Datastore, args: Table.Change<S>) => void,
thisArg?: any
): IDisposable {
return Datastore.listenTable(this._dataStore, loc, slot, thisArg);
}
/**
* Listen to changes in a record. Changes to other records are ignored.
*
* @param loc - the record location ({schema, record}).
*
* @param slot - a callback function to invoke when the record changes.
*
* @returns - `IDisposable` that can be disposed to remove the listener.
*/
listenRecord<S extends Schema>(
loc: Datastore.RecordLocation<S>,
slot: (source: Datastore, args: Record.Change<S>) => void,
thisArg?: any
): IDisposable {
return Datastore.listenRecord(this._dataStore, loc, slot, thisArg);
}
/**
* Listen to changes in a field. Changes to other fields are ignored.
*
* @param loc - the table location ({schema, record, field}).
*
* @param slot - a callback function to invoke when the field changes.
*
* @returns - an `IDisposable` that can be disposed to remove the listener.
*/
listenField<S extends Schema, F extends keyof S['fields']>(
loc: Datastore.FieldLocation<S, F>,
slot: (source: Datastore, args: S['fields'][F]['ChangeType']) => void,
thisArg?: any
): IDisposable {
return Datastore.listenField(this._dataStore, loc, slot, thisArg);
}
/**
* A helper function to wrap an update to the datastore in calls to
* `beginTransaction` and `endTransaction`.
*
* @param update: - a function that performs the update on the datastore.
* The function is called with a transaction id string, in case the
* user wishes to store the transaction ID for later use.
*
* @returns - the transaction ID.
*
* #### Notes
* If the datastore is already in a transaction, this does not attempt
* to start a new one, and returns an empty string for the transaction
* id. This allows for transactions to be composed a bit more easily.
*/
withTransaction(update: (id: string) => void): string {
return Datastore.withTransaction(this._dataStore, update);
}
private _transactionStore: TransactionStore | null;
private _adapter: DummyAdapter;
private _dataStore: Datastore;
private _isDisposed: boolean;
} | the_stack |
import { AttributeContextExpectedValue, AttributeExpectedValue } from '../../Utilities/ObjectValidator';
import { CommonTest } from './CommonTest';
// tslint:disable:max-func-body-length
// tslint:disable:variable-name
describe('Cdm.ResolutionGuidanceFilterIn', () => {
/**
* Resolution Guidance Test - FilterIn - Some
*/
it('TestFilterInSome', async (done) => {
const testName: string = 'TestFilterInSome';
{
const entityName: string = 'Employee';
const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expected_default: AttributeExpectedValue[] = [];
const expected_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly: AttributeExpectedValue[] = [];
const expected_structured: AttributeExpectedValue[] = [];
const expected_normalized_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = [];
await CommonTest.runTestWithValues(
testName,
entityName,
expectedContext_default,
expectedContext_normalized,
expectedContext_referenceOnly,
expectedContext_structured,
expectedContext_normalized_structured,
expectedContext_referenceOnly_normalized,
expectedContext_referenceOnly_structured,
expectedContext_referenceOnly_normalized_structured,
expected_default,
expected_normalized,
expected_referenceOnly,
expected_structured,
expected_normalized_structured,
expected_referenceOnly_normalized,
expected_referenceOnly_structured,
expected_referenceOnly_normalized_structured
);
}
{
const entityName: string = 'EmployeeNames';
const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expected_default: AttributeExpectedValue[] = [];
const expected_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly: AttributeExpectedValue[] = [];
const expected_structured: AttributeExpectedValue[] = [];
const expected_normalized_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = [];
await CommonTest.runTestWithValues(
testName,
entityName,
expectedContext_default,
expectedContext_normalized,
expectedContext_referenceOnly,
expectedContext_structured,
expectedContext_normalized_structured,
expectedContext_referenceOnly_normalized,
expectedContext_referenceOnly_structured,
expectedContext_referenceOnly_normalized_structured,
expected_default,
expected_normalized,
expected_referenceOnly,
expected_structured,
expected_normalized_structured,
expected_referenceOnly_normalized,
expected_referenceOnly_structured,
expected_referenceOnly_normalized_structured
);
}
done();
});
/**
* Resolution Guidance Test - FilterIn - Some With AttributeGroupRef
*/
it('TestFilterInSomeWithAttributeGroupRef', async (done) => {
const testName: string = 'TestFilterInSomeWithAttributeGroupRef';
{
const entityName: string = 'Employee';
const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expected_default: AttributeExpectedValue[] = [];
const expected_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly: AttributeExpectedValue[] = [];
const expected_structured: AttributeExpectedValue[] = [];
const expected_normalized_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = [];
await CommonTest.runTestWithValues(
testName,
entityName,
expectedContext_default,
expectedContext_normalized,
expectedContext_referenceOnly,
expectedContext_structured,
expectedContext_normalized_structured,
expectedContext_referenceOnly_normalized,
expectedContext_referenceOnly_structured,
expectedContext_referenceOnly_normalized_structured,
expected_default,
expected_normalized,
expected_referenceOnly,
expected_structured,
expected_normalized_structured,
expected_referenceOnly_normalized,
expected_referenceOnly_structured,
expected_referenceOnly_normalized_structured
);
}
{
const entityName: string = 'EmployeeNames';
const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expected_default: AttributeExpectedValue[] = [];
const expected_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly: AttributeExpectedValue[] = [];
const expected_structured: AttributeExpectedValue[] = [];
const expected_normalized_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = [];
await CommonTest.runTestWithValues(
testName,
entityName,
expectedContext_default,
expectedContext_normalized,
expectedContext_referenceOnly,
expectedContext_structured,
expectedContext_normalized_structured,
expectedContext_referenceOnly_normalized,
expectedContext_referenceOnly_structured,
expectedContext_referenceOnly_normalized_structured,
expected_default,
expected_normalized,
expected_referenceOnly,
expected_structured,
expected_normalized_structured,
expected_referenceOnly_normalized,
expected_referenceOnly_structured,
expected_referenceOnly_normalized_structured
);
}
done();
});
/**
* Resolution Guidance Test - FilterIn - All
*/
it('TestFilterInAll', async (done) => {
const testName: string = 'TestFilterInAll';
{
const entityName: string = 'Employee';
const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expected_default: AttributeExpectedValue[] = [];
const expected_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly: AttributeExpectedValue[] = [];
const expected_structured: AttributeExpectedValue[] = [];
const expected_normalized_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = [];
await CommonTest.runTestWithValues(
testName,
entityName,
expectedContext_default,
expectedContext_normalized,
expectedContext_referenceOnly,
expectedContext_structured,
expectedContext_normalized_structured,
expectedContext_referenceOnly_normalized,
expectedContext_referenceOnly_structured,
expectedContext_referenceOnly_normalized_structured,
expected_default,
expected_normalized,
expected_referenceOnly,
expected_structured,
expected_normalized_structured,
expected_referenceOnly_normalized,
expected_referenceOnly_structured,
expected_referenceOnly_normalized_structured
);
}
{
const entityName: string = 'EmployeeNames';
const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expected_default: AttributeExpectedValue[] = [];
const expected_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly: AttributeExpectedValue[] = [];
const expected_structured: AttributeExpectedValue[] = [];
const expected_normalized_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = [];
await CommonTest.runTestWithValues(
testName,
entityName,
expectedContext_default,
expectedContext_normalized,
expectedContext_referenceOnly,
expectedContext_structured,
expectedContext_normalized_structured,
expectedContext_referenceOnly_normalized,
expectedContext_referenceOnly_structured,
expectedContext_referenceOnly_normalized_structured,
expected_default,
expected_normalized,
expected_referenceOnly,
expected_structured,
expected_normalized_structured,
expected_referenceOnly_normalized,
expected_referenceOnly_structured,
expected_referenceOnly_normalized_structured
);
}
done();
});
/**
* Resolution Guidance Test - FilterIn - All With AttributeGroupRef
*/
it('TestFilterInAllWithAttributeGroupRef', async (done) => {
const testName: string = 'TestFilterInAllWithAttributeGroupRef';
{
const entityName: string = 'Employee';
const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expected_default: AttributeExpectedValue[] = [];
const expected_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly: AttributeExpectedValue[] = [];
const expected_structured: AttributeExpectedValue[] = [];
const expected_normalized_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = [];
await CommonTest.runTestWithValues(
testName,
entityName,
expectedContext_default,
expectedContext_normalized,
expectedContext_referenceOnly,
expectedContext_structured,
expectedContext_normalized_structured,
expectedContext_referenceOnly_normalized,
expectedContext_referenceOnly_structured,
expectedContext_referenceOnly_normalized_structured,
expected_default,
expected_normalized,
expected_referenceOnly,
expected_structured,
expected_normalized_structured,
expected_referenceOnly_normalized,
expected_referenceOnly_structured,
expected_referenceOnly_normalized_structured
);
}
{
const entityName: string = 'EmployeeNames';
const expectedContext_default: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue = new AttributeContextExpectedValue();
const expected_default: AttributeExpectedValue[] = [];
const expected_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly: AttributeExpectedValue[] = [];
const expected_structured: AttributeExpectedValue[] = [];
const expected_normalized_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized: AttributeExpectedValue[] = [];
const expected_referenceOnly_structured: AttributeExpectedValue[] = [];
const expected_referenceOnly_normalized_structured: AttributeExpectedValue[] = [];
await CommonTest.runTestWithValues(
testName,
entityName,
expectedContext_default,
expectedContext_normalized,
expectedContext_referenceOnly,
expectedContext_structured,
expectedContext_normalized_structured,
expectedContext_referenceOnly_normalized,
expectedContext_referenceOnly_structured,
expectedContext_referenceOnly_normalized_structured,
expected_default,
expected_normalized,
expected_referenceOnly,
expected_structured,
expected_normalized_structured,
expected_referenceOnly_normalized,
expected_referenceOnly_structured,
expected_referenceOnly_normalized_structured
);
}
done();
});
}); | the_stack |
import {
chain,
externalSchematic,
move,
noop,
Rule,
SchematicContext,
Tree,
} from '@angular-devkit/schematics';
import {
createOrUpdate,
getWorkspace,
getWorkspacePath,
} from '@nrwl/workspace';
import {
getJsonFromFile,
getAppPaths,
prerun,
getNpmScope,
getPrefix,
getGroupByName,
updateJsonFile,
updateFile,
} from '@nstudio/xplat-utils';
import {
XplatHelpers,
findNodes,
ReplaceChange,
insert,
updateTsConfig,
} from '@nstudio/xplat';
// import xplatAngular from '@nstudio/angular/src/schematics/xplat/index';
import * as ts from 'typescript';
import { join } from 'path';
import * as fs from 'fs';
export interface PackageNameMapping {
[packageName: string]: string;
}
const options: XplatHelpers.Schema = {};
const importsToUpdateMapping: PackageNameMapping = {};
const importsScssToUpdateMapping: PackageNameMapping = {};
export default function (): Rule {
return chain([
prerun(
{
framework: 'angular',
},
true
),
// update imports throughout old lib architecture and apps
updateImports(),
]);
}
export function updateImports() {
return (tree: Tree, _context: SchematicContext) => {
const npmScope = getNpmScope();
importsToUpdateMapping[`@${npmScope}/core`] = `@${npmScope}/xplat/core`;
importsToUpdateMapping[`@${npmScope}/core/*`] = `@${npmScope}/xplat/core`;
importsToUpdateMapping[
`@${npmScope}/features`
] = `@${npmScope}/xplat/features`;
importsToUpdateMapping[
`@${npmScope}/features/*`
] = `@${npmScope}/xplat/features`;
importsToUpdateMapping[`@${npmScope}/utils`] = `@${npmScope}/xplat/utils`;
importsToUpdateMapping[`@${npmScope}/utils/*`] = `@${npmScope}/xplat/utils`;
// collect which platforms were currently used
importsToUpdateMapping[
`@${npmScope}/electron`
] = `@${npmScope}/xplat/electron/core`;
importsToUpdateMapping[
`@${npmScope}/electron/core`
] = `@${npmScope}/xplat/electron/core`;
importsToUpdateMapping[
`@${npmScope}/electron/core/*`
] = `@${npmScope}/xplat/electron/core`;
importsToUpdateMapping[
`@${npmScope}/electron/features`
] = `@${npmScope}/xplat/electron/features`;
importsToUpdateMapping[
`@${npmScope}/electron/features/*`
] = `@${npmScope}/xplat/electron/features`;
importsToUpdateMapping[
`@${npmScope}/electron/utils`
] = `@${npmScope}/xplat/electron/utils`;
importsToUpdateMapping[
`@${npmScope}/electron/utils/*`
] = `@${npmScope}/xplat/electron/utils`;
importsToUpdateMapping[
`@${npmScope}/ionic`
] = `@${npmScope}/xplat/ionic/core`;
importsToUpdateMapping[
`@${npmScope}/ionic/core`
] = `@${npmScope}/xplat/ionic/core`;
importsToUpdateMapping[
`@${npmScope}/ionic/core/*`
] = `@${npmScope}/xplat/ionic/core`;
importsToUpdateMapping[
`@${npmScope}/ionic/features`
] = `@${npmScope}/xplat/ionic/features`;
importsToUpdateMapping[
`@${npmScope}/ionic/features/*`
] = `@${npmScope}/xplat/ionic/features`;
importsToUpdateMapping[
`@${npmScope}/ionic/utils`
] = `@${npmScope}/xplat/ionic/utils`;
importsToUpdateMapping[
`@${npmScope}/ionic/utils/*`
] = `@${npmScope}/xplat/ionic/utils`;
importsToUpdateMapping[
`@${npmScope}/nativescript`
] = `@${npmScope}/xplat/nativescript/core`;
importsToUpdateMapping[
`@${npmScope}/nativescript/core`
] = `@${npmScope}/xplat/nativescript/core`;
importsToUpdateMapping[
`@${npmScope}/nativescript/core/*`
] = `@${npmScope}/xplat/nativescript/core`;
importsToUpdateMapping[
`@${npmScope}/nativescript/features`
] = `@${npmScope}/xplat/nativescript/features`;
importsToUpdateMapping[
`@${npmScope}/nativescript/features/*`
] = `@${npmScope}/xplat/nativescript/features`;
importsToUpdateMapping[
`@${npmScope}/nativescript/utils`
] = `@${npmScope}/xplat/nativescript/utils`;
importsToUpdateMapping[
`@${npmScope}/nativescript/utils/*`
] = `@${npmScope}/xplat/nativescript/utils`;
importsToUpdateMapping[`@${npmScope}/web`] = `@${npmScope}/xplat/web/core`;
importsToUpdateMapping[
`@${npmScope}/web/core`
] = `@${npmScope}/xplat/web/core`;
importsToUpdateMapping[
`@${npmScope}/web/core/*`
] = `@${npmScope}/xplat/web/core`;
importsToUpdateMapping[
`@${npmScope}/web/features`
] = `@${npmScope}/xplat/web/features`;
importsToUpdateMapping[
`@${npmScope}/web/features/*`
] = `@${npmScope}/xplat/web/features`;
importsToUpdateMapping[
`@${npmScope}/web/utils`
] = `@${npmScope}/xplat/web/utils`;
importsToUpdateMapping[
`@${npmScope}/web/utils/*`
] = `@${npmScope}/xplat/web/utils`;
// console.log(
// 'updateImports',
// 'directoriesToUpdateImports:',
// directoriesToUpdateImports
// );
// scss imports
importsScssToUpdateMapping[`@${npmScope}/scss`] = `@${npmScope}/xplat-scss`;
importsScssToUpdateMapping[
`@${npmScope}/ionic-scss`
] = `@${npmScope}/xplat-ionic-scss`;
importsScssToUpdateMapping[
`@${npmScope}/web-scss`
] = `@${npmScope}/xplat-web-scss`;
importsScssToUpdateMapping[
`@${npmScope}/nativescript-scss`
] = `@${npmScope}/xplat-nativescript-scss`;
['/libs', '/apps']
.map((dir) => tree.getDir(dir))
.forEach((projectDir) => {
projectDir.visit((file) => {
// only look at .ts and .scss files
// ignore some directories in various apps
if (
!/^.*\.(ts|scss)$/.test(file) ||
file.indexOf('/node_modules/') > -1 ||
file.indexOf('/platforms/ios') > -1 ||
file.indexOf('/platforms/android') > -1
) {
return;
}
// if it doesn't contain at least 1 reference to the packages to be renamed bail out
const contents = tree.read(file).toString('utf-8');
if (/^.*\.scss$/.test(file)) {
if (
!Object.keys(importsScssToUpdateMapping).some((packageName) =>
contents.includes(packageName)
)
) {
return;
}
Object.entries(importsScssToUpdateMapping).forEach(
([packageName, newPackageName]) => {
if (contents.indexOf(packageName) > -1) {
const regEx = new RegExp(packageName, 'ig');
tree.overwrite(file, contents.replace(regEx, newPackageName));
}
}
);
} else {
if (
!Object.keys(importsToUpdateMapping).some((packageName) =>
contents.includes(packageName)
)
) {
return;
}
// console.log('updateImports', 'found old import in:', file);
const astSource = ts.createSourceFile(
file,
contents,
ts.ScriptTarget.Latest,
true
);
const changes = Object.entries(importsToUpdateMapping)
.map(([packageName, newPackageName]) => {
if (file.indexOf('apps/') > -1) {
// ensure core vs. shared is handled
if (
file.indexOf('core.module') > -1 ||
file.indexOf('app.module') > -1
) {
if (packageName.indexOf(`@${npmScope}/core`) > -1) {
newPackageName = `@${npmScope}/xplat/core`;
} else if (file.indexOf(`@${npmScope}/features`) > -1) {
newPackageName = `@${npmScope}/xplat/features`;
} else if (file.indexOf('electron') > -1) {
newPackageName = `@${npmScope}/xplat/electron/core`;
} else if (file.indexOf('ionic') > -1) {
newPackageName = `@${npmScope}/xplat/ionic/core`;
} else if (file.indexOf('nativescript') > -1) {
newPackageName = `@${npmScope}/xplat/nativescript/core`;
} else if (file.indexOf('web') > -1) {
newPackageName = `@${npmScope}/xplat/web/core`;
}
} else if (file.indexOf('.module') > -1) {
if (file.indexOf('electron') > -1) {
newPackageName = `@${npmScope}/xplat/electron/features`;
} else if (file.indexOf('ionic') > -1) {
newPackageName = `@${npmScope}/xplat/ionic/features`;
} else if (file.indexOf('nativescript') > -1) {
newPackageName = `@${npmScope}/xplat/nativescript/features`;
} else if (file.indexOf('web') > -1) {
newPackageName = `@${npmScope}/xplat/web/features`;
}
}
}
const nodes = findNodes(
astSource,
ts.SyntaxKind.ImportDeclaration
) as ts.ImportDeclaration[];
return nodes
.filter((node) => {
// remove quotes from module name
const rawImportModuleText = node.moduleSpecifier
.getText()
.slice(1)
.slice(0, -1);
if (packageName.indexOf('*') > -1) {
// replace deep imports
return (
rawImportModuleText.indexOf(
packageName.replace('*', '')
) === 0
);
} else {
// replace exact matches
return rawImportModuleText === packageName;
}
})
.map(
(node) =>
new ReplaceChange(
file,
node.moduleSpecifier.getStart(),
node.moduleSpecifier.getText(),
`'${newPackageName}'`
)
);
})
// .flatMap()/.flat() is not available? So, here's a flat poly
.reduce((acc, val) => acc.concat(val), []);
// if the reference to packageName was in fact an import statement
if (changes.length > 0) {
// update the file in the tree
insert(tree, file, changes);
}
}
});
});
return tree;
};
} | the_stack |
import {
concatUnique,
deduplicateBy,
deepKeys,
ensureSet,
flatten,
flatMap,
get,
groupBy,
isEmpty,
isEqual,
moveFromToIndex,
objectDiff,
omit,
pick,
set,
squashObject,
takeWhile,
valueOrNull,
} from '../FunctionalUtils';
interface IThing {
firstName: string;
middleName?: string;
lastName: string;
dogs: string[];
}
const person: IThing = {
dogs: ['woof'],
firstName: 'Bobo',
lastName: 'Bobic',
};
const cloneOfAPerson: IThing = {...person};
// import { deduplicateBy, deepKeys, isEmpty, objectDiff } from '../functional';
describe('functional.ts', () => {
describe('deepKeys', () => {
it('should work like Object.keys for shallow objects', () => {
const obj = {
a: 1,
b: '2',
c: false,
};
expect(Object.keys(obj)).toEqual(deepKeys(obj));
});
it('should fetch key paths in a nested object', () => {
const obj = {
a: {
b: 'ok',
c: {
d: 3,
},
},
e: false,
};
const expectedPaths = ['a.b', 'a.c.d', 'e'];
expect(deepKeys(obj).sort()).toEqual(expectedPaths.sort());
});
it('should not produce deep paths for arrays (indices)', () => {
const obj = {
a: {
b: ['1', '5'],
c: {
d: 3,
},
},
e: false,
};
const expectedPaths = ['a.b', 'a.c.d', 'e'];
expect(deepKeys(obj).sort()).toEqual(expectedPaths.sort());
});
it.only('should dive into arrays if the flag is set to do so', () => {
const obj = {
a: [1, 2, 3],
b: [
{ c: 1 },
{ d: [0]},
],
c: [],
};
const expectedPaths = ['a[0]', 'a[1]', 'a[2]', 'b[0].c', 'b[1].d[0]'];
expect(deepKeys(obj, true).sort()).toEqual(expectedPaths.sort());
});
});
describe('objectDiff', () => {
it('should produce an object describing the difference between two objects with bool-per-key', () => {
const a = {
a: 1,
b: 2,
c: 3,
d: 3,
};
const b = {
a: 1,
b: 5,
c: 3.1,
e: 3,
};
const expectedDiff = {
a: false,
b: true,
c: true,
d: true,
e: true,
};
expect(objectDiff(a, b)).toEqual(expectedDiff);
});
it('should work for deep-nested objects', () => {
const a = {
deposit: {
original: '124',
},
loan: {
first: '123',
second: '432',
},
};
const b = {
deposit: {
copy: '124',
},
loan: {
first: '125',
second: '432',
},
};
const expectedDiff = {
deposit: {
copy: true,
original: true,
},
loan: {
first: true,
second: false,
},
};
expect(objectDiff(a, b)).toEqual(expectedDiff);
});
it('should declare everything to be different when given only one object', () => {
const a = {
a: {
b: 1,
},
c: 3,
};
const expectedDiff = {
a: {
b: true,
},
c: true,
};
expect(objectDiff(a)).toEqual(expectedDiff);
});
});
describe('deduplicateBy', () => {
const items = [
{
id: 1,
name: 'One',
},
{
id: 2,
name: 'Two',
},
{
id: 1,
name: 'Ein',
},
{
id: 3,
name: 'Three',
},
{
id: 1,
name: 'Ett',
},
];
it('should find unique values in an array of objects by a property name', () => {
const deduped = deduplicateBy('id', items);
expect(deduped.length).toBe(3);
});
it('should take the first item for duplicate key values', () => {
const deduped = deduplicateBy('id', items);
expect(deduped.find((item) => item.id === 1)!.name).toBe('One');
expect(deduped.find((item) => item.id === 2)!.name).toBe('Two');
expect(deduped.find((item) => item.id === 3)!.name).toBe('Three');
});
it('should do nothing if there are no duplicates', () => {
expect(deduplicateBy('name', items)).toEqual(items);
});
});
describe('flatten', () => {
it('should take an array of arrays and make a one level flatter array out of it', () => {
expect(flatten([])).toEqual([]);
expect(flatten([[1]])).toEqual([1]);
expect(flatten([[1], [2], [3]])).toEqual([1, 2, 3]);
expect(flatten([[1], [2, 3]])).toEqual([1, 2, 3]);
});
});
describe('flatMap', () => {
it('should take an array and a function that transforms each element in an array, and return a flattened array of results', () => {
const doubler = <T>(it: T) => [it, it];
expect(flatMap([], doubler)).toEqual([]);
expect(flatMap([1], doubler)).toEqual([1, 1]);
expect(flatMap([1, 3], doubler)).toEqual([1, 1, 3, 3]);
});
});
describe('omit', () => {
it('should not modify the original', () => {
expect(person).toEqual(cloneOfAPerson);
omit(person);
expect(person).toEqual(cloneOfAPerson);
});
it('should return an object without values for the provided keys', () => {
expect(omit({...person})).toEqual(person);
expect(omit({...person}, 'dogs')).toEqual({
firstName: person.firstName,
lastName: person.lastName,
});
expect(omit({...person}, 'dogs', 'firstName')).toEqual({
lastName: person.lastName,
});
expect(omit({...person}, 'dogs', 'firstName', 'lastName')).toEqual({});
});
it('should keep the value undefined if it is not set', () => {
expect(omit({...person}, 'middleName')).toEqual(person);
});
});
describe('pick', () => {
it('should not modify the original', () => {
expect(person).toEqual(cloneOfAPerson);
pick(person);
expect(person).toEqual(cloneOfAPerson);
});
it('should return an object with only values for the provided keys', () => {
expect(pick({...person})).toEqual({});
expect(pick({...person}, 'dogs')).toEqual({
dogs: person.dogs,
});
expect(pick({...person}, 'dogs', 'firstName')).toEqual({
dogs: person.dogs,
firstName: person.firstName,
});
expect(pick({...person}, 'dogs', 'firstName', 'lastName')).toEqual(person);
});
it('should keep the value undefined if it is not set', () => {
expect(pick({...person}, 'middleName')).toEqual({});
});
});
describe('isEmpty', () => {
it('should say strings are empty if they are length 0', () => {
expect(isEmpty('')).toBe(true);
expect(isEmpty(' ')).toBe(false);
expect(isEmpty('asdadas')).toBe(false);
});
it('should say arrays are empty if they are length 0', () => {
expect(isEmpty([])).toBe(true);
expect(isEmpty([null])).toBe(false);
expect(isEmpty([1, 2])).toBe(false);
});
it('should say objects are empty if they have no non-nully keys', () => {
expect(isEmpty({})).toBe(true);
expect(isEmpty({ bla: undefined })).toBe(true);
expect(isEmpty({ bla: null })).toBe(true);
expect(isEmpty({ bla: 1 })).toBe(false);
});
it('should say everything else is empty', () => {
expect(isEmpty(null)).toBe(true);
expect(isEmpty(false)).toBe(true);
expect(isEmpty(true)).toBe(true);
expect(isEmpty(2)).toBe(true);
});
});
describe('groupBy', () => {
it('should collect objects into groups keyed by the return value for the function', () => {
const grouper = <T extends { name: string }>(it: T) => it.name;
const a = { name: 'foo' };
const b = { name: 'bar' };
const c = { name: 'baz' };
const d = { name: 'foo' };
expect(groupBy([], grouper)).toEqual({});
expect(groupBy([a], grouper)).toEqual({ foo: [a] });
expect(groupBy([a, b], grouper)).toEqual({ foo: [a], bar: [b] });
expect(groupBy([a, b, c], grouper)).toEqual({ foo: [a], bar: [b], baz: [c] });
expect(groupBy([a, b, c, d], grouper)).toEqual({ foo: [a, d], bar: [b], baz: [c] });
});
});
describe('isEqual', () => {
it('should work like === for simple values', () => {
expect(isEqual(1, 1)).toBe(true);
expect(isEqual(1, 2)).toBe(false);
expect(isEqual(null, null)).toBe(true);
expect(isEqual(null, undefined)).toBe(false);
expect(isEqual('x', 'x')).toBe(true);
expect(isEqual('x', 'y')).toBe(false);
});
it('should compare arrays by members, in order', () => {
expect(isEqual([], [])).toBe(true);
expect(isEqual([1], [])).toBe(false);
expect(isEqual([1], [1])).toBe(true);
expect(isEqual([1, 2], [1])).toBe(false);
expect(isEqual([1, 2], [1, 2])).toBe(true);
expect(isEqual([1, 2], [2, 1])).toBe(false);
});
it('should compare sets by values irrespective of order in construction', () => {
expect(isEqual(new Set(), new Set())).toBe(true);
expect(isEqual(new Set([1, 2]), new Set([2, 1]))).toBe(true);
expect(isEqual(new Set([1]), new Set())).toBe(false);
expect(isEqual(new Set([1, 2, 3]), new Set(['1', '2', '3'] as any))).toBe(false);
});
it('should deep compare objects, key order should not matter', () => {
expect(isEqual({}, {})).toBe(true);
expect(isEqual({ a: 1 }, {})).toBe(false);
expect(isEqual({ a: 1 }, { a: 1 })).toBe(true);
expect(isEqual({ a: 1 }, { a: 2 })).toBe(false);
expect(isEqual({ a: 1, b: 2 }, { a: 1 })).toBe(false);
expect(isEqual({ a: 1, b: 2 }, { b: 2, a: 1 })).toBe(true);
});
it('should work for nested stuff', () => {
expect(isEqual({
a: { b: 1 },
}, {
a: { b: 1 },
})).toBe(true);
expect(isEqual({
a: { b: 1 },
}, {
a: { b: 2 },
})).toBe(false);
expect(isEqual({
a: { b: [1] },
}, {
a: { b: [1] },
})).toBe(true);
expect(isEqual({
a: { b: [{ c: 1 }] },
}, {
a: { b: [{ c: 1 }] },
})).toBe(true);
});
it('should work for Lodash tests', () => {
// Basic equality and identity comparisons.
expect(isEqual(null, null)).toBeTruthy();
expect(!isEqual(null, void 0)).toBeTruthy();
expect(!isEqual(void 0, null)).toBeTruthy();
// String object and primitive comparisons.
expect(isEqual('Curly', 'Curly')).toBeTruthy();
expect(isEqual(new String('Curly'), 'Curly')).toBeTruthy();
expect(isEqual('Curly', new String('Curly'))).toBeTruthy();
expect(!isEqual('Curly', 'Larry')).toBeTruthy();
expect(!isEqual(new String('Curly'), new String('Larry'))).toBeTruthy();
expect(!isEqual(new String('Curly'), {toString: () => 'Curly'} as any)).toBeTruthy();
// Number object and primitive comparisons.
expect(isEqual(75, 75)).toBeTruthy();
expect(isEqual(new Number(75), new Number(75))).toBeTruthy();
expect(isEqual(75, new Number(75))).toBeTruthy();
expect(isEqual(new Number(75), 75)).toBeTruthy();
expect(!isEqual(new Number(75), new Number(63))).toBeTruthy();
expect(!isEqual(new Number(63), {valueOf: () => 63 } as any)).toBeTruthy();
// Comparisons involving `NaN`.
expect(isEqual(NaN, NaN)).toBeTruthy();
expect(isEqual(new Number(NaN), NaN)).toBeTruthy();
expect(!isEqual(61, NaN)).toBeTruthy();
expect(!isEqual(new Number(79), NaN)).toBeTruthy();
expect(!isEqual(Infinity, NaN)).toBeTruthy();
// Boolean object and primitive comparisons.
expect(isEqual(true, true)).toBeTruthy();
expect(isEqual(new Boolean(), new Boolean())).toBeTruthy();
expect(isEqual(true, new Boolean(true))).toBeTruthy();
expect(isEqual(new Boolean(true), true)).toBeTruthy();
// Common type coercions.
expect(!isEqual(new Boolean(false), true)).toBeTruthy();
expect(!isEqual('75', 75 as unknown as string)).toBeTruthy();
expect(!isEqual(new Number(63), new String(63) as unknown as number)).toBeTruthy();
expect(!isEqual(75, '75' as unknown as number)).toBeTruthy();
expect(!isEqual(0, '' as unknown as number)).toBeTruthy();
expect(!isEqual(1, true as unknown as number)).toBeTruthy();
expect(!isEqual(new Boolean(false), new Number(0) as unknown as boolean)).toBeTruthy();
expect(!isEqual(false, new String('') as unknown as boolean)).toBeTruthy();
expect(!isEqual(12564504e5, new Date(2009, 9, 25) as unknown as number)).toBeTruthy();
// Dates.
expect(!isEqual(new Date(2009, 9, 25), new Date(2009, 11, 13))).toBeTruthy();
expect(!isEqual(new Date(2009, 11, 13), {
getTime: () => 12606876e5,
} as any)).toBeTruthy();
expect(!isEqual(new Date('Curly'), new Date('Curly'))).toBeTruthy();
});
});
describe('get', () => {
it('should work like lodash get', () => {
expect(get({ a: 1 }, 'a')).toBe(1);
expect(get({ a: { b: 2 } }, 'a.b' as any)).toBe(2);
expect(get({ a: { b: 3 } }, 'a.c' as any)).toBeUndefined();
expect(get({ a: { b: 4 } }, 'a.c.f' as any)).toBeUndefined();
expect(get({ a: { b: 5 } }, 'a.c.f' as any, 3)).toBe(3);
expect(get({ a: { b: 6 } }, ['a', 'c', 'f'] as any, 3)).toBe(3);
expect(get({
a: [{ b : 7}],
}, 'a[0].b' as any)).toBe(7);
expect(get({
a: [{ b : 1}],
}, 'a[1].b' as any)).toBeUndefined();
expect(get({ a: ['a'] }, 'a[0]' as any)).toBe('a');
expect(get({
a: [{ 'b c' : 8}],
}, 'a[0][b c]' as any)).toBe(8);
expect(get({
a: [{ 'b c' : 9}],
}, ['a', '0', 'b c'] as any)).toBe(9);
});
});
describe('set', () => {
it('should work like lodash set', () => {
expect(set({}, 'a' as any, 1)).toEqual({ a: 1 });
expect(set({}, 'a.b' as any, 1)).toEqual({ a: { b: 1 } });
expect(set({}, 'a[0]' as any, 1)).toEqual({ a: [1] });
expect(set({}, ['a', '0'] as any, 1)).toEqual({ a: [1] });
expect(set({}, 'a[foo]' as any, 1)).toEqual({ a: { foo: 1 } });
expect(set({}, 'a[foo bar]' as any, 1)).toEqual({ a: { 'foo bar': 1 } });
expect(set({}, ['a', 'foo'] as any, 1)).toEqual({ a: { foo: 1 } });
expect(set({
a: [
{ b: 1 },
],
}, 'a[0].b' as any, 2)).toEqual({
a: [
{ b: 2 },
],
});
});
});
describe('valueOrNull', () => {
it('should return nullonly for null, undefined, empty objects, empty arrays and empty strings', () => {
expect(valueOrNull(null)).toBeNull();
expect(valueOrNull(undefined)).toBeNull();
expect(valueOrNull([])).toBeNull();
expect(valueOrNull({})).toBeNull();
expect(valueOrNull('')).toBeNull();
expect(valueOrNull(0)).toBe(0);
expect(valueOrNull(false)).toBe(false);
expect(valueOrNull(true)).toBe(true);
expect(valueOrNull('0')).toBe('0');
expect(valueOrNull([0])).toEqual([0]);
expect(valueOrNull({ a: 0 })).toEqual({ a: 0 });
});
});
describe('takeWhile', () => {
it('should take values as long as the predicate is satisfied', () => {
expect(takeWhile([1, 2, 3, 4], (x) => x < 10)).toEqual([1, 2, 3, 4]);
expect(takeWhile([1, 2, 10, 4], (x) => x < 10)).toEqual([1, 2]);
expect(takeWhile([1, 12, 3, 4], (x) => x > 10)).toEqual([]);
expect(takeWhile([], () => true)).toEqual([]);
});
});
describe('squashObject', () => {
it('should return undefined for null-y values', () => {
expect(squashObject(null)).toBe(undefined);
expect(squashObject(undefined)).toBe(undefined);
});
it('should return undefined for empty objects and objects with no values defined', () => {
expect(squashObject({})).toBe(undefined);
expect(squashObject({
key: null,
})).toBe(undefined);
expect(squashObject({
key: undefined,
})).toBe(undefined);
});
it('should return the object in full if it has any values', () => {
const objs = [
{
key: false,
},
{
key: false,
other: undefined,
},
];
objs.forEach((o) => {
expect(squashObject(o)).toEqual(o);
});
});
});
describe('ensureSet', () => {
it('should return a Set object if an array, object or primitive value are passed', () => {
const arr = [1, 2, 3];
const obj = { a: 1};
expect(ensureSet(arr)).toBeInstanceOf(Set);
expect(ensureSet(obj)).toBeInstanceOf(Set);
expect(ensureSet('i am a string' as any)).toBeInstanceOf(Set);
});
it('should return a filled Set object with correct values if a non-empty array is passed', () => {
const arr = [1, 2, 3];
const setObj = ensureSet(arr);
expect(setObj.has(1)).toBe(true);
expect(setObj.has(2)).toBe(true);
expect(setObj.has(3)).toBe(true);
expect(setObj.has(6)).toBe(false);
});
});
describe('concatUnique', () => {
it('should concatenate arrays of arrays', () => {
expect(concatUnique([[1, 2], [3], [4, 5]])).toEqual([1, 2, 3, 4, 5]);
expect(concatUnique([[1, 2], [], [4]])).toEqual([1, 2, 4]);
});
it('should keep only keep the first occurrence of a unique value', () => {
expect(concatUnique([[1, 2], [1, 3]])).toEqual([1, 2, 3]);
expect(concatUnique([[1, 2], [1, 3, 1]])).toEqual([1, 2, 3]);
expect(concatUnique([['a'], ['a']])).toEqual(['a']);
expect(concatUnique([[{}], [{}]])).toEqual([{}]);
});
});
describe('[Regression](https://oradian.atlassian.net/browse/IN-12151)', () => {
it('should correctly check for equality of objects', () => {
const first = [
{ id: 1, displayName: 'Male', active: true },
{ id: 2, displayName: 'Female', active: true },
];
const second = [
{ id: 1, displayName: 'Male', active: true },
{ id: 2, displayName: 'Female', active: true },
];
const expected = [
{ id: 1, displayName: 'Male', active: true },
{ id: 2, displayName: 'Female', active: true },
];
expect(concatUnique([first, second])).toEqual(expected);
});
});
describe('moveFromToIndex', () => {
const xs = [1, 2, 3, 4, 5];
it('should move an item at one index to the other, pushing others back', () => {
expect(moveFromToIndex(xs, 0, 1)).toEqual([2, 1, 3, 4, 5]);
expect(moveFromToIndex(xs, 2, 1)).toEqual([1, 3, 2, 4, 5]);
expect(moveFromToIndex(xs, 4, 1)).toEqual([1, 5, 2, 3, 4]);
});
it('should work inserting at the zeroth index', () => {
expect(moveFromToIndex(xs, 2, 0)).toEqual([3, 1, 2, 4, 5]);
});
it('should work for inserting at the last index', () => {
expect(moveFromToIndex(xs, 1, 4)).toEqual([1, 3, 4, 5, 2]);
expect(moveFromToIndex(xs, 3, 4)).toEqual([1, 2, 3, 4, 5]);
});
});
}); | the_stack |
import type {
CSMessage,
CommentCMsg,
CommentCSMsg,
LyricSMsg,
MsicRankingCMsg,
ProviderCMsg,
} from "@cloudmusic/shared";
import { ColorThemeKind, Uri, ViewColumn, commands, window } from "vscode";
import {
IPC,
MultiStepInput,
State,
pickAlbum,
pickArtist,
pickSong,
pickUser,
} from ".";
import type { ProviderSMsg, WebviewType } from "@cloudmusic/shared";
import type { WebviewView, WebviewViewProvider } from "vscode";
import { AccountManager } from "../manager";
import { NeteaseEnum } from "@cloudmusic/shared";
import type { NeteaseTypings } from "api";
import { SETTING_DIR } from "../constant";
import i18n from "../i18n";
import { resolve } from "path";
import { toDataURL } from "qrcode";
const getNonce = (): string => {
let text = "";
const possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 32; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
};
export class AccountViewProvider implements WebviewViewProvider {
private static _view?: WebviewView;
constructor(
private readonly _extUri: Uri,
private readonly _volume: number
) {}
static master(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "master", is: State.master };
void this._view.webview.postMessage(msg);
}
}
static play(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "state", state: "playing" };
void this._view.webview.postMessage(msg);
}
}
static pause(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "state", state: "paused" };
void this._view.webview.postMessage(msg);
}
}
static stop(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "state", state: "none" };
void this._view.webview.postMessage(msg);
}
}
static wasmLoad(path: string): void {
if (this._view) {
const url = this._view.webview.asWebviewUri(Uri.file(path)).toString();
const msg: ProviderSMsg = { command: "load", url };
void this._view.webview.postMessage(msg);
}
}
static wasmPause(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "pause" };
void this._view.webview.postMessage(msg);
}
}
static wasmPlay(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "play" };
void this._view.webview.postMessage(msg);
}
}
static wasmStop(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "stop" };
void this._view.webview.postMessage(msg);
}
}
static wasmVolume(level: number): void {
if (this._view) {
const msg: ProviderSMsg = { command: "volume", level };
void this._view.webview.postMessage(msg);
}
}
/* static position(position: number): void {
const msg: ProviderSMsg = { command: "position", position });
} */
static account(profiles: NeteaseTypings.Profile[]): void {
if (this._view) {
const msg: ProviderSMsg = { command: "account", profiles };
void this._view.webview.postMessage(msg);
}
}
static metadata(): void {
if (this._view) {
const item = State.playItem;
const msg: ProviderSMsg = item
? {
command: "metadata",
// duration: item.item.dt / 1000,
title: item.label,
artist: item.description,
album: item.tooltip,
artwork: [{ src: item.item.al.picUrl }],
}
: { command: "metadata" };
void this._view.webview.postMessage(msg);
}
}
resolveWebviewView(
webview: WebviewView
// context: WebviewViewResolveContext
// token: CancellationToken
): void {
AccountViewProvider._view = webview;
webview.title = i18n.word.account;
webview.webview.options = {
enableScripts: true,
localResourceRoots: [this._extUri, Uri.file(SETTING_DIR)],
};
webview.webview.onDidReceiveMessage((msg: ProviderCMsg) => {
switch (msg.command) {
case "pageLoaded":
{
const files = ["flac", "m4a", "ogg", "opus"].map((ext) =>
webview.webview
.asWebviewUri(
Uri.joinPath(this._extUri, "media", "audio", `silent.${ext}`)
)
.toString()
);
const msg: ProviderSMsg = { command: "test", files };
AccountViewProvider.master();
AccountViewProvider.account([...AccountManager.accounts.values()]);
AccountViewProvider.metadata();
void webview.webview.postMessage(msg);
AccountViewProvider.wasmVolume(this._volume);
}
break;
case "account":
AccountManager.accountQuickPick(msg.userId);
break;
case "end":
if (State.repeat) IPC.load();
else void commands.executeCommand("cloudmusic.next");
break;
case "load":
IPC.loaded();
break;
case "position":
IPC.position(msg.pos);
break;
case "playing":
IPC.playing(msg.playing);
break;
default:
void commands.executeCommand(`cloudmusic.${msg.command}`);
break;
}
});
const js = webview.webview
.asWebviewUri(Uri.joinPath(this._extUri, "dist", "provider.js"))
.toString();
const css = webview.webview
.asWebviewUri(Uri.joinPath(this._extUri, "dist", "style.css"))
.toString();
webview.webview.html = `
<!DOCTYPE html>
<html
lang="en"
${window.activeColorTheme.kind === ColorThemeKind.Light ? "" : 'class="dark"'}
>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>${i18n.word.account}</title>
<link rel="stylesheet" type="text/css" href=${css} />
</head>
<body>
<div id="root"></div>
</body>
<script type="module" src=${js} nonce=${getNonce()}></script>
</html>`;
}
}
export class Webview {
private static readonly _cssUri = Uri.file(resolve(__dirname, "style.css"));
private static readonly _iconUri = Uri.file(
resolve(__dirname, "..", "media", "icon.ico")
);
static async login(): Promise<void> {
const key = await IPC.netease("loginQrKey", []);
if (!key) return;
const imgSrc = await toDataURL(
`https://music.163.com/login?codekey=${key}`
);
const { panel, setHtml } = this._getPanel(i18n.word.signIn, "login");
panel.webview.onDidReceiveMessage(({ channel }: CSMessage) => {
void panel.webview.postMessage({ msg: { imgSrc }, channel });
});
return new Promise((resolve, reject) => {
const timer = setInterval(
() =>
void IPC.netease("loginQrCheck", [key])
.then((code) => {
if (code === 803) {
panel.dispose();
resolve();
} else if (code === 800) {
panel.dispose();
void window.showErrorMessage(i18n.sentence.fail.signIn);
reject();
}
})
.catch(reject),
512
);
panel.onDidDispose(() => clearInterval(timer));
setHtml();
});
}
static lyric(): void {
const { panel, setHtml } = this._getPanel(i18n.word.lyric, "lyric");
panel.onDidDispose(() => {
State.lyric.updatePanel = undefined;
State.lyric.updateFontSize = undefined;
});
State.lyric.updatePanel = (oi: number, ti: number) =>
panel.webview.postMessage({
command: "lyric",
data: {
otext: State.lyric.o.text?.[oi],
ttext: State.lyric.t.text?.[ti],
},
} as LyricSMsg);
State.lyric.updateFontSize = (size: number) =>
panel.webview.postMessage({
command: "size",
data: size,
} as LyricSMsg);
setHtml();
}
static async description(id: number, name: string): Promise<void> {
const desc = await IPC.netease("artistDesc", [id]);
const { panel, setHtml } = this._getPanel(name, "description");
panel.webview.onDidReceiveMessage(({ channel }: CSMessage) => {
void panel.webview.postMessage({ msg: { name, desc }, channel });
});
setHtml();
}
static async musicRanking(uid: number): Promise<void> {
const record = await IPC.netease("userRecord", [uid]);
const { panel, setHtml } = this._getPanel(
i18n.word.musicRanking,
"musicRanking"
);
panel.webview.onDidReceiveMessage(
({ msg, channel }: CSMessage | MsicRankingCMsg) => {
if (channel) {
void panel.webview.postMessage({ msg: record, channel });
return;
}
if (!msg) return;
switch (msg.command) {
case "song":
void MultiStepInput.run(async (input) =>
pickSong(
input,
1,
(await IPC.netease("songDetail", [uid, [msg.id]]))[0]
)
);
break;
case "album":
void MultiStepInput.run((input) => pickAlbum(input, 1, msg.id));
break;
case "artist":
void MultiStepInput.run((input) => pickArtist(input, 1, msg.id));
break;
}
}
);
setHtml();
}
static comment(
type: NeteaseEnum.CommentType,
gid: number,
title: string
): void {
let time = 0;
let index = 0;
let pageNo = 1;
const pageSize = 30;
const sortTypes = [
NeteaseEnum.SortType.hottest,
...(type === NeteaseEnum.CommentType.dj
? []
: [NeteaseEnum.SortType.recommendation]),
NeteaseEnum.SortType.latest,
];
const titles = [
i18n.word.hottest,
...(type === NeteaseEnum.CommentType.dj
? []
: [i18n.word.recommendation]),
i18n.word.latest,
];
const getList = async () => {
const list = await IPC.netease("commentNew", [
type,
gid,
pageNo,
pageSize,
sortTypes[index],
time,
]);
time = list.comments?.[list.comments.length - 1]?.time || 0;
return list;
};
const { panel, setHtml } = this._getPanel(
`${i18n.word.comment} (${title})`,
"comment"
);
panel.webview.onDidReceiveMessage(
async ({ msg, channel }: CSMessage<CommentCSMsg> | CommentCMsg) => {
if (!channel) {
switch (msg.command) {
case "user":
void MultiStepInput.run((input) => pickUser(input, 1, msg.id));
break;
/* case "floor":
await apiCommentFloor(type, gid, id, pageSize, time);
break;
case "reply":
break; */
}
return;
}
if (msg.command === "init") {
void panel.webview.postMessage({
msg: { titles, ...(await getList()) },
channel,
});
return;
}
if (msg.command === "like") {
void panel.webview.postMessage({
msg: await IPC.netease("commentLike", [type, msg.t, gid, msg.id]),
channel,
});
return;
}
switch (msg.command) {
case "prev":
if (pageNo <= 1) return;
--pageNo;
if (index === sortTypes.length - 1) time = 0;
break;
case "next":
++pageNo;
break;
case "tabs":
time = 0;
index = msg.index;
pageNo = 1;
break;
}
void panel.webview.postMessage({
msg: { ...(await getList()) },
channel,
});
}
);
setHtml();
}
private static _getPanel(title: string, type: WebviewType) {
const panel = window.createWebviewPanel(
"Cloudmusic",
title,
ViewColumn.One,
{ enableScripts: true, retainContextWhenHidden: true }
);
panel.iconPath = this._iconUri;
const css = panel.webview.asWebviewUri(this._cssUri).toString();
const js = panel.webview
.asWebviewUri(Uri.file(resolve(__dirname, `${type}.js`)))
.toString();
return {
panel,
setHtml: () => (panel.webview.html = this._layout(title, css, js)),
};
}
private static _layout(title: string, css: string, js: string) {
const nonce = getNonce();
return `
<!DOCTYPE html>
<html
lang="en"
${window.activeColorTheme.kind === ColorThemeKind.Light ? "" : 'class="dark"'}
>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>${title}</title>
<link rel="stylesheet" type="text/css" href=${css} />
</head>
<body>
<div id="root"></div>
</body>
<script type="module" src=${js} nonce=${nonce}></script>
</html>`;
}
} | the_stack |
import IReservesApiModel from '@/model/api/reserves/IReservesApiModel';
import IRuleApiModel from '@/model/api/rule/IRuleApiModel';
import { inject, injectable } from 'inversify';
import { cloneDeep } from 'lodash';
import * as apid from '../../../../../api';
import * as event from '../../../lib/event';
import DateUtil from '../../../util/DateUtil';
import IScheduleApiModel from '../../api/schedule/IScheduleApiModel';
import IChannelModel from '../../channels/IChannelModel';
import IServerConfigModel from '../../serverConfig/IServerConfigModel';
import { ISettingStorageModel } from '../../storage/setting/ISettingStorageModel';
import IGuideProgramDialogState from '../guide/IGuideProgramDialogState';
import IGuideReserveUtil, { ReserveStateItemIndex } from '../guide/IGuideReserveUtil';
import IReserveStateUtil, { ReserveStateData } from '../reserve/IReserveStateUtil';
import ISearchState, {
BroadcastWave,
EncodedOption,
GenreItem,
KeywordOption,
QuerySearchOption,
ReserveOption,
SaveOption,
SearchOption,
SearchResultItem,
SelectorItem,
SubGenreIndex,
SubGenreItem,
TimeReserveOption,
Week,
} from './ISearchState';
@injectable()
export default class SearchState implements ISearchState {
public isTimeSpecification: boolean = false;
public searchOption: SearchOption | null = null;
public timeReserveOption: TimeReserveOption | null = null;
public reserveOption: ReserveOption | null = null;
public saveOption: SaveOption | null = null;
public encodeOption: EncodedOption | null = null;
// vuetify-datetime-picker のリセットがうまくできないため一瞬 false にすることでクリアする
public isShowPeriod: boolean = true;
// ルールオプションのアコーディオンの開閉を行う
public optionPanel: number[] = [];
// ジャンル絞り込みプルダウン値
public genreSelect: number = -1;
private channelModel: IChannelModel;
private serverConfig: IServerConfigModel;
private scheduleApiModel: IScheduleApiModel;
private ruleApiModel: IRuleApiModel;
private reservesApiModel: IReservesApiModel;
private reserveStateUtil: IReserveStateUtil;
private reserveIndexUtil: IGuideReserveUtil;
private programDialogState: IGuideProgramDialogState;
private settingModel: ISettingStorageModel;
private genreItems: GenreItem[] = [];
private startTimeItems: SelectorItem[] = [];
private rangeTimeItems: SelectorItem[] = [];
private ruleId: apid.RuleId | null = null;
private searchResult: SearchResultItem[] | null = null;
private reservesResult: apid.ReserveItem[] | null = null;
constructor(
@inject('IChannelModel') channelModel: IChannelModel,
@inject('IServerConfigModel') serverConfig: IServerConfigModel,
@inject('IScheduleApiModel') scheduleApiModel: IScheduleApiModel,
@inject('IRuleApiModel') ruleApiModel: IRuleApiModel,
@inject('IReservesApiModel') reservesApiModel: IReservesApiModel,
@inject('IReserveStateUtil') reserveStateUtil: IReserveStateUtil,
@inject('IGuideReserveUtil') reserveIndexUtil: IGuideReserveUtil,
@inject('IGuideProgramDialogState') programDialogState: IGuideProgramDialogState,
@inject('ISettingStorageModel') settingModel: ISettingStorageModel,
) {
this.channelModel = channelModel;
this.serverConfig = serverConfig;
this.scheduleApiModel = scheduleApiModel;
this.ruleApiModel = ruleApiModel;
this.reservesApiModel = reservesApiModel;
this.reserveStateUtil = reserveStateUtil;
this.reserveIndexUtil = reserveIndexUtil;
this.programDialogState = programDialogState;
this.settingModel = settingModel;
// set genres
for (const genre in event.Genre) {
const subgenres = (event.SubGenre as any)[genre];
if (typeof subgenres === 'undefined') {
continue;
}
const subGenres: SubGenreItem[] = [];
for (const s in subgenres) {
if (subgenres[s].length === 0) {
continue;
}
subGenres.push({
name: subgenres[s],
value: parseInt(s, 10),
});
}
this.genreItems.push({
name: (event.Genre as any)[genre],
value: parseInt(genre, 10),
subGenres: subGenres,
});
}
// set startTimeItems
for (let i = 0; i <= 23; i++) {
this.startTimeItems.push({
text: `${i.toString(10)}時`,
value: i,
});
}
// set rangeTimeItems
for (let i = 1; i <= 23; i++) {
this.rangeTimeItems.push({
text: `${i.toString(10)}時間`,
value: i,
});
}
}
/**
* 初期化
*/
public async init(ruleId: apid.RuleId | null = null): Promise<void> {
this.ruleId = ruleId;
this.isTimeSpecification = false;
this.initSearchOption();
this.initTimeReserveOption();
this.initReserveOption();
this.initSaveOption();
this.initEncodeOption();
this.genreSelect = -1;
this.programDialogState.close();
// 検索結果クリア
this.searchResult = null;
this.reservesResult = null;
if (this.ruleId !== null) {
// ruleId を元にルール情報を取得する
const rule = await this.ruleApiModel.get(this.ruleId);
// 取得したルールを反映させる
this.setRuleOption(rule);
}
this.initOptionPanel();
}
/**
* 検索オプション初期化
*/
private initSearchOption(): void {
this.searchOption = {
keyword: null,
keywordOption: {
keyCS: false,
keyRegExp: false,
name: false,
description: false,
extended: false,
},
ignoreKeyword: null,
ignoreKeywordOption: {
keyCS: false,
keyRegExp: false,
name: false,
description: false,
extended: false,
},
channels: [],
broadcastWave: {
GR: {
isEnable: true,
isShow: true,
},
BS: {
isEnable: true,
isShow: true,
},
CS: {
isEnable: true,
isShow: true,
},
SKY: {
isEnable: true,
isShow: true,
},
},
genres: {},
isShowSubgenres: true,
startTime: undefined,
rangeTime: undefined,
week: {
mon: true,
tue: true,
wed: true,
thu: true,
fri: true,
sat: true,
sun: true,
},
durationMin: null,
durationMax: null,
startPeriod: null,
endPeriod: null,
isFree: false,
};
// 放送波の表示をサーバの設定と合わせる
const config = this.serverConfig.getConfig();
if (config !== null) {
if (config.broadcast.GR === false) {
this.searchOption.broadcastWave.GR.isEnable = false;
this.searchOption.broadcastWave.GR.isShow = false;
}
if (config.broadcast.BS === false) {
this.searchOption.broadcastWave.BS.isEnable = false;
this.searchOption.broadcastWave.BS.isShow = false;
}
if (config.broadcast.CS === false) {
this.searchOption.broadcastWave.CS.isEnable = false;
this.searchOption.broadcastWave.CS.isShow = false;
}
if (config.broadcast.SKY === false) {
this.searchOption.broadcastWave.SKY.isEnable = false;
this.searchOption.broadcastWave.SKY.isShow = false;
}
}
// ジャンル
for (const genreItem of this.genreItems) {
const subGenreIndex: SubGenreIndex = {};
for (const subGenreItem of genreItem.subGenres) {
subGenreIndex[subGenreItem.value] = false;
}
this.searchOption.genres[genreItem.value] = {
isEnable: false,
subGenreIndex: subGenreIndex,
};
}
}
/**
* 時刻予約オプション初期化
*/
private initTimeReserveOption(): void {
this.timeReserveOption = {
keyword: null,
channel: undefined,
startTime: null,
endTime: null,
week: {
mon: false,
tue: false,
wed: false,
thu: false,
fri: false,
sat: false,
sun: false,
},
};
}
/**
* 予約プション初期化
*/
private initReserveOption(): void {
this.reserveOption = {
enable: true,
allowEndLack: true,
avoidDuplicate: this.settingModel.getSavedValue().isCheckAvoidDuplicate,
periodToAvoidDuplicate: null,
};
}
/**
* 保存オプション
*/
private initSaveOption(): void {
this.saveOption = {
parentDirectoryName: null,
directory: null,
recordedFormat: null,
};
}
/**
* エンコードオプション
*/
private initEncodeOption(): void {
this.encodeOption = {
mode1: null,
encodeParentDirectoryName1: null,
directory1: null,
mode2: null,
encodeParentDirectoryName2: null,
directory2: null,
mode3: null,
encodeParentDirectoryName3: null,
directory3: null,
isDeleteOriginalAfterEncode: this.settingModel.getSavedValue().isCheckDeleteOriginalAfterEncode,
};
}
/**
* パネルの開閉を初期化する
*/
private initOptionPanel(): void {
this.optionPanel = [0, 1, 2, 3, 4, 7];
if (this.encodeOption !== null) {
// encode2 が空でない場合は開く
if (this.encodeOption.mode2) {
this.optionPanel.push(5);
}
// encode3 が空でない場合は開く
if (this.encodeOption.mode3) {
this.optionPanel.push(6);
}
}
}
/**
* 渡された rule を反映させる
* @param rule: apid.Rule
*/
private setRuleOption(rule: apid.Rule): void {
this.isTimeSpecification = rule.isTimeSpecification;
if (this.isTimeSpecification === true) {
this.setTimeReserveRuleSearchOption(rule.searchOption);
} else {
this.setSearchOption(rule.searchOption);
}
this.setReserveOption(rule.reserveOption);
if (typeof rule.saveOption !== 'undefined') {
this.setSaveOption(rule.saveOption);
}
if (typeof rule.encodeOption !== 'undefined') {
this.setEncodeOption(rule.encodeOption);
}
}
/**
* timeReserveOption をセットする
* @param searchOption: apid.RuleSearchOption
*/
private setTimeReserveRuleSearchOption(searchOption: apid.RuleSearchOption): void {
if (typeof searchOption.keyword === 'undefined') {
throw new Error('keywordIsUndefined');
}
if (typeof searchOption.channelIds === 'undefined' || searchOption.channelIds.length === 0) {
throw new Error('channelIdsIsUndefined');
}
if (typeof searchOption.times === 'undefined' || searchOption.times.length === 0) {
throw new Error('timesIsUndefined');
}
for (const time of searchOption.times) {
if (typeof time.start === 'undefined' || typeof time.range === 'undefined') {
throw new Error('TimeOptionError');
}
}
const start = searchOption.times[0].start;
const range = searchOption.times[0].range;
this.timeReserveOption = {
keyword: searchOption.keyword,
channel: searchOption.channelIds[0],
startTime: typeof start === 'undefined' ? null : this.convertNumToTimepickerStr(start),
endTime: typeof start === 'undefined' || typeof range === 'undefined' ? null : this.convertNumToTimepickerStr(start + range),
week: this.convertRuleWeekToWeek(searchOption.times[0].week),
};
}
/**
* searchOption をセットする
* @param searchOption: apid.RuleSearchOption
*/
private setSearchOption(searchOption: apid.RuleSearchOption): void {
if (this.searchOption === null) {
throw new Error('searchOptionIsNull');
}
// キーワード
if (typeof searchOption.keyword !== 'undefined') {
this.searchOption.keyword = searchOption.keyword;
this.searchOption.keywordOption = {
keyCS: !!searchOption.keyCS,
keyRegExp: !!searchOption.keyRegExp,
name: !!searchOption.name,
description: !!searchOption.description,
extended: !!searchOption.extended,
};
}
// 除外キーワード
if (typeof searchOption.ignoreKeyword !== 'undefined') {
this.searchOption.ignoreKeyword = searchOption.ignoreKeyword;
this.searchOption.ignoreKeywordOption = {
keyCS: !!searchOption.ignoreKeyCS,
keyRegExp: !!searchOption.ignoreKeyRegExp,
name: !!searchOption.ignoreName,
description: !!searchOption.ignoreDescription,
extended: !!searchOption.ignoreExtended,
};
}
// 放送局
if (typeof searchOption.channelIds !== 'undefined') {
this.searchOption.channels = searchOption.channelIds.slice(0, searchOption.channelIds.length);
} else {
this.searchOption.broadcastWave.GR.isEnable = !!searchOption.GR;
this.searchOption.broadcastWave.BS.isEnable = !!searchOption.BS;
this.searchOption.broadcastWave.CS.isEnable = !!searchOption.CS;
this.searchOption.broadcastWave.SKY.isEnable = !!searchOption.SKY;
}
// ジャンル
if (typeof searchOption.genres !== 'undefined') {
for (const genre of searchOption.genres) {
// tslint:disable-next-line:prefer-conditional-expression
if (typeof genre.subGenre === 'undefined') {
this.searchOption.genres[genre.genre].isEnable = true;
} else {
this.searchOption.genres[genre.genre].isEnable = false;
this.searchOption.genres[genre.genre].subGenreIndex[genre.subGenre] = true;
}
}
}
// 時刻 (レンジ)
if (typeof searchOption.times !== 'undefined' && searchOption.times.length > 0) {
this.searchOption.startTime = searchOption.times[0].start;
this.searchOption.rangeTime = searchOption.times[0].range;
this.searchOption.week = this.convertRuleWeekToWeek(searchOption.times[0].week);
}
// 長さ
if (typeof searchOption.durationMin !== 'undefined') {
this.searchOption.durationMin = Math.floor(searchOption.durationMin / 60);
}
if (typeof searchOption.durationMax !== 'undefined') {
this.searchOption.durationMax = Math.floor(searchOption.durationMax / 60);
}
// 期間
if (typeof searchOption.searchPeriods !== 'undefined' && searchOption.searchPeriods.length > 0) {
this.searchOption.startPeriod = new Date(searchOption.searchPeriods[0].startAt);
this.searchOption.endPeriod = new Date(searchOption.searchPeriods[0].endAt);
}
// 無料放送か
this.searchOption.isFree = !!searchOption.isFree;
}
/**
* reserveOption をセットする
* @param reserveOption: apidRuleReserveOption
*/
private setReserveOption(reserveOption: apid.RuleReserveOption): void {
if (this.reserveOption === null) {
throw new Error('reserveOptionIsNull');
}
this.reserveOption.enable = reserveOption.enable;
this.reserveOption.allowEndLack = reserveOption.allowEndLack;
this.reserveOption.avoidDuplicate = reserveOption.avoidDuplicate;
if (typeof reserveOption.periodToAvoidDuplicate !== 'undefined') {
this.reserveOption.periodToAvoidDuplicate = reserveOption.periodToAvoidDuplicate;
}
}
/**
* saveOption をセットする
* @param saveOption: apid.ReserveSaveOption
*/
private setSaveOption(saveOption: apid.ReserveSaveOption): void {
if (this.saveOption === null) {
throw new Error('saveOptionIsNull');
}
if (typeof saveOption.parentDirectoryName !== 'undefined') {
this.saveOption.parentDirectoryName = saveOption.parentDirectoryName;
}
if (typeof saveOption.directory !== 'undefined') {
this.saveOption.directory = saveOption.directory;
}
if (typeof saveOption.recordedFormat !== 'undefined') {
this.saveOption.recordedFormat = saveOption.recordedFormat;
}
}
/**
* encodeOption をセットする
* @param encodeOption: apid.ReserveEncodedOption
*/
private setEncodeOption(encodeOption: apid.ReserveEncodedOption): void {
if (this.encodeOption === null) {
throw new Error('encodeOptionIsNull');
}
if (typeof encodeOption.mode1 !== 'undefined') {
this.encodeOption.mode1 = encodeOption.mode1;
if (typeof encodeOption.encodeParentDirectoryName1 !== 'undefined') {
this.encodeOption.encodeParentDirectoryName1 = encodeOption.encodeParentDirectoryName1;
}
if (typeof encodeOption.directory1 !== 'undefined') {
this.encodeOption.directory1 = encodeOption.directory1;
}
}
if (typeof encodeOption.mode2 !== 'undefined') {
this.encodeOption.mode2 = encodeOption.mode2;
if (typeof encodeOption.encodeParentDirectoryName2 !== 'undefined') {
this.encodeOption.encodeParentDirectoryName2 = encodeOption.encodeParentDirectoryName2;
}
if (typeof encodeOption.directory2 !== 'undefined') {
this.encodeOption.directory2 = encodeOption.directory2;
}
}
if (typeof encodeOption.mode3 !== 'undefined') {
this.encodeOption.mode3 = encodeOption.mode3;
if (typeof encodeOption.encodeParentDirectoryName3 !== 'undefined') {
this.encodeOption.encodeParentDirectoryName3 = encodeOption.encodeParentDirectoryName3;
}
if (typeof encodeOption.directory3 !== 'undefined') {
this.encodeOption.directory3 = encodeOption.directory3;
}
}
this.encodeOption.isDeleteOriginalAfterEncode = encodeOption.isDeleteOriginalAfterEncode;
}
/**
* query による検索設定をセットする
* @param query: QuerySearchOption
*/
public setQueryOption(query: QuerySearchOption): void {
if (this.searchOption === null) {
throw new Error('SearchOptionIsNull');
}
if (typeof query.keyword !== 'undefined') {
this.searchOption.keyword = query.keyword;
}
if (typeof query.channelId !== 'undefined') {
this.searchOption.channels.push(query.channelId);
}
if (typeof query.genre !== 'undefined' && typeof this.searchOption.genres[query.genre] !== 'undefined') {
if (typeof query.subGenre === 'undefined') {
this.searchOption.genres[query.genre].isEnable = true;
for (const subGenre in this.searchOption.genres[query.genre].subGenreIndex) {
this.searchOption.genres[query.genre].subGenreIndex[subGenre] = true;
}
} else if (typeof this.searchOption.genres[query.genre].subGenreIndex[query.subGenre] !== 'undefined') {
this.searchOption.genres[query.genre].subGenreIndex[query.subGenre] = true;
}
}
}
/**
* 入力項目をクリア
*/
public clear(): void {
this.initSearchOption();
this.initTimeReserveOption();
this.searchResult = null;
}
/**
* 放送局 item を返す
* @return SelectorItem[]
*/
public getChannelItems(): SelectorItem[] {
return this.channelModel.getChannels(this.settingModel.getSavedValue().isHalfWidthDisplayed).map(c => {
return {
text: c.name,
value: c.id,
};
});
}
/**
* ジャンル item を返す
* @return GenreItem
*/
public getGenreItems(): GenreItem[] {
return this.genreItems;
}
/**
* 時刻の開始時間 item を返す
* @return SelectorItem[]
*/
public getStartTimeItems(): SelectorItem[] {
return this.startTimeItems;
}
/**
* 時刻の時刻幅 item を返す
* @return SelectorItem[]
*/
public getRangeTimeItems(): SelectorItem[] {
return this.rangeTimeItems;
}
/**
* ジャンルクリック時の処理
* @param genre: apid.ProgramGenreLv1
*/
public onClickGenre(genre: apid.ProgramGenreLv1): void {
if (this.searchOption === null || typeof this.searchOption.genres[genre] === 'undefined') {
return;
}
const subGenreCnt = Object.keys(this.searchOption.genres[genre].subGenreIndex).length;
if (this.searchOption.isShowSubgenres === true && subGenreCnt > 0) {
const isEnable = this.getEnabledSubGenreCnt(genre) < subGenreCnt;
this.searchOption.genres[genre].isEnable = isEnable;
for (const subGenre in this.searchOption.genres[genre].subGenreIndex) {
this.searchOption.genres[genre].subGenreIndex[subGenre] = isEnable;
}
} else {
const isEnable = !this.searchOption.genres[genre].isEnable;
this.searchOption.genres[genre].isEnable = isEnable;
for (const subGenre in this.searchOption.genres[genre].subGenreIndex) {
this.searchOption.genres[genre].subGenreIndex[subGenre] = isEnable;
}
}
}
/**
* 指定されたジャンルの有効になっているサブジャンルの個数を返す
* @param genre: apid.ProgramGenreLv1
* @return number
*/
private getEnabledSubGenreCnt(genre: apid.ProgramGenreLv1): number {
if (this.searchOption === null || typeof this.searchOption.genres[genre] === 'undefined') {
return 0;
}
let enabledSubGenreCnt = 0;
for (const subGenre in this.searchOption.genres[genre].subGenreIndex) {
if (this.searchOption.genres[genre].subGenreIndex[subGenre] === true) {
enabledSubGenreCnt++;
}
}
return enabledSubGenreCnt;
}
/**
* サブジャンルクリック時の処理
* @param genre: apid.ProgramGenreLv1
* @param subGenre: apid.ProgramGenreLv2
*/
public onClickSubGenre(genre: apid.ProgramGenreLv1, subGenre: apid.ProgramGenreLv2): void {
if (
this.searchOption === null ||
typeof this.searchOption.genres[genre] === 'undefined' ||
typeof this.searchOption.genres[genre].subGenreIndex[subGenre] === 'undefined'
) {
return;
}
this.searchOption.genres[genre].subGenreIndex[subGenre] = !this.searchOption.genres[genre].subGenreIndex[subGenre];
this.searchOption.genres[genre].isEnable = this.getEnabledSubGenreCnt(genre) >= Object.keys(this.searchOption.genres[genre].subGenreIndex).length;
}
/**
* ジャンルクリア処理
*/
public clearGenres(): void {
if (this.searchOption === null) {
return;
}
for (const genre in this.searchOption.genres) {
this.searchOption.genres[genre].isEnable = false;
for (const subGenre in this.searchOption.genres[genre].subGenreIndex) {
this.searchOption.genres[genre].subGenreIndex[subGenre] = false;
}
}
}
/**
* 検索準備
*/
public prepSearch(): void {
// 検索オプション準備
this.prepSearchOption();
// ディレクトリの自動設定
if (this.settingModel.getSavedValue().isEnableCopyKeywordToDirectory === true) {
if (this.searchOption !== null && this.saveOption !== null && this.isEditingRule() === false) {
this.saveOption.directory = this.searchOption.keyword;
this.saveOption = cloneDeep(this.saveOption);
if (this.encodeOption !== null) {
this.encodeOption.directory1 = this.searchOption.keyword;
}
}
}
// エンコード設定
if (this.isEditingRule() === false && this.settingModel.getSavedValue().isEnableEncodingSettingWhenCreateRule === true && this.encodeOption !== null) {
const items = this.getEncodeModeItems();
if (items.length > 0) {
this.encodeOption.mode1 = items[0];
}
}
}
/**
* searchOption の準備
*/
private prepSearchOption(): void {
if (this.searchOption === null) {
throw new Error('searchOption is null');
}
// keyword
if (this.searchOption.keyword === null) {
this.searchOption.keywordOption.keyCS = false;
this.searchOption.keywordOption.keyRegExp = false;
this.searchOption.keywordOption.name = false;
this.searchOption.keywordOption.description = false;
this.searchOption.keywordOption.extended = false;
} else if (this.isDisabledMainKeywordOption(this.searchOption.keywordOption) === true) {
this.searchOption.keywordOption.name = true;
this.searchOption.keywordOption.description = true;
}
// ignore keyword
if (this.searchOption.ignoreKeyword === null) {
this.searchOption.ignoreKeywordOption.keyCS = false;
this.searchOption.ignoreKeywordOption.keyRegExp = false;
this.searchOption.ignoreKeywordOption.name = false;
this.searchOption.ignoreKeywordOption.description = false;
this.searchOption.ignoreKeywordOption.extended = false;
} else if (this.isDisabledMainKeywordOption(this.searchOption.ignoreKeywordOption) === true) {
this.searchOption.ignoreKeywordOption.name = true;
this.searchOption.ignoreKeywordOption.description = true;
}
// channels
if (this.searchOption.channels.length > 0) {
this.searchOption.broadcastWave.GR.isEnable = false;
this.searchOption.broadcastWave.BS.isEnable = false;
this.searchOption.broadcastWave.CS.isEnable = false;
this.searchOption.broadcastWave.SKY.isEnable = false;
} else if (this.isDisabledAllBroadcasWave(this.searchOption.broadcastWave)) {
this.searchOption.broadcastWave.GR.isEnable = true;
this.searchOption.broadcastWave.BS.isEnable = true;
this.searchOption.broadcastWave.CS.isEnable = true;
this.searchOption.broadcastWave.SKY.isEnable = true;
}
// time range
if (typeof this.searchOption.startTime === 'undefined' || typeof this.searchOption.rangeTime === 'undefined') {
this.searchOption.startTime = undefined;
this.searchOption.rangeTime = undefined;
}
// week
if (
this.searchOption.week.mon === false &&
this.searchOption.week.tue === false &&
this.searchOption.week.wed === false &&
this.searchOption.week.thu === false &&
this.searchOption.week.fri === false &&
this.searchOption.week.sat === false &&
this.searchOption.week.sun === false
) {
this.searchOption.week.mon = true;
this.searchOption.week.tue = true;
this.searchOption.week.wed = true;
this.searchOption.week.thu = true;
this.searchOption.week.fri = true;
this.searchOption.week.sat = true;
this.searchOption.week.sun = true;
}
// period
if (this.searchOption.startPeriod === null || this.searchOption.endPeriod === null) {
this.searchOption.startPeriod = null;
this.searchOption.endPeriod = null;
}
}
/**
* keywordOption の name, description, extend すべてが有効になっていないか
* @param option: KeywordOption
* return boolean オプションが無効の場合は true を返す
*/
private isDisabledMainKeywordOption(option: KeywordOption): boolean {
return option.name === false && option.description === false && option.extended === false;
}
private isDisabledAllBroadcasWave(broadcas: BroadcastWave): boolean {
if (broadcas.GR.isShow === true && broadcas.GR.isEnable === true) {
return false;
}
if (broadcas.BS.isShow === true && broadcas.BS.isEnable === true) {
return false;
}
if (broadcas.CS.isShow === true && broadcas.CS.isEnable === true) {
return false;
}
if (broadcas.SKY.isShow === true && broadcas.SKY.isEnable === true) {
return false;
}
return true;
}
/**
* 番組を検索し結果を取得する
* @return Promise<void>
*/
public async fetchSearchResult(): Promise<void> {
if (this.searchOption === null) {
throw new Error('searchOption is null');
}
const scheduleSearchOption = this.createScheduleSearchOption(this.searchOption);
const newResult = await this.scheduleApiModel.getScheduleSearch(scheduleSearchOption);
const reserveIndex = await this.getReserveIndex(newResult);
this.searchResult = newResult.map(p => {
const startAt = DateUtil.getJaDate(new Date(p.startAt));
const endAt = DateUtil.getJaDate(new Date(p.endAt));
const channel = this.channelModel.findChannel(p.channelId, this.settingModel.getSavedValue().isHalfWidthDisplayed);
const reserveType = typeof reserveIndex[p.id] === 'undefined' ? 'none' : reserveIndex[p.id].type;
const result: SearchResultItem = {
display: {
channelName: channel === null ? p.channelId.toString(10) : channel.name,
name: p.name,
day: DateUtil.format(startAt, 'MM/dd'),
dow: DateUtil.format(startAt, 'w'),
startTime: DateUtil.format(startAt, 'hh:mm'),
endTime: DateUtil.format(endAt, 'hh:mm'),
duration: Math.floor((p.endAt - p.startAt) / 1000 / 60),
description: p.description,
extended: p.extended,
reserveType: reserveType,
},
channel: channel,
program: p,
};
if (typeof reserveIndex[p.id] !== 'undefined') {
result.reserve = {
type: reserveType,
reserveId: reserveIndex[p.id].item.reserveId,
ruleId: reserveIndex[p.id].item.ruleId,
};
}
return result;
});
}
/**
* ReserveStateItemIndex を取得する
* @param items: apid.ScheduleProgramItem[]
* @return Promise<ReserveStateItemIndex>
*/
private async getReserveIndex(items: apid.ScheduleProgramItem[]): Promise<ReserveStateItemIndex> {
const option = this.createGetReserveListOption(items);
if (option === null) {
return {};
}
return await this.reserveIndexUtil.getReserveIndex(option);
}
/**
* apid.ScheduleProgramItem[] から apid.GetReserveListsOption を生成する
* @param items: apid.ScheduleProgramItem[]
* @return apid.GetReserveListsOption | null items がからの場合は null を返す
*/
private createGetReserveListOption(items: apid.ScheduleProgramItem[]): apid.GetReserveListsOption | null {
if (items.length === 0) {
return null;
}
const option: apid.GetReserveListsOption = {
startAt: items[0].startAt,
endAt: items[0].endAt,
};
for (const item of items) {
if (option.startAt > item.startAt) {
option.startAt = item.startAt;
}
if (option.endAt < item.endAt) {
option.endAt = item.endAt;
}
}
return option;
}
/**
* SearchOption から apid.ScheduleSearchOption を生成する
* @param option: SearchOption
* @return apid.ScheduleSearchOption
*/
private createScheduleSearchOption(option: SearchOption): apid.ScheduleSearchOption {
return {
option: this.createRuleSearchOption(option),
isHalfWidth: this.settingModel.getSavedValue().isHalfWidthDisplayed,
limit: this.settingModel.getSavedValue().searchLength,
};
}
/**
* SearchOption から apid.RuleSearchOption を生成する
* @param option: SearchOption
* @return apid.RuleSearchOption
*/
private createRuleSearchOption(option: SearchOption): apid.RuleSearchOption {
const ruleOption: apid.RuleSearchOption = {};
// keyword
if (option.keyword !== null) {
ruleOption.keyword = option.keyword;
ruleOption.keyCS = option.keywordOption.keyCS;
ruleOption.keyRegExp = option.keywordOption.keyRegExp;
ruleOption.name = option.keywordOption.name;
ruleOption.description = option.keywordOption.description;
ruleOption.extended = option.keywordOption.extended;
}
// ignore keyword
if (option.ignoreKeyword !== null) {
ruleOption.ignoreKeyword = option.ignoreKeyword;
ruleOption.ignoreKeyCS = option.ignoreKeywordOption.keyCS;
ruleOption.ignoreKeyRegExp = option.ignoreKeywordOption.keyRegExp;
ruleOption.ignoreName = option.ignoreKeywordOption.name;
ruleOption.ignoreDescription = option.ignoreKeywordOption.description;
ruleOption.ignoreExtended = option.ignoreKeywordOption.extended;
}
// channels
if (option.channels.length > 0) {
ruleOption.channelIds = option.channels;
} else if (this.isEnabledAllBroadcasWave(option.broadcastWave) === false) {
if (option.broadcastWave.GR.isShow === true) {
ruleOption.GR = option.broadcastWave.GR.isEnable;
}
if (option.broadcastWave.BS.isShow === true) {
ruleOption.BS = option.broadcastWave.BS.isEnable;
}
if (option.broadcastWave.CS.isShow === true) {
ruleOption.CS = option.broadcastWave.CS.isEnable;
}
if (option.broadcastWave.SKY.isShow === true) {
ruleOption.SKY = option.broadcastWave.SKY.isEnable;
}
}
// genres
const genres: apid.Genre[] = [];
for (const genre in option.genres) {
if (option.genres[genre].isEnable === true) {
genres.push({
genre: parseInt(genre, 10),
});
continue;
}
for (const subGenre in option.genres[genre].subGenreIndex) {
if (option.genres[genre].subGenreIndex[subGenre] === true) {
genres.push({
genre: parseInt(genre, 10),
subGenre: parseInt(subGenre, 10),
});
}
}
}
if (genres.length > 0) {
ruleOption.genres = genres;
}
// time
ruleOption.times = [
{
week: this.convertWeekToRuleWeek(option.week),
},
];
if (typeof option.startTime !== 'undefined' && typeof option.rangeTime !== 'undefined') {
ruleOption.times[0].start = option.startTime;
ruleOption.times[0].range = option.rangeTime;
}
// isFree
if (option.isFree === true) {
ruleOption.isFree = option.isFree;
}
// duration
if (option.durationMin !== null) {
ruleOption.durationMin = option.durationMin * 60;
}
if (option.durationMax !== null) {
ruleOption.durationMax = option.durationMax * 60;
}
// periiod
if (option.startPeriod !== null && option.endPeriod !== null) {
ruleOption.searchPeriods = [
{
startAt: option.startPeriod.getTime(),
endAt: option.endPeriod.getTime(),
},
];
}
return ruleOption;
}
/**
* 有効な放送波が全て有効か返す
* @param broadcas: BroadcastWave
* @return boolean true なら有効
*/
private isEnabledAllBroadcasWave(broadcas: BroadcastWave): boolean {
if (broadcas.GR.isShow === true && broadcas.GR.isEnable !== true) {
return false;
}
if (broadcas.BS.isShow === true && broadcas.BS.isEnable !== true) {
return false;
}
if (broadcas.CS.isShow === true && broadcas.CS.isEnable !== true) {
return false;
}
if (broadcas.SKY.isShow === true && broadcas.SKY.isEnable !== true) {
return false;
}
return true;
}
/**
* Week を Rule の week に変換する
* @param week: Week
* @return number
*/
private convertWeekToRuleWeek(week: Week): number {
let weekNum = 0;
if (week.sun === true) {
weekNum += 0x01;
}
if (week.mon === true) {
weekNum += 0x02;
}
if (week.tue === true) {
weekNum += 0x04;
}
if (week.wed === true) {
weekNum += 0x08;
}
if (week.thu === true) {
weekNum += 0x10;
}
if (week.fri === true) {
weekNum += 0x20;
}
if (week.sat === true) {
weekNum += 0x40;
}
return weekNum === 0 ? 0x7f : weekNum;
}
/**
* Rule の week を Week に変換する
* @param week: number
* @return Week
*/
private convertRuleWeekToWeek(week: number): Week {
return {
sun: (week & 0x01) !== 0,
mon: (week & 0x02) !== 0,
tue: (week & 0x04) !== 0,
wed: (week & 0x08) !== 0,
thu: (week & 0x10) !== 0,
fri: (week & 0x20) !== 0,
sat: (week & 0x40) !== 0,
};
}
/**
* 取得した検索結果を返す
* @return SearchResultItem[] | null
*/
public getSearchResult(): SearchResultItem[] | null {
return this.searchResult;
}
/**
* ルールの予約情報を取得する
*/
public async fetchRuleReserves(): Promise<void> {
if (this.ruleId === null) {
throw new Error('RuleIdIsNull');
}
const result = await this.reservesApiModel.gets({
type: 'all',
isHalfWidth: this.settingModel.getSavedValue().isHalfWidthDisplayed,
ruleId: this.ruleId,
});
this.reservesResult = result.reserves;
}
/**
* 取得した予約情報を返す
* @return apid.ReserveItem[]
*/
public getRuleReservesResult(): ReserveStateData[] {
return this.reservesResult === null
? []
: this.reserveStateUtil.convertReserveItemsToStateDatas(this.reservesResult, this.settingModel.getSavedValue().isHalfWidthDisplayed);
}
/**
* 録画先ディレクトリの一覧を返す
* @return string[]
*/
public getPrentDirectoryItems(): string[] {
const config = this.serverConfig.getConfig();
return config === null ? [] : config.recorded;
}
/**
* エンコードモード一覧を返す
* @return string
*/
public getEncodeModeItems(): string[] {
const config = this.serverConfig.getConfig();
return config === null ? [] : config.encode;
}
/**
* エンコードに対応しているか
*/
public isEnableEncodeMode(): boolean {
return this.getEncodeModeItems().length > 0;
}
/**
* ルール編集か?
* @return boolean true でルール編集
*/
public isEditingRule(): boolean {
return this.ruleId !== null;
}
/**
* ルールの追加
*/
public async addRule(): Promise<void> {
await this.ruleApiModel.add(this.createAddRuleOption());
}
/**
* ルール追加用のデータを生成する
* @return apid.AddRuleOption
*/
private createAddRuleOption(): apid.AddRuleOption {
let rule: apid.AddRuleOption | null = null;
if (this.isTimeSpecification === false) {
if (this.searchOption === null) {
throw new Error('SearchOptionIsNull');
}
if (this.reserveOption === null) {
throw new Error('ReserveOptionIsNull');
}
rule = {
isTimeSpecification: false,
searchOption: this.createRuleSearchOption(this.searchOption),
reserveOption: this.createRuleReserveOption(this.reserveOption),
};
} else {
if (this.timeReserveOption === null) {
throw new Error('TimeReserveOptionIsNull');
}
if (this.reserveOption === null) {
throw new Error('ReserveOptionIsNull');
}
rule = {
isTimeSpecification: true,
searchOption: this.createTimeSpecificationRuleSearchOption(this.timeReserveOption),
reserveOption: this.createRuleReserveOption(this.reserveOption),
};
}
if (this.saveOption !== null) {
rule.saveOption = this.createReserveSaveOption(this.saveOption);
}
if (this.encodeOption !== null) {
rule.encodeOption = this.createReserveEncodedOption(this.encodeOption);
}
return rule;
}
/**
* TimeReserveOption から apid.RuleSearchOption を生成する
* @param option TimeReserveOption
* @return apid.RuleSearchOption
*/
private createTimeSpecificationRuleSearchOption(option: TimeReserveOption): apid.RuleSearchOption {
if (option.keyword === null || typeof option.channel === 'undefined' || option.startTime === null || option.endTime === null) {
throw new Error('TimeReserveOptionIsInvalidValue');
}
const start = this.convertTimepickerStrToNum(option.startTime);
const end = this.convertTimepickerStrToNum(option.endTime);
return {
keyword: option.keyword,
channelIds: [option.channel],
times: [
{
start: start,
range: start <= end ? end - start : 24 * 60 * 60 - (start - end),
week: this.convertWeekToRuleWeek(option.week),
},
],
};
}
/**
* Timepicker の入力値を秒に変換
* @param timeStr: string
* @return number
*/
private convertTimepickerStrToNum(timeStr: string): number {
const times = timeStr.split(':');
if (times.length < 2) {
throw new Error('TimePickerValueIsIncorrect');
}
return parseInt(times[0], 10) * 60 * 60 + parseInt(times[1], 10) * 60;
}
/**
* number を timpicker の入力に変換
* @param num: number
* @return string hh:mm
*/
private convertNumToTimepickerStr(num: number): string {
const hour = Math.floor(num / (60 * 60)) % 24;
const min = Math.floor((num % (60 * 60)) / 60) % 60;
return ('00' + hour).slice(-2) + ':' + ('00' + min).slice(-2);
}
/**
* ReserveOption から apid.RuleReserveOption を生成する
* @param option: ReserveOption
* @return apid.RuleReserveOption
*/
private createRuleReserveOption(option: ReserveOption): apid.RuleReserveOption {
const reserveOption: apid.RuleReserveOption = {
enable: option.enable,
allowEndLack: option.allowEndLack,
avoidDuplicate: option.avoidDuplicate,
};
if (option.periodToAvoidDuplicate !== null) {
reserveOption.periodToAvoidDuplicate = parseInt(option.periodToAvoidDuplicate as any, 10);
}
return reserveOption;
}
/**
* SaveOption から apid.ReserveSaveOption を生成する
* @param option: SaveOption
* @return apid.ReserveSaveOption
*/
private createReserveSaveOption(option: SaveOption): apid.ReserveSaveOption {
const saveOption: apid.ReserveSaveOption = {};
if (option.parentDirectoryName !== null) {
saveOption.parentDirectoryName = option.parentDirectoryName;
}
if (option.directory !== null) {
saveOption.directory = option.directory;
}
if (option.recordedFormat !== null) {
saveOption.recordedFormat = option.recordedFormat;
}
return saveOption;
}
/**
* EncodedOption から apid.ReserveEncodedOption を生成する
* @param option: EncodedOption
* @return apid.ReserveEncodedOption
*/
private createReserveEncodedOption(option: EncodedOption): apid.ReserveEncodedOption | undefined {
const encodeOption: apid.ReserveEncodedOption = {
isDeleteOriginalAfterEncode: option.isDeleteOriginalAfterEncode,
};
if (option.mode1 === null && option.mode2 === null && option.mode3 === null) {
return;
}
if (option.mode1 !== null) {
encodeOption.mode1 = option.mode1;
if (option.encodeParentDirectoryName1 !== null) {
encodeOption.encodeParentDirectoryName1 = option.encodeParentDirectoryName1;
}
if (option.directory1 !== null) {
encodeOption.directory1 = option.directory1;
}
}
if (option.mode2 !== null) {
encodeOption.mode2 = option.mode2;
if (option.encodeParentDirectoryName2 !== null) {
encodeOption.encodeParentDirectoryName2 = option.encodeParentDirectoryName2;
}
if (option.directory2 !== null) {
encodeOption.directory2 = option.directory2;
}
}
if (option.mode3 !== null) {
encodeOption.mode3 = option.mode3;
if (option.encodeParentDirectoryName3 !== null) {
encodeOption.encodeParentDirectoryName3 = option.encodeParentDirectoryName3;
}
if (option.directory3 !== null) {
encodeOption.directory3 = option.directory3;
}
}
return encodeOption;
}
/**
* ルール更新
*/
public async updateRule(): Promise<void> {
if (this.ruleId === null) {
throw new Error('RuleIdIsNull');
}
await this.ruleApiModel.update(this.ruleId, this.createAddRuleOption());
}
} | the_stack |
import { deepStrictEqual, doesNotThrow, notDeepStrictEqual, notStrictEqual, ok, strictEqual, throws } from 'assert';
// FoalTS
import { controller } from '../../common/utils/controller.util';
import { Config } from '../config';
import { Hook, HookFunction } from '../hooks';
import { Context, Get, HttpResponseOK, Post } from '../http';
import {
ApiDefineCallback,
ApiDefineTag,
ApiDeprecated,
ApiExternalDoc,
ApiInfo,
ApiOperation,
ApiOperationDescription,
ApiParameter,
ApiRequestBody,
ApiResponse,
ApiSecurityRequirement,
ApiServer,
ApiUseTag,
IApiCallback,
IApiComponents,
IApiExternalDocumentation,
IApiOperation,
IApiParameter,
IApiPaths,
IApiRequestBody,
IApiResponse,
IApiSecurityRequirement,
IApiServer,
IApiTag,
OpenApi
} from '../openapi';
import { dependency, ServiceManager } from '../service-manager';
import { makeControllerRoutes } from './make-controller-routes';
describe('makeControllerRoutes', () => {
const hook1: HookFunction = () => new HttpResponseOK('hook1');
const hook2: HookFunction = () => new HttpResponseOK('hook2');
const hook3: HookFunction = () => new HttpResponseOK('hook3');
const hook4: HookFunction = () => new HttpResponseOK('hook4');
const hook5: HookFunction = () => new HttpResponseOK('hook5');
const hook6: HookFunction = () => new HttpResponseOK('hook6');
const ctx = new Context({});
const services = new ServiceManager();
it('should return the routes from a controller with a method.', () => {
class FoobarController {
@Get()
bar() {}
}
const routes = Array.from(makeControllerRoutes(FoobarController, new ServiceManager()))
.map(({ route }) => route);
strictEqual(routes.length, 1);
// bar() {}
ok(routes[0].controller instanceof FoobarController);
deepStrictEqual(routes[0].hooks, []);
strictEqual(routes[0].httpMethod, 'GET');
strictEqual(routes[0].path, '');
strictEqual(routes[0].propertyKey, 'bar');
});
it('should return the routes from a controller with a method and a path.', () => {
@Reflect.metadata('path', '/foo/')
class FoobarController {
@Get('/bar')
bar() {}
}
const routes = Array.from(makeControllerRoutes(FoobarController, new ServiceManager()))
.map(({ route }) => route);
strictEqual(routes.length, 1);
// bar() {}
strictEqual(routes[0].path, '/foo/bar');
});
it('should return the routes from a controller with a method and controller and method hooks.', () => {
@Hook(hook3)
@Hook(hook4)
class FoobarController {
@Get()
@Hook(hook5)
@Hook(hook6)
bar() {}
}
const routes = Array.from(makeControllerRoutes(FoobarController, new ServiceManager()))
.map(({ route }) => route);
strictEqual(routes.length, 1);
// bar() {}
deepStrictEqual(
routes[0].hooks.map(hook => (hook(ctx, services) as HttpResponseOK).body),
[ 'hook3', 'hook4', 'hook5', 'hook6' ]
);
});
it('should return the routes from the controller methods that have a http-method decorator.', () => {
class FoobarController {
@Get()
bar() {}
foo() {}
@Post()
barfoo() {}
}
const routes = Array.from(makeControllerRoutes(FoobarController, new ServiceManager()))
.map(({ route }) => route);
strictEqual(routes.length, 2);
// bar() {}
strictEqual(routes[0].httpMethod, 'GET');
strictEqual(routes[0].propertyKey, 'bar');
// barfoo() {}
strictEqual(routes[1].httpMethod, 'POST');
strictEqual(routes[1].propertyKey, 'barfoo');
});
it('should properly instantiate a controller that has dependencies.', () => {
class Service1 {}
class Service2 {}
class FoobarController {
@dependency
service1: Service1;
@dependency
service2: Service2;
@Get()
bar() {}
}
const services = new ServiceManager();
const routes = Array.from(makeControllerRoutes(FoobarController, services))
.map(({ route }) => route);
strictEqual(routes.length, 1);
// bar
ok(routes[0].controller instanceof FoobarController);
strictEqual(routes[0].controller.service1, services.get(Service1));
strictEqual(routes[0].controller.service2, services.get(Service2));
});
it('should register the controller instance in the ServiceManager.', () => {
class FoobarController {
@Get()
bar() {}
}
const services = new ServiceManager();
const routes = Array.from(makeControllerRoutes(FoobarController, services))
.map(({ route }) => route);
strictEqual(routes.length, 1);
// bar
strictEqual(routes[0].controller, services.get(FoobarController));
});
it('should return all the routes of the prototype chain of an inherited controller.', () => {
class FoobarController {
@Get('/bar')
@Hook(hook1)
bar() {}
}
@Reflect.metadata('path', '/foo')
@Hook(hook2)
class FoobarController2 extends FoobarController {
@Post('/barfoo')
@Hook(hook3)
barfoo() {}
}
const routes = Array.from(makeControllerRoutes(FoobarController2, new ServiceManager()))
.map(({ route }) => route);
strictEqual(routes.length, 2);
// barfoo
ok(routes[0].controller instanceof FoobarController2);
deepStrictEqual(
routes[0].hooks.map(hook => (hook(ctx, services) as HttpResponseOK).body),
[ 'hook2', 'hook3' ]
);
strictEqual(routes[0].httpMethod, 'POST');
strictEqual(routes[0].path, '/foo/barfoo');
strictEqual(routes[0].propertyKey, 'barfoo');
// bar
ok(routes[1].controller instanceof FoobarController2);
deepStrictEqual(
routes[1].hooks.map(hook => (hook(ctx, services) as HttpResponseOK).body),
[ 'hook2', 'hook1' ]
);
strictEqual(routes[1].httpMethod, 'GET');
strictEqual(routes[1].path, '/foo/bar');
strictEqual(routes[1].propertyKey, 'bar');
});
it('should recursively return the routes of the subControllers if they exist.', () => {
@Reflect.metadata('path', '/api')
@Hook(hook2)
class ApiController {
@Get('/flights')
@Hook(hook3)
flights() {}
}
@Reflect.metadata('path', '/auth')
@Hook(hook4)
class AuthController {
@Get('/')
@Hook(hook5)
index() {}
}
@Reflect.metadata('path', '/foo')
@Hook(hook1)
class AppController {
subControllers = [
ApiController,
AuthController,
];
}
const routes = Array.from(makeControllerRoutes(AppController, new ServiceManager()))
.map(({ route }) => route);
strictEqual(routes.length, 2);
// bar
ok(routes[0].controller instanceof ApiController);
deepStrictEqual(
routes[0].hooks.map(hook => (hook(ctx, services) as HttpResponseOK).body),
[ 'hook1', 'hook2', 'hook3' ]
);
strictEqual(routes[0].httpMethod, 'GET');
strictEqual(routes[0].path, '/foo/api/flights');
strictEqual(routes[0].propertyKey, 'flights');
// foobar
ok(routes[1].controller instanceof AuthController);
deepStrictEqual(
routes[1].hooks.map(hook => (hook(ctx, services) as HttpResponseOK).body),
[ 'hook1', 'hook4', 'hook5' ]
);
strictEqual(routes[1].httpMethod, 'GET');
strictEqual(routes[1].path, '/foo/auth/');
strictEqual(routes[1].propertyKey, 'index');
});
it('should return the sub-controllers and controller routes in the right order.', () => {
class SubController {
@Get('/bar')
bar() {}
}
class AppController {
subControllers = [ SubController ];
@Get('/foo')
foo() {}
}
const routes = Array.from(makeControllerRoutes(AppController, new ServiceManager()))
.map(({ route }) => route);
strictEqual(routes.length, 2);
// bar
ok(routes[0].controller instanceof SubController);
// foo
ok(routes[1].controller instanceof AppController);
});
it('should bind the controller instance to the controller and method hooks.', () => {
let firstThis: FoobarController|undefined;
// tslint:disable-next-line:prefer-const
let secondThis: FoobarController|undefined;
@Hook(function(this: FoobarController) {
firstThis = this;
})
class FoobarController {
@Get()
@Hook(function(this: FoobarController) {
secondThis = this;
})
bar() {}
}
const routes = Array.from(makeControllerRoutes(FoobarController, new ServiceManager()))
.map(({ route }) => route);
strictEqual(routes.length, 1);
// bar() {}
strictEqual(firstThis, undefined);
routes[0].hooks[0](ctx, services);
strictEqual(firstThis as any instanceof FoobarController, true);
strictEqual(secondThis, undefined);
routes[0].hooks[1](ctx, services);
strictEqual(secondThis as any instanceof FoobarController, true);
strictEqual(firstThis, secondThis);
});
describe('should register the OpenAPI documents of the @ApiInfo controllers', () => {
const infoMetadata = {
title: 'foo',
version: '0.0.0'
};
const openApi = services.get(OpenApi);
beforeEach(() => Config.set('settings.openapi.enabled', true));
afterEach(() => Config.remove('settings.openapi.enabled'));
it('but not the other controllers.', () => {
@ApiInfo(infoMetadata)
class ApiController {}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
throws(
() => openApi.getDocument(AppController),
{
message: 'No OpenAPI document found associated with the controller AppController. '
+ 'Are you sure you added the @ApiInfo decorator on the controller?'
}
);
});
it('with the proper OpenAPI version.', () => {
@ApiInfo(infoMetadata)
class ApiController {}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
strictEqual(openApi.getDocument(ApiController).openapi, '3.0.0');
});
it('with the API information.', () => {
const metadata = {
title: 'foo',
version: '0.0.0'
};
@ApiInfo(metadata)
class ApiController {}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
strictEqual(openApi.getDocument(ApiController).info, metadata);
});
it('with the API information (dynamic API information).', () => {
const metadata = {
title: 'foo',
version: '0.0.0'
};
@ApiInfo((controller: ApiController) => controller.metadata)
class ApiController {
metadata = metadata;
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
strictEqual(openApi.getDocument(ApiController).info, metadata);
});
it('with the servers if they exist.', () => {
@ApiInfo(infoMetadata)
class ApiController {}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
strictEqual(openApi.getDocument(ApiController).hasOwnProperty('servers'), false);
const server: IApiServer = {
url: 'http://example.com'
};
@ApiInfo(infoMetadata)
@ApiServer(server)
class ApiController2 {}
class AppController2 {
subControllers = [
controller('/api', ApiController2)
];
}
Array.from(makeControllerRoutes(AppController2, services));
deepStrictEqual(openApi.getDocument(ApiController2).servers, [ server ]);
});
it('with the components if they exist.', () => {
@ApiInfo(infoMetadata)
class ApiController {
@Get('/foo')
foo() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
strictEqual(openApi.getDocument(ApiController).hasOwnProperty('components'), false);
const callback: IApiCallback = {};
@ApiInfo(infoMetadata)
@ApiDefineCallback('callback', callback)
class ApiController2 {}
class AppController2 {
subControllers = [
controller('/api', ApiController2)
];
}
Array.from(makeControllerRoutes(AppController2, services));
deepStrictEqual(openApi.getDocument(ApiController2).components, {
callbacks: { callback }
});
});
it('with the security requirements if they exist.', () => {
@ApiInfo(infoMetadata)
class ApiController {}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
strictEqual(openApi.getDocument(ApiController).hasOwnProperty('security'), false);
const securityRequirement: IApiSecurityRequirement = {};
@ApiInfo(infoMetadata)
@ApiSecurityRequirement(securityRequirement)
class ApiController2 {}
class AppController2 {
subControllers = [
controller('/api', ApiController2)
];
}
Array.from(makeControllerRoutes(AppController2, services));
deepStrictEqual(openApi.getDocument(ApiController2).security, [ securityRequirement ]);
});
it('with the tags if they exist.', () => {
@ApiInfo(infoMetadata)
class ApiController {
@Get('/foo')
foo() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
strictEqual(openApi.getDocument(ApiController).hasOwnProperty('tags'), false);
const tag: IApiTag = {
name: 'tag1'
};
@ApiInfo(infoMetadata)
@ApiDefineTag(tag)
class ApiController2 {}
class AppController2 {
subControllers = [
controller('/api', ApiController2)
];
}
Array.from(makeControllerRoutes(AppController2, services));
deepStrictEqual(openApi.getDocument(ApiController2).tags, [ tag ]);
});
it('with the external documentation if it exists.', () => {
@ApiInfo(infoMetadata)
class ApiController {}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
strictEqual(openApi.getDocument(ApiController).hasOwnProperty('externalDocs'), false);
const externalDocs: IApiExternalDocumentation = {
url: 'http://example.com/docs'
};
@ApiInfo(infoMetadata)
@ApiExternalDoc(externalDocs)
class ApiController2 {}
class AppController2 {
subControllers = [
controller('/api', ApiController2)
];
}
Array.from(makeControllerRoutes(AppController2, services));
strictEqual(openApi.getDocument(ApiController2).externalDocs, externalDocs);
});
it('with the paths and operations of the root controller methods.', () => {
const operation1: IApiOperation = {
responses: {},
summary: 'Operation 1',
};
const operation2: IApiOperation = {
responses: {},
summary: 'Operation 2',
};
@ApiInfo(infoMetadata)
class ApiController {
@Post('/bar')
@ApiOperation(operation1)
bar() {}
@Get('/foo')
@ApiOperation(operation2)
foo() {}
barfoo() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
deepStrictEqual(openApi.getDocument(ApiController).paths, {
'/bar': {
post: operation1
},
'/foo': {
get: operation2
},
});
});
it('with the paths and operations of the sub controllers methods.', () => {
const operation1: IApiOperation = {
responses: {},
summary: 'Operation 1',
};
const operation2: IApiOperation = {
responses: {},
summary: 'Operation 2',
};
const operation3: IApiOperation = {
responses: {},
summary: 'Operation 3',
};
class ProductController {
@Get()
@ApiOperation(operation3)
index() {}
}
class UserController {
subControllers = [
controller('/products', ProductController),
];
@Post('/foo')
@ApiOperation(operation2)
foo() {}
}
@ApiInfo(infoMetadata)
class ApiController {
subControllers = [
controller('/users', UserController),
];
@Post('/bar')
@ApiOperation(operation1)
bar() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
deepStrictEqual(openApi.getDocument(ApiController).paths, {
'/bar': {
post: operation1
},
'/users/foo': {
post: operation2
},
'/users/products': {
get: operation3
},
});
});
it('with the paths with the proper OpenAPI path templating.', () => {
const operation1: IApiOperation = {
responses: {},
summary: 'Operation 1',
};
const operation2: IApiOperation = {
responses: {},
summary: 'Operation 2',
};
const operation3: IApiOperation = {
responses: {},
summary: 'Operation 3',
};
const operation4: IApiOperation = {
responses: {},
summary: 'Operation 4',
};
class BoxController {
@Get('/:boxId')
@ApiOperation(operation4)
readBox() {}
}
@ApiInfo(infoMetadata)
class ApiController {
subControllers = [
controller('/boxes', BoxController)
];
@Get()
@ApiOperation(operation1)
index() {}
@Get('foo')
@ApiOperation(operation2)
foo() {}
@Get('/users/:userId/products/:productId')
@ApiOperation(operation3)
bar() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
deepStrictEqual(openApi.getDocument(ApiController).paths, {
'/': {
get: operation1
},
'/boxes/{boxId}': {
get: operation4
},
'/foo': {
get: operation2
},
'/users/{userId}/products/{productId}': {
get: operation3
},
});
});
it('while gathering several operations (POST, GET, etc) under the same path.', () => {
const operation1: IApiOperation = {
responses: {},
summary: 'Operation 1',
};
const operation2: IApiOperation = {
responses: {},
summary: 'Operation 2',
};
const operation3: IApiOperation = {
responses: {},
summary: 'Operation 3',
};
const operation4: IApiOperation = {
responses: {},
summary: 'Operation 4',
};
@ApiInfo(infoMetadata)
class ApiController {
subControllers = [
SubController1, SubController2
];
@Get('/foo')
@ApiOperation(operation1)
foo() {}
@Post('/foo')
@ApiOperation(operation2)
foo2() {}
}
class SubController1 {
@Get('/bar')
@ApiOperation(operation3)
foobar() {}
}
class SubController2 {
@Post('/bar')
@ApiOperation(operation4)
foobar() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
deepStrictEqual(openApi.getDocument(ApiController).paths, {
'/bar': {
get: operation3,
post: operation4,
},
'/foo': {
get: operation1,
post: operation2
},
});
});
it('with the operations completed with the operation pieces defined in the sub-controllers.', () => {
const response: IApiResponse = { description: 'Unauthorized' };
const parameter: IApiParameter = { in: 'cookie', name: 'foo' };
@ApiInfo(infoMetadata)
@ApiResponse(401, response)
class ApiController {
subControllers = [
SubController
];
@Post('/barfoo')
@ApiUseTag('tag3')
barfoo() {}
}
@ApiParameter(parameter)
@ApiDeprecated()
@ApiUseTag('tag1')
class SubController {
subControllers = [
SubSubController
];
}
@ApiUseTag('tag3')
class SubSubController {
@Get('/foo')
@ApiUseTag('tag2')
foo() {}
@Post('/bar')
@ApiDeprecated(false)
bar() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
deepStrictEqual(openApi.getDocument(ApiController).paths, {
'/bar': {
post: {
deprecated: false,
parameters: [
parameter
],
responses: {
401: response
},
tags: [ 'tag1', 'tag3' ]
}
},
'/barfoo': {
post: {
responses: {
401: response
},
tags: [ 'tag3' ]
}
},
'/foo': {
get: {
deprecated: true,
parameters: [
parameter
],
responses: {
401: response
},
tags: [ 'tag1', 'tag3', 'tag2' ]
},
}
} as IApiPaths);
});
it('but with not the root servers, security requirements and externalDocs in the paths.', () => {
const server: IApiServer = { url: 'http://example.com' };
const externalDocs: IApiExternalDocumentation = { url: 'http://example.com/docs' };
const securityRequirement: IApiSecurityRequirement = { a: [ 'b' ] };
@ApiInfo(infoMetadata)
@ApiServer(server)
@ApiExternalDoc(externalDocs)
@ApiSecurityRequirement(securityRequirement)
class ApiController {
@Get('/foo')
foo() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
const document = openApi.getDocument(ApiController);
deepStrictEqual(document.servers, [ server ]);
deepStrictEqual(document.externalDocs, externalDocs);
deepStrictEqual(document.security, [ securityRequirement ]);
deepStrictEqual(document.paths, {
'/foo': {
get: {
responses: {}
}
}
});
});
it('with the components of the sub-controllers and sub-controllers methods if they exist.', () => {
const callback1: IApiCallback = { a: { $ref: '1' } };
const callback2: IApiCallback = { a: { $ref: '2' } };
const callback2bis: IApiCallback = { a: { $ref: '2bis' } };
const callback3: IApiCallback = { a: { $ref: '3' } };
const callback4: IApiCallback = { a: { $ref: '4' } };
const callback5: IApiCallback = { a: { $ref: '5' } };
const callback6: IApiCallback = { a: { $ref: '6' } };
const callback7: IApiCallback = { a: { $ref: '7' } };
@ApiInfo(infoMetadata)
@ApiDefineCallback('callback1', callback1)
class ApiController {
subControllers = [
SubController
];
@Get('/bar')
@ApiDefineCallback('callback2', callback2)
bar() {}
@Get('/bar2')
@ApiDefineCallback('callback2bis', callback2bis)
bar2() {}
}
@ApiDefineCallback('callback3', callback3)
@ApiDefineCallback('callback4', callback4)
class SubController {
subControllers = [
SubSubController
];
}
@ApiDefineCallback('callback5', callback5)
class SubSubController {
@Get('/foo')
@ApiDefineCallback('callback6', callback6)
foo() {}
@Get('/foo2')
@ApiDefineCallback('callback7', callback7)
foo2() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
deepStrictEqual(openApi.getDocument(ApiController).components, {
callbacks: {
callback1,
callback2,
callback2bis,
callback3,
callback4,
callback5,
callback6,
callback7,
}
});
});
it('with the tags of the sub-controllers and sub-controllers methods if they exist.', () => {
const tag1: IApiTag = { name: '1' };
const tag2bis: IApiTag = { name: '2bis' };
const tag2: IApiTag = { name: '2' };
const tag3: IApiTag = { name: '3' };
const tag4: IApiTag = { name: '4' };
const tag5: IApiTag = { name: '5' };
const tag6: IApiTag = { name: '6' };
const tag7: IApiTag = { name: '7' };
@ApiInfo(infoMetadata)
@ApiDefineTag(tag1)
class ApiController {
subControllers = [
SubController
];
@Get('/bar')
@ApiDefineTag(tag2)
bar() {}
@Get('/bar2')
@ApiDefineTag(tag2bis)
bar2() {}
}
@ApiDefineTag(tag3)
@ApiDefineTag(tag4)
class SubController {
subControllers = [
SubSubController
];
}
@ApiDefineTag(tag5)
class SubSubController {
@Get('/foo')
@ApiDefineTag(tag6)
foo() {}
@Get('/foo2')
@ApiDefineTag(tag7)
foo2() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
deepStrictEqual(openApi.getDocument(ApiController).tags, [
tag1, tag3, tag4, tag5, tag6, tag7, tag2, tag2bis
]);
});
it('and should throw an Error is some paths are duplicated.', done => {
@ApiInfo(infoMetadata)
class ApiController {
@Get('/api/users/:userId/products/:productId')
something() {}
// Note that there is no beginning slash for the test.
@Get('api/users/:userId2/products/:productId2')
something2() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
try {
Array.from(makeControllerRoutes(AppController, services));
done(new Error('The function should have thrown an Error.'));
} catch (error) {
strictEqual(
error.message,
'[OpenAPI] Templated paths with the same hierarchy but different '
+ 'templated names MUST NOT exist as they are identical.'
+ '\n Path 1: /api/users/{userId}/products/{productId}'
+ '\n Path 2: /api/users/{userId2}/products/{productId2}'
);
done();
}
});
it('and should not throw a "duplicate path" error on similar but different paths.', () => {
@ApiInfo(infoMetadata)
class ApiController {
@Get('/api/users/:userId')
something() {}
@Get('/api/users/:userId/products/:productId2')
something2() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
doesNotThrow(() => Array.from(makeControllerRoutes(AppController, services)));
});
it('and should use the controller instances to retreive the dynamic metadata.', () => {
@ApiRequestBody(controller => controller.requestBody)
@ApiDefineCallback('callback1', controller => controller.callback)
class SubController {
requestBody: IApiRequestBody = {
content: {
'application/xml': {}
}
};
callback: IApiCallback = {
a: { $ref: 'foobar' }
};
@Post('/bar')
bar() {}
}
@ApiInfo(infoMetadata)
@ApiRequestBody(controller => controller.requestBody2)
@ApiDefineCallback('callback2', controller => controller.callback2)
class ApiController {
subControllers = [ SubController ];
requestBody: IApiRequestBody = {
content: {
'application/json': {}
}
};
requestBody2: IApiRequestBody = {
content: {
'application/json': {
schema: {}
}
}
};
callback2: IApiCallback = {
b: { $ref: 'foobar' }
};
callback3: IApiCallback = {
c: { $ref: 'foobar' }
};
@Get('/foo')
@ApiRequestBody(controller => controller.requestBody)
@ApiDefineCallback('callback3', controller => controller.callback3)
foo() {}
@Get('/barfoo')
barfoo() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
Array.from(makeControllerRoutes(AppController, services));
const document = openApi.getDocument(ApiController);
deepStrictEqual(document.paths, {
'/bar': {
post: {
requestBody: {
content: {
'application/xml': {}
}
},
responses: {}
}
},
'/barfoo': {
get: {
requestBody: {
content: {
'application/json': { schema: {} }
}
},
responses: {}
}
},
'/foo': {
get: {
requestBody: {
content: {
'application/json': {}
}
},
responses: {}
}
}
});
deepStrictEqual(document.components, {
callbacks: {
callback1: {
a: { $ref: 'foobar' }
},
callback2: {
b: { $ref: 'foobar' }
},
callback3: {
c: { $ref: 'foobar' }
}
}
});
});
it('with the controller instances.', () => {
@ApiDefineCallback('callback2', { $ref: '$ref2' })
class UserController {
@Get('/foobar')
foobar() {}
}
// This controller does not have its own routes but
// it may have a controller hook that uses the OpenAPI component.
@ApiInfo(infoMetadata)
@ApiDefineCallback('callback1', { $ref: '$ref1' })
class ApiController {
subControllers = [
controller('/users', UserController)
];
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
}
const array = Array.from(makeControllerRoutes(AppController, services));
strictEqual(array.length, 1);
const components: IApiComponents = {
callbacks: {
callback1: { $ref: '$ref1' },
callback2: { $ref: '$ref2' },
}
};
const openApi = services.get(OpenApi);
const appController = services.get(AppController);
const apiController = services.get(ApiController);
const userController = services.get(UserController);
deepStrictEqual(openApi.getComponents(apiController), components);
deepStrictEqual(openApi.getComponents(userController), components);
deepStrictEqual(openApi.getComponents(appController), {});
});
});
it('should not yield the controller tags, components or operation if it is not part of an OpenAPI API.', () => {
@ApiDefineTag({ name: 'tag1' })
@ApiDefineCallback('callback1', { $ref: 'ref1' })
@ApiOperationDescription('description1')
class UserController {
@Get('/something')
something() {}
}
@ApiInfo({
title: 'foo',
version: '0.0.0'
})
class ApiController {
subControllers = [
controller('/users', UserController)
];
@Get('/bar')
@ApiDefineTag({ name: 'bartag' })
@ApiDefineCallback('barcallback', { $ref: 'barref' })
@ApiOperationDescription('bardescription')
bar() {}
}
class AppController {
subControllers = [
controller('/api', ApiController)
];
@Get('/foo')
@ApiDefineTag({ name: 'footag' })
@ApiDefineCallback('foocallback', { $ref: 'fooref' })
@ApiOperationDescription('foodescription')
foo() {}
}
for (const { tags, components, operation } of makeControllerRoutes(AppController, new ServiceManager())) {
strictEqual(tags, undefined);
deepStrictEqual(components, {});
deepStrictEqual(operation, { responses: {} });
}
for (const { tags, components, operation } of makeControllerRoutes(ApiController, new ServiceManager())) {
notStrictEqual(tags, undefined);
notDeepStrictEqual(components, {});
notDeepStrictEqual(operation, { responses: {} });
}
});
}); | the_stack |
import {expect, toJSON} from '@loopback/testlab';
import {
CrudFeatures,
CrudRepositoryCtor,
CrudTestContext,
DataSourceOptions,
} from '../../..';
import {
deleteAllModelsInDefaultDataSource,
MixedIdType,
withCrudCtx,
} from '../../../helpers.repository-tests';
import {
CartItem,
CartItemRepository,
Customer,
CustomerCartItemLink,
CustomerCartItemLinkRepository,
CustomerRepository,
User,
UserRepository,
UserLink,
UserLinkRepository,
} from '../fixtures/models';
import {givenBoundCrudRepositories} from '../helpers';
export function hasManyThroughRelationAcceptance(
dataSourceOptions: DataSourceOptions,
repositoryClass: CrudRepositoryCtor,
features: CrudFeatures,
) {
describe('HasManyThrough relation (acceptance)', () => {
before(deleteAllModelsInDefaultDataSource);
let customerRepo: CustomerRepository;
let cartItemRepo: CartItemRepository;
let customerCartItemLinkRepo: CustomerCartItemLinkRepository;
let existingCustomerId: MixedIdType;
before(
withCrudCtx(async function setupRepository(ctx: CrudTestContext) {
({customerRepo, cartItemRepo, customerCartItemLinkRepo} =
givenBoundCrudRepositories(
ctx.dataSource,
repositoryClass,
features,
));
await ctx.dataSource.automigrate([
Customer.name,
CartItem.name,
CustomerCartItemLink.name,
]);
}),
);
beforeEach(async () => {
await customerRepo.deleteAll();
await cartItemRepo.deleteAll();
await customerCartItemLinkRepo.deleteAll();
});
beforeEach(async () => {
existingCustomerId = (await givenPersistedCustomerInstance()).id;
});
it('creates an instance of the related model alone with a through model', async () => {
const item = await customerRepo
.cartItems(existingCustomerId)
.create(
{description: 'an item'},
{throughData: {description: 'a through model'}},
);
expect(toJSON(item)).containDeep(
toJSON({
id: item.id,
description: 'an item',
}),
);
const persistedItem = await cartItemRepo.findById(item.id);
expect(toJSON(persistedItem)).to.deepEqual(toJSON(item));
const persistedLink = await customerCartItemLinkRepo.find();
expect(toJSON(persistedLink[0])).to.containDeep(
toJSON({
customerId: existingCustomerId,
cartItemId: item.id,
description: 'a through model',
}),
);
});
it('finds instances of the related model', async () => {
const item = await customerRepo
.cartItems(existingCustomerId)
.create(
{description: 'an item'},
{throughData: {description: 'a through model'}},
);
const notMyItem = await cartItemRepo.create({
description: "someone else's item",
});
const result = await customerRepo.cartItems(existingCustomerId).find();
expect(toJSON(result)).to.containDeep(toJSON([item]));
expect(toJSON(result[0])).to.not.containEql(toJSON(notMyItem));
});
it('patches instances', async () => {
const item1 = await customerRepo
.cartItems(existingCustomerId)
.create({description: 'group 1'});
const item2 = await customerRepo
.cartItems(existingCustomerId)
.create({description: 'group 1'});
const count = await customerRepo
.cartItems(existingCustomerId)
.patch({description: 'updated'});
expect(count.count).to.equal(2);
const result = await customerRepo.cartItems(existingCustomerId).find();
expect(toJSON(result)).to.containDeep(
toJSON([
{id: item1.id, description: 'updated'},
{id: item2.id, description: 'updated'},
]),
);
});
it('patches an instance based on the filter', async () => {
const item1 = await customerRepo
.cartItems(existingCustomerId)
.create({description: 'group 1'});
const item2 = await customerRepo
.cartItems(existingCustomerId)
.create({description: 'group 1'});
const count = await customerRepo
.cartItems(existingCustomerId)
.patch({description: 'group 2'}, {id: item2.id});
expect(count.count).to.equal(1);
const result = await customerRepo.cartItems(existingCustomerId).find();
expect(toJSON(result)).to.containDeep(
toJSON([
{id: item1.id, description: 'group 1'},
{id: item2.id, description: 'group 2'},
]),
);
});
it('throws error when query tries to change the target id', async () => {
// a diff id for CartItem instance
const anotherId = (await givenPersistedCustomerInstance()).id;
await customerRepo
.cartItems(existingCustomerId)
.create({description: 'group 1'});
await expect(
customerRepo.cartItems(existingCustomerId).patch({id: anotherId}),
).to.be.rejectedWith(/Property "id" cannot be changed!/);
});
it('deletes many instances and their through models', async () => {
await customerRepo
.cartItems(existingCustomerId)
.create({description: 'group 1'});
await customerRepo
.cartItems(existingCustomerId)
.create({description: 'group 1'});
let links = await customerCartItemLinkRepo.find();
let cartItems = await cartItemRepo.find();
expect(links).have.length(2);
expect(cartItems).have.length(2);
await customerRepo.cartItems(existingCustomerId).delete();
links = await customerCartItemLinkRepo.find();
cartItems = await cartItemRepo.find();
expect(links).have.length(0);
expect(cartItems).have.length(0);
});
it('deletes corresponding through models when the target gets deleted', async () => {
const item = await customerRepo
.cartItems(existingCustomerId)
.create({description: 'group 1'});
const anotherId = (await givenPersistedCustomerInstance()).id;
// another through model that links to the same item
await customerCartItemLinkRepo.create({
customerId: anotherId,
cartItemId: item.id,
});
let links = await customerCartItemLinkRepo.find();
let cartItems = await cartItemRepo.find();
expect(links).have.length(2);
expect(cartItems).have.length(1);
await customerRepo.cartItems(existingCustomerId).delete();
links = await customerCartItemLinkRepo.find();
cartItems = await cartItemRepo.find();
expect(links).have.length(0);
expect(cartItems).have.length(0);
});
it('deletes instances based on the filter', async () => {
const item1 = await customerRepo
.cartItems(existingCustomerId)
.create({description: 'group 1'});
await customerRepo
.cartItems(existingCustomerId)
.create({description: 'group 2'});
let links = await customerCartItemLinkRepo.find();
let cartItems = await cartItemRepo.find();
expect(links).have.length(2);
expect(cartItems).have.length(2);
await customerRepo
.cartItems(existingCustomerId)
.delete({description: 'does not exist'});
links = await customerCartItemLinkRepo.find();
cartItems = await cartItemRepo.find();
expect(links).have.length(2);
expect(cartItems).have.length(2);
await customerRepo
.cartItems(existingCustomerId)
.delete({description: 'group 2'});
links = await customerCartItemLinkRepo.find();
cartItems = await cartItemRepo.find();
expect(links).have.length(1);
expect(toJSON(cartItems)).to.containDeep(
toJSON([{id: item1.id, description: 'group 1'}]),
);
});
it('links a target model to a source model', async () => {
const item = await cartItemRepo.create({description: 'an item'});
let targets = await customerRepo.cartItems(existingCustomerId).find();
expect(targets).to.be.empty();
await customerRepo.cartItems(existingCustomerId).link(item.id);
targets = await customerRepo.cartItems(existingCustomerId).find();
expect(targets).to.deepEqual([item]);
const link = await customerCartItemLinkRepo.find();
expect(toJSON(link[0])).to.containEql(
toJSON({customerId: existingCustomerId, cartItemId: item.id}),
);
});
it('unlinks a target model from a source model', async () => {
const item = await customerRepo
.cartItems(existingCustomerId)
.create({description: 'an item'});
let targets = await customerRepo.cartItems(existingCustomerId).find();
expect(targets).to.deepEqual([item]);
await customerRepo.cartItems(existingCustomerId).unlink(item.id);
targets = await customerRepo.cartItems(existingCustomerId).find();
expect(targets).to.be.empty();
const link = await customerCartItemLinkRepo.find();
expect(link).to.be.empty();
});
async function givenPersistedCustomerInstance() {
return customerRepo.create({name: 'a customer'});
}
});
describe('HasManyThrough relation - self through', () => {
before(deleteAllModelsInDefaultDataSource);
let userRepo: UserRepository;
let userLinkRepo: UserLinkRepository;
let existedUserId: MixedIdType;
before(
withCrudCtx(async function setupRepository(ctx: CrudTestContext) {
({userRepo, userLinkRepo} = givenBoundCrudRepositories(
ctx.dataSource,
repositoryClass,
features,
));
await ctx.dataSource.automigrate([User.name, UserLink.name]);
}),
);
beforeEach(async () => {
await userRepo.deleteAll();
await userLinkRepo.deleteAll();
});
beforeEach(async () => {
existedUserId = (await givenPersistedUserInstance()).id;
});
it('creates instances of self model', async () => {
const followed = await userRepo
.users(existedUserId)
.create(
{name: 'another user'},
{throughData: {description: 'a through model - UserLink'}},
);
const persistedUser = await userRepo.findById(followed.id);
const persistedLink = await userLinkRepo.find();
expect(toJSON(persistedUser)).to.containDeep(toJSON(followed));
expect(toJSON(persistedLink[0])).to.containDeep(
toJSON({
followerId: existedUserId,
followeeId: followed.id,
description: 'a through model - UserLink',
}),
);
});
it('finds an instance of self model alone with a through model', async () => {
const followed = await userRepo
.users(existedUserId)
.create(
{name: 'another user'},
{throughData: {description: 'a through model - UserLink'}},
);
const notFollowed = await userRepo.create({
name: 'not being followed',
});
const persistedUser = await userRepo.users(existedUserId).find();
const persistedLink = await userLinkRepo.find();
expect(toJSON(persistedUser[0])).to.deepEqual(toJSON(followed));
expect(toJSON(persistedUser[0])).to.not.containEql(toJSON(notFollowed));
expect(toJSON(persistedLink)).to.containDeep(
toJSON([
{
followerId: existedUserId,
followeeId: followed.id,
description: 'a through model - UserLink',
},
]),
);
});
it('finds instances of self model', async () => {
const u1 = await userRepo.create({name: 'u1'});
const u2 = await userRepo.create({name: 'u2'});
const u3 = await userRepo.create({name: 'u3'});
await userRepo.users(u1.id).link(u2.id);
await userRepo.users(u1.id).link(u3.id);
await userRepo.users(u3.id).link(u1.id);
const u1Following = await userRepo.users(u1.id).find();
const u2Following = await userRepo.users(u2.id).find();
const u3Following = await userRepo.users(u3.id).find();
expect(toJSON(u1Following)).to.deepEqual(toJSON([u2, u3]));
expect(toJSON(u2Following)).to.deepEqual(toJSON([]));
expect(toJSON(u3Following)).to.not.containEql(toJSON([u1]));
const persistedLink = await userLinkRepo.find();
expect(persistedLink.length).to.equal(3);
});
async function givenPersistedUserInstance() {
return userRepo.create({name: 'a user'});
}
});
} | the_stack |
'use strict';
import * as assert from 'assert';
import { ReactWrapper } from 'enzyme';
import * as path from 'path';
import * as React from 'react';
import { Provider } from 'react-redux';
import { EXTENSION_ROOT_DIR } from '../../client/common/constants';
import { InteractiveWindowMessages } from '../../client/datascience/interactive-common/interactiveWindowTypes';
import { CommonActionType } from '../../datascience-ui/interactive-common/redux/reducers/types';
import { IKeyboardEvent } from '../../datascience-ui/react-common/event';
import { ImageButton } from '../../datascience-ui/react-common/imageButton';
import { noop } from '../core';
import { DataScienceIocContainer } from './dataScienceIocContainer';
import { IMountedWebView } from './mountedWebView';
import { createInputEvent, createKeyboardEvent } from './reactHelpers';
export * from './testHelpersCore';
/* eslint-disable comma-dangle, @typescript-eslint/no-explicit-any, no-multi-str */
export enum CellInputState {
Hidden,
Visible,
Collapsed,
Expanded
}
export enum CellPosition {
First = 'first',
Last = 'last'
}
export function addMockData(
ioc: DataScienceIocContainer,
code: string,
result: string | number | undefined | string[],
mimeType?: string | string[],
cellType?: string,
traceback?: string[]
) {
if (ioc.mockJupyter) {
if (cellType && cellType === 'error') {
ioc.mockJupyter.addError(code, result ? result.toString() : '', traceback);
} else {
if (result) {
ioc.mockJupyter.addCell(code, result, mimeType);
} else {
ioc.mockJupyter.addCell(code);
}
}
}
}
// export function addInputMockData(
// ioc: DataScienceIocContainer,
// code: string,
// result: string | number | undefined,
// mimeType?: string,
// cellType?: string
// ) {
// if (ioc.mockJupyter) {
// if (cellType && cellType === 'error') {
// ioc.mockJupyter.addError(code, result ? result.toString() : '');
// } else {
// if (result) {
// ioc.mockJupyter.addInputCell(code, result, mimeType);
// } else {
// ioc.mockJupyter.addInputCell(code);
// }
// }
// }
// }
// export function addContinuousMockData(
// ioc: DataScienceIocContainer,
// code: string,
// resultGenerator: (c: CancellationToken) => Promise<{ result: string; haveMore: boolean }>
// ) {
// if (ioc.mockJupyter) {
// ioc.mockJupyter.addContinuousOutputCell(code, resultGenerator);
// }
// }
export function verifyServerStatus(wrapper: ReactWrapper<any, Readonly<{}>, React.Component>, statusText: string) {
wrapper.update();
const foundResult = wrapper.find('div.kernel-status-server');
assert.ok(foundResult.length >= 1, "Didn't find server status");
const html = foundResult.html();
assert.ok(html.includes(statusText), `${statusText} not found in server status`);
}
/**
* Creates a keyboard event for a cells.
*
* @export
* @param {(Partial<IKeyboardEvent> & { code: string })} event
* @returns
*/
export function createKeyboardEventForCell(event: Partial<IKeyboardEvent> & { code: string }) {
const defaultKeyboardEvent: IKeyboardEvent = {
altKey: false,
code: '',
ctrlKey: false,
editorInfo: {
contents: '',
isDirty: false,
isFirstLine: false,
isLastLine: false,
isSuggesting: false,
clear: noop
},
metaKey: false,
preventDefault: noop,
shiftKey: false,
stopPropagation: noop,
target: {} as any
};
const defaultEditorInfo = defaultKeyboardEvent.editorInfo!;
const providedEditorInfo = event.editorInfo || {};
return {
...defaultKeyboardEvent,
...event,
editorInfo: {
...defaultEditorInfo,
...providedEditorInfo
}
};
}
export function simulateKey(
domNode: HTMLTextAreaElement,
key: string,
code: string,
shiftDown?: boolean,
ctrlKey?: boolean,
altKey?: boolean,
metaKey?: boolean
) {
// Submit a keypress into the textarea. Simulate doesn't work here because the keydown
// handler is not registered in any react code. It's being handled with DOM events
// Save current selection start so we move appropriately after the event
const selectionStart = domNode.selectionStart;
// According to this:
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Usage_notes
// The normal events are
// 1) keydown
// 2) keypress
// 3) keyup
let event = createKeyboardEvent('keydown', { key, code, shiftKey: shiftDown, ctrlKey, altKey, metaKey });
// Dispatch. Result can be swallowed. If so skip the next event.
let result = domNode.dispatchEvent(event);
if (result) {
event = createKeyboardEvent('keypress', { key, code, shiftKey: shiftDown, ctrlKey, altKey, metaKey });
result = domNode.dispatchEvent(event);
if (result) {
event = createKeyboardEvent('keyup', { key, code, shiftKey: shiftDown, ctrlKey, altKey, metaKey });
domNode.dispatchEvent(event);
// Update our value. This will reset selection to zero.
const before = domNode.value.slice(0, selectionStart);
const after = domNode.value.slice(selectionStart);
const keyText = key;
if (key === '\b') {
domNode.value = `${before.slice(0, before.length > 0 ? before.length - 1 : 0)}${after}`;
} else {
domNode.value = `${before}${keyText}${after}`;
}
// Tell the dom node its selection start has changed. Monaco
// reads this to determine where the character went.
domNode.selectionEnd = selectionStart + 1;
domNode.selectionStart = selectionStart + 1;
// Dispatch an input event so we update the textarea
domNode.dispatchEvent(createInputEvent());
}
}
}
export async function submitInput(mountedWebView: IMountedWebView, textArea: HTMLTextAreaElement): Promise<void> {
// Get a render promise with the expected number of renders (how many updates a the shift + enter will cause)
// Should be 6 - 1 for the shift+enter and 5 for the new cell.
const renderPromise = mountedWebView.waitForMessage(InteractiveWindowMessages.ExecutionRendered);
// Submit a keypress into the textarea
simulateKey(textArea, '\n', 'Enter', true);
return renderPromise;
}
function enterKey(
textArea: HTMLTextAreaElement,
key: string,
code: string,
shiftDown?: boolean,
ctrlKey?: boolean,
altKey?: boolean,
metaKey?: boolean
) {
// Simulate a key press
simulateKey(textArea, key, code, shiftDown, ctrlKey, altKey, metaKey);
}
export function enterEditorKey(
editorControl: ReactWrapper<any, Readonly<{}>, React.Component> | undefined,
keyboardEvent: Partial<IKeyboardEvent> & { code: string }
): HTMLTextAreaElement | null {
const textArea = getTextArea(editorControl);
assert.ok(textArea!, 'Cannot find the textarea inside the monaco editor');
textArea!.focus();
enterKey(
textArea!,
keyboardEvent.code,
keyboardEvent.code,
keyboardEvent.shiftKey,
keyboardEvent.ctrlKey,
keyboardEvent.altKey,
keyboardEvent.metaKey
);
return textArea;
}
export function typeCode(
editorControl: ReactWrapper<any, Readonly<{}>, React.Component> | undefined,
code: string
): HTMLTextAreaElement | null {
const textArea = getTextArea(editorControl);
assert.ok(textArea!, 'Cannot find the textarea inside the monaco editor');
textArea!.focus();
// Now simulate entering all of the keys
for (let i = 0; i < code.length; i += 1) {
let key = code.charAt(i);
let keyCode = key;
if (key === '\n') {
keyCode = 'Enter';
} else if (key === '\b') {
keyCode = 'Backspace';
} else if (key === '\u0046') {
keyCode = 'Delete';
}
enterKey(textArea!, key, keyCode);
}
return textArea;
}
function getTextArea(
editorControl: ReactWrapper<any, Readonly<{}>, React.Component> | undefined
): HTMLTextAreaElement | null {
// Find the last cell. It should have a monacoEditor object. We need to search
// through its DOM to find the actual textarea to send input to
// (we can't actually find it with the enzyme wrappers because they only search
// React accessible nodes and the monaco html is not react)
assert.ok(editorControl, 'Editor not defined in order to type code into');
let ecDom = editorControl!.getDOMNode();
if ((ecDom as any).length) {
ecDom = (ecDom as any)[0];
}
assert.ok(ecDom, 'ec DOM object not found');
return ecDom!.querySelector('.overflow-guard')!.querySelector('textarea');
}
export function findButton(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
mainClass: React.ComponentClass<any>,
index: number
): ReactWrapper<any, Readonly<{}>, React.Component> | undefined {
const mainObj = wrapper.find(mainClass);
if (mainObj) {
const buttons = mainObj.find(ImageButton);
if (buttons) {
return buttons.at(index);
}
}
}
export function getMainPanel<P>(
wrapper: ReactWrapper<any, Readonly<{}>>,
mainClass: React.ComponentClass<any>
): P | undefined {
const mainObj = wrapper.find(mainClass);
if (mainObj) {
return (mainObj.instance() as any) as P;
}
return undefined;
}
export function escapePath(p: string) {
return p.replace(/\\/g, '\\\\');
}
export function srcDirectory() {
return path.join(EXTENSION_ROOT_DIR, 'src', 'test', 'datascience');
}
// Open up our variable explorer which also triggers a data fetch
export function openVariableExplorer(wrapper: ReactWrapper<any, Readonly<{}>, React.Component>) {
const nodes = wrapper.find(Provider);
if (nodes.length > 0) {
const store = nodes.at(0).props().store;
if (store) {
store.dispatch({ type: CommonActionType.TOGGLE_VARIABLE_EXPLORER });
}
}
}
export async function waitForVariablesUpdated(mountedWebView: IMountedWebView, numberOfTimes?: number): Promise<void> {
return mountedWebView.waitForMessage(InteractiveWindowMessages.VariablesComplete, { numberOfTimes });
} | the_stack |
* call asynchronously on a 'server' and receive the result
* back via a callback.
*/
export interface Client {
/** Invoke an RPC call and invoke callback with the results.
* The values in the arguments array are passed to handler registered
* with Server.on() for the given method.
*
* The optional timeout specifies the time interval within which
* a reply should be received if @p callback is specified.
*
* If no reply is received within the timeout, @p callback is invoked
* with a timeout error. If @p timeout is null, a default timeout
* is used.
*/
call<R>(
method: string,
args: any[],
callback?: (err: any, result: R) => void,
timeout?: number
): void;
}
/** Provides an interface for handling an RPC call.
*/
export interface Server {
/** Register a synchronous RPC handler. If a client runs Client.call() with
* a matching the method name, @p handler will be invoked with the supplied
* arguments. Any exception thrown will be converted to an error returned
* via the callback passed to Client.call()
*/
on<R>(method: string, handler: (...args: any[]) => R): void;
/** Register an async RPC handler. This is similar to on() except that
* instead of returning a value or throwing an exception, onAsync()
* should call done() with the error or result when finished.
*
* If the handler throws an exception directly, that is equivalent to
* calling done() with the exception.
*/
onAsync<R>(
method: string,
handler: (done: (err: any, result: R) => void, ...args: any[]) => void
): void;
}
export interface Message {
id: number;
method: string;
}
export interface CallMessage extends Message {
payload: any[];
}
export interface ReplyMessage extends Message {
err: any;
result: any;
}
/** Interface for sending and receiving messages to/from a remote
* object such as a window or web worker.
*/
export interface MessagePort<Call, Reply> {
on(method: string, handler: Function): void;
on(method: 'rpc-call', handler: (call: Call) => void): void;
on(method: 'rpc-reply', handler: (reply: Reply) => void): void;
emit(method: string, data: Object): void;
emit(method: 'rpc-call', data: Call): void;
emit(method: 'rpc-reply', data: Reply): void;
}
/** Subset of the DOM Window interface related to sending and receiving
* messages to/from other windows.
*/
export interface WindowMessageInterface {
addEventListener(
event: string,
handler: EventListenerOrEventListenerObject
): void;
addEventListener(
event: 'message',
handler: (ev: MessageEvent) => any
): void;
postMessage(message: any, targetOrigin: string): void;
}
/** A MessagePort implementation which uses the Window.postMessage() and
* Window.addEventListener() APIs for use with RpcHandler.
*
* A WindowMessagePort has a send-tag and a receive-tag.
* The send-tag is included with all messages emitted via emit().
*
* The port will only invoke handlers passed to on() if the message's
* tag matches the WindowMessagePort's receive-tag.
*/
export class WindowMessagePort {
constructor(
public window: WindowMessageInterface,
public targetOrigin: string,
public sendTag: string,
public receiveTag: string
) {}
on(method: string, handler: Function): void {
this.window.addEventListener('message', (ev: MessageEvent) => {
if (
typeof ev.data.rpcMethod !== 'undefined' &&
typeof ev.data.tag !== 'undefined' &&
ev.data.rpcMethod == method &&
ev.data.tag == this.receiveTag
) {
handler(ev.data.data);
}
});
}
emit(method: string, data: Object): void {
this.window.postMessage(
{
rpcMethod: method,
data: data,
tag: this.sendTag,
},
this.targetOrigin
);
}
}
export class WorkerMessagePort {
constructor(
public worker: Worker,
public sendTag: string,
public receiveTag: string
) {}
on(method: string, handler: Function) {
this.worker.addEventListener('message', (ev: MessageEvent) => {
if (
typeof ev.data.rpcMethod !== 'undefined' &&
typeof ev.data.tag !== 'undefined' &&
ev.data.rpcMethod == method &&
ev.data.tag == this.receiveTag
) {
handler(ev.data.data);
}
});
}
emit(method: string, data: Object) {
this.worker.postMessage({
rpcMethod: method,
data: data,
tag: this.sendTag,
});
}
}
export class ChromeMessagePort {
constructor(public targetTab?: number) {}
on(method: string, handler: Function): void {
chrome.runtime.onMessage.addListener((msg, sender) => {
if (typeof msg.rpcMethod !== 'string' || msg.rpcMethod != method) {
return;
}
if (this.targetTab) {
if (!sender.tab || sender.tab.id != this.targetTab) {
return;
}
}
handler(msg.data);
});
}
emit(method: string, data: Object): void {
var payload = {
rpcMethod: method,
data: data,
};
if (this.targetTab) {
chrome.tabs.sendMessage(this.targetTab, payload);
} else {
chrome.runtime.sendMessage(payload);
}
}
}
interface PendingRpcCall {
id: number;
method: string;
callback?: Function;
// ID of timeout timer to verify that RPC calls are replied
// to.
replyTimerId?: NodeJS.Timer | number;
}
/** Interface for object providing timer APIs, which may
* either be 'window' (in a browser context) or 'global' (in Node).
*/
interface Timers {
setTimeout(callback: () => void, ms: number): any;
clearTimeout(id: any): void;
}
/** Simple RPC implementation. RpcHandler implements both the
* client and server-sides of an RPC handler.
*/
export class RpcHandler implements Client, Server {
private id: number;
private pending: PendingRpcCall[];
private port: MessagePort<CallMessage, ReplyMessage>;
private handlers: {
method: string;
callback: (args: any) => any;
isAsync: boolean;
}[];
private timers: Timers;
/** A handler responsible for performing any special copying
* of method arguments or replies needed before the data
* is sent to the message port.
*/
clone: (data: any) => any;
/** Construct an RPC handler which uses @p port to send and receive
* messages to/from the other side of the connection.
*/
constructor(port: MessagePort<CallMessage, ReplyMessage>, timers?: Timers) {
this.port = port;
if (timers) {
this.timers = timers;
} else if (typeof window !== 'undefined') {
// default to using window.setTimeout() in browser
this.timers = window;
} else if (typeof global !== 'undefined') {
// default to global.setTimeout() in Node
this.timers = global;
}
this.id = 1;
this.handlers = [];
this.pending = [];
this.clone = data => {
return data;
};
this.port.on('rpc-reply', (reply: ReplyMessage) => {
var pending = this.pending.filter(pending => {
return pending.id == reply.id;
});
if (pending.length != 1) {
throw new Error(
'No matching RPC call found for method: ' + reply.method
);
}
if (pending[0].callback) {
pending[0].callback(reply.err, reply.result);
}
});
this.port.on('rpc-call', (call: CallMessage) => {
var handled = false;
this.handlers.forEach(handler => {
if (handler.method == call.method) {
var done = (err: any, result: any) => {
this.port.emit('rpc-reply', {
id: call.id,
method: call.method,
err: this.clone(err),
result: this.clone(result),
});
};
try {
if (handler.isAsync) {
handler.callback.apply(
null,
[done].concat(call.payload)
);
} else {
var result = handler.callback.apply(
null,
call.payload
);
done(null, result);
}
} catch (err) {
done(err, null);
}
handled = true;
}
});
if (!handled) {
throw new Error('No handler found for method: ' + call.method);
}
});
}
call<R>(
method: string,
args: any[],
callback?: (err: any, result: R) => void,
timeout?: number
) {
var call = {
id: ++this.id,
method: method,
payload: args,
};
var pending: PendingRpcCall = {
id: call.id,
method: method,
};
if (callback) {
timeout = timeout || 5000;
pending.callback = (err: any, result: R) => {
this.timers.clearTimeout(<number>pending.replyTimerId);
callback(err, result);
};
pending.replyTimerId = this.timers.setTimeout(() => {
callback(
new Error(
`RPC call ${method} did not receive a reply within ${
timeout
} ms`
),
null
);
console.warn(
'rpc-call %s did not receive a reply within %d ms',
method,
timeout
);
}, timeout);
}
this.pending.push(pending);
this.port.emit('rpc-call', call);
}
on<R>(method: string, handler: (...args: any[]) => R) {
this.handlers.push({
method: method,
callback: handler,
isAsync: false,
});
}
onAsync<R>(
method: string,
handler: (done: (err: any, result: R) => void, ...args: any[]) => void
) {
this.handlers.push({
method: method,
callback: handler,
isAsync: true,
});
}
} | the_stack |
declare module 'dgram' {
import { AddressInfo } from 'node:net';
import * as dns from 'node:dns';
import { EventEmitter, Abortable } from 'node:events';
interface RemoteInfo {
address: string;
family: 'IPv4' | 'IPv6';
port: number;
size: number;
}
interface BindOptions {
port?: number | undefined;
address?: string | undefined;
exclusive?: boolean | undefined;
fd?: number | undefined;
}
type SocketType = 'udp4' | 'udp6';
interface SocketOptions extends Abortable {
type: SocketType;
reuseAddr?: boolean | undefined;
/**
* @default false
*/
ipv6Only?: boolean | undefined;
recvBufferSize?: number | undefined;
sendBufferSize?: number | undefined;
lookup?: ((hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void) | undefined;
}
/**
* Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram
* messages. When `address` and `port` are not passed to `socket.bind()` the
* method will bind the socket to the "all interfaces" address on a random port
* (it does the right thing for both `udp4` and `udp6` sockets). The bound address
* and port can be retrieved using `socket.address().address` and `socket.address().port`.
*
* If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.close()` on the socket:
*
* ```js
* const controller = new AbortController();
* const { signal } = controller;
* const server = dgram.createSocket({ type: 'udp4', signal });
* server.on('message', (msg, rinfo) => {
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
* });
* // Later, when you want to close the server.
* controller.abort();
* ```
* @since v0.11.13
* @param options Available options are:
* @param callback Attached as a listener for `'message'` events. Optional.
*/
function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
/**
* Encapsulates the datagram functionality.
*
* New instances of `dgram.Socket` are created using {@link createSocket}.
* The `new` keyword is not to be used to create `dgram.Socket` instances.
* @since v0.1.99
*/
class Socket extends EventEmitter {
/**
* Tells the kernel to join a multicast group at the given `multicastAddress` and`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the`multicastInterface` argument is not
* specified, the operating system will choose
* one interface and will add membership to it. To add membership to every
* available interface, call `addMembership` multiple times, once per interface.
*
* When called on an unbound socket, this method will implicitly bind to a random
* port, listening on all interfaces.
*
* When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur:
*
* ```js
* const cluster = require('cluster');
* const dgram = require('dgram');
* if (cluster.isPrimary) {
* cluster.fork(); // Works ok.
* cluster.fork(); // Fails with EADDRINUSE.
* } else {
* const s = dgram.createSocket('udp4');
* s.bind(1234, () => {
* s.addMembership('224.0.0.114');
* });
* }
* ```
* @since v0.6.9
*/
addMembership(multicastAddress: string, multicastInterface?: string): void;
/**
* Returns an object containing the address information for a socket.
* For UDP sockets, this object will contain `address`, `family` and `port`properties.
*
* This method throws `EBADF` if called on an unbound socket.
* @since v0.1.99
*/
address(): AddressInfo;
/**
* For UDP sockets, causes the `dgram.Socket` to listen for datagram
* messages on a named `port` and optional `address`. If `port` is not
* specified or is `0`, the operating system will attempt to bind to a
* random port. If `address` is not specified, the operating system will
* attempt to listen on all addresses. Once binding is complete, a`'listening'` event is emitted and the optional `callback` function is
* called.
*
* Specifying both a `'listening'` event listener and passing a`callback` to the `socket.bind()` method is not harmful but not very
* useful.
*
* A bound datagram socket keeps the Node.js process running to receive
* datagram messages.
*
* If binding fails, an `'error'` event is generated. In rare case (e.g.
* attempting to bind with a closed socket), an `Error` may be thrown.
*
* Example of a UDP server listening on port 41234:
*
* ```js
* const dgram = require('dgram');
* const server = dgram.createSocket('udp4');
*
* server.on('error', (err) => {
* console.log(`server error:\n${err.stack}`);
* server.close();
* });
*
* server.on('message', (msg, rinfo) => {
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
* });
*
* server.on('listening', () => {
* const address = server.address();
* console.log(`server listening ${address.address}:${address.port}`);
* });
*
* server.bind(41234);
* // Prints: server listening 0.0.0.0:41234
* ```
* @since v0.1.99
* @param callback with no parameters. Called when binding is complete.
*/
bind(port?: number, address?: string, callback?: () => void): void;
bind(port?: number, callback?: () => void): void;
bind(callback?: () => void): void;
bind(options: BindOptions, callback?: () => void): void;
/**
* Close the underlying socket and stop listening for data on it. If a callback is
* provided, it is added as a listener for the `'close'` event.
* @since v0.1.99
* @param callback Called when the socket has been closed.
*/
close(callback?: () => void): void;
/**
* Associates the `dgram.Socket` to a remote address and port. Every
* message sent by this handle is automatically sent to that destination. Also,
* the socket will only receive messages from that remote peer.
* Trying to call `connect()` on an already connected socket will result
* in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not
* provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets)
* will be used by default. Once the connection is complete, a `'connect'` event
* is emitted and the optional `callback` function is called. In case of failure,
* the `callback` is called or, failing this, an `'error'` event is emitted.
* @since v12.0.0
* @param callback Called when the connection is completed or on error.
*/
connect(port: number, address?: string, callback?: () => void): void;
connect(port: number, callback: () => void): void;
/**
* A synchronous function that disassociates a connected `dgram.Socket` from
* its remote address. Trying to call `disconnect()` on an unbound or already
* disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception.
* @since v12.0.0
*/
disconnect(): void;
/**
* Instructs the kernel to leave a multicast group at `multicastAddress` using the`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the
* kernel when the socket is closed or the process terminates, so most apps will
* never have reason to call this.
*
* If `multicastInterface` is not specified, the operating system will attempt to
* drop membership on all valid interfaces.
* @since v0.6.9
*/
dropMembership(multicastAddress: string, multicastInterface?: string): void;
/**
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
* @since v8.7.0
* @return the `SO_RCVBUF` socket receive buffer size in bytes.
*/
getRecvBufferSize(): number;
/**
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
* @since v8.7.0
* @return the `SO_SNDBUF` socket send buffer size in bytes.
*/
getSendBufferSize(): number;
/**
* By default, binding a socket will cause it to block the Node.js process from
* exiting as long as the socket is open. The `socket.unref()` method can be used
* to exclude the socket from the reference counting that keeps the Node.js
* process active. The `socket.ref()` method adds the socket back to the reference
* counting and restores the default behavior.
*
* Calling `socket.ref()` multiples times will have no additional effect.
*
* The `socket.ref()` method returns a reference to the socket so calls can be
* chained.
* @since v0.9.1
*/
ref(): this;
/**
* Returns an object containing the `address`, `family`, and `port` of the remote
* endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception
* if the socket is not connected.
* @since v12.0.0
*/
remoteAddress(): AddressInfo;
/**
* Broadcasts a datagram on the socket.
* For connectionless sockets, the destination `port` and `address` must be
* specified. Connected sockets, on the other hand, will use their associated
* remote endpoint, so the `port` and `address` arguments must not be set.
*
* The `msg` argument contains the message to be sent.
* Depending on its type, different behavior can apply. If `msg` is a `Buffer`,
* any `TypedArray` or a `DataView`,
* the `offset` and `length` specify the offset within the `Buffer` where the
* message begins and the number of bytes in the message, respectively.
* If `msg` is a `String`, then it is automatically converted to a `Buffer`with `'utf8'` encoding. With messages that
* contain multi-byte characters, `offset` and `length` will be calculated with
* respect to `byte length` and not the character position.
* If `msg` is an array, `offset` and `length` must not be specified.
*
* The `address` argument is a string. If the value of `address` is a host name,
* DNS will be used to resolve the address of the host. If `address` is not
* provided or otherwise falsy, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default.
*
* If the socket has not been previously bound with a call to `bind`, the socket
* is assigned a random port number and is bound to the "all interfaces" address
* (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.)
*
* An optional `callback` function may be specified to as a way of reporting
* DNS errors or for determining when it is safe to reuse the `buf` object.
* DNS lookups delay the time to send for at least one tick of the
* Node.js event loop.
*
* The only way to know for sure that the datagram has been sent is by using a`callback`. If an error occurs and a `callback` is given, the error will be
* passed as the first argument to the `callback`. If a `callback` is not given,
* the error is emitted as an `'error'` event on the `socket` object.
*
* Offset and length are optional but both _must_ be set if either are used.
* They are supported only when the first argument is a `Buffer`, a `TypedArray`,
* or a `DataView`.
*
* This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket.
*
* Example of sending a UDP packet to a port on `localhost`;
*
* ```js
* const dgram = require('dgram');
* const message = Buffer.from('Some bytes');
* const client = dgram.createSocket('udp4');
* client.send(message, 41234, 'localhost', (err) => {
* client.close();
* });
* ```
*
* Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`;
*
* ```js
* const dgram = require('dgram');
* const buf1 = Buffer.from('Some ');
* const buf2 = Buffer.from('bytes');
* const client = dgram.createSocket('udp4');
* client.send([buf1, buf2], 41234, (err) => {
* client.close();
* });
* ```
*
* Sending multiple buffers might be faster or slower depending on the
* application and operating system. Run benchmarks to
* determine the optimal strategy on a case-by-case basis. Generally speaking,
* however, sending multiple buffers is faster.
*
* Example of sending a UDP packet using a socket connected to a port on`localhost`:
*
* ```js
* const dgram = require('dgram');
* const message = Buffer.from('Some bytes');
* const client = dgram.createSocket('udp4');
* client.connect(41234, 'localhost', (err) => {
* client.send(message, (err) => {
* client.close();
* });
* });
* ```
* @since v0.1.99
* @param msg Message to be sent.
* @param offset Offset in the buffer where the message starts.
* @param length Number of bytes in the message.
* @param port Destination port.
* @param address Destination host name or IP address.
* @param callback Called when the message has been sent.
*/
send(msg: string | Uint8Array | ReadonlyArray<any>, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array | ReadonlyArray<any>, port?: number, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array | ReadonlyArray<any>, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array, offset: number, length: number, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array, offset: number, length: number, port?: number, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array, offset: number, length: number, callback?: (error: Error | null, bytes: number) => void): void;
/**
* Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP
* packets may be sent to a local interface's broadcast address.
*
* This method throws `EBADF` if called on an unbound socket.
* @since v0.6.9
*/
setBroadcast(flag: boolean): void;
/**
* _All references to scope in this section are referring to[IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC
* 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_
* _with a scope index is written as `'IP%scope'` where scope is an interface name_
* _or interface number._
*
* Sets the default outgoing multicast interface of the socket to a chosen
* interface or back to system interface selection. The `multicastInterface` must
* be a valid string representation of an IP from the socket's family.
*
* For IPv4 sockets, this should be the IP configured for the desired physical
* interface. All packets sent to multicast on the socket will be sent on the
* interface determined by the most recent successful use of this call.
*
* For IPv6 sockets, `multicastInterface` should include a scope to indicate the
* interface as in the examples that follow. In IPv6, individual `send` calls can
* also use explicit scope in addresses, so only packets sent to a multicast
* address without specifying an explicit scope are affected by the most recent
* successful use of this call.
*
* This method throws `EBADF` if called on an unbound socket.
*
* #### Example: IPv6 outgoing multicast interface
*
* On most systems, where scope format uses the interface name:
*
* ```js
* const socket = dgram.createSocket('udp6');
*
* socket.bind(1234, () => {
* socket.setMulticastInterface('::%eth1');
* });
* ```
*
* On Windows, where scope format uses an interface number:
*
* ```js
* const socket = dgram.createSocket('udp6');
*
* socket.bind(1234, () => {
* socket.setMulticastInterface('::%2');
* });
* ```
*
* #### Example: IPv4 outgoing multicast interface
*
* All systems use an IP of the host on the desired physical interface:
*
* ```js
* const socket = dgram.createSocket('udp4');
*
* socket.bind(1234, () => {
* socket.setMulticastInterface('10.0.0.2');
* });
* ```
* @since v8.6.0
*/
setMulticastInterface(multicastInterface: string): void;
/**
* Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`,
* multicast packets will also be received on the local interface.
*
* This method throws `EBADF` if called on an unbound socket.
* @since v0.3.8
*/
setMulticastLoopback(flag: boolean): void;
/**
* Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for
* "Time to Live", in this context it specifies the number of IP hops that a
* packet is allowed to travel through, specifically for multicast traffic. Each
* router or gateway that forwards a packet decrements the TTL. If the TTL is
* decremented to 0 by a router, it will not be forwarded.
*
* The `ttl` argument may be between 0 and 255\. The default on most systems is `1`.
*
* This method throws `EBADF` if called on an unbound socket.
* @since v0.3.8
*/
setMulticastTTL(ttl: number): void;
/**
* Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer
* in bytes.
*
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
* @since v8.7.0
*/
setRecvBufferSize(size: number): void;
/**
* Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer
* in bytes.
*
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
* @since v8.7.0
*/
setSendBufferSize(size: number): void;
/**
* Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live",
* in this context it specifies the number of IP hops that a packet is allowed to
* travel through. Each router or gateway that forwards a packet decrements the
* TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
* Changing TTL values is typically done for network probes or when multicasting.
*
* The `ttl` argument may be between between 1 and 255\. The default on most systems
* is 64.
*
* This method throws `EBADF` if called on an unbound socket.
* @since v0.1.101
*/
setTTL(ttl: number): void;
/**
* By default, binding a socket will cause it to block the Node.js process from
* exiting as long as the socket is open. The `socket.unref()` method can be used
* to exclude the socket from the reference counting that keeps the Node.js
* process active, allowing the process to exit even if the socket is still
* listening.
*
* Calling `socket.unref()` multiple times will have no addition effect.
*
* The `socket.unref()` method returns a reference to the socket so calls can be
* chained.
* @since v0.9.1
*/
unref(): this;
/**
* Tells the kernel to join a source-specific multicast channel at the given`sourceAddress` and `groupAddress`, using the `multicastInterface` with the`IP_ADD_SOURCE_MEMBERSHIP` socket
* option. If the `multicastInterface` argument
* is not specified, the operating system will choose one interface and will add
* membership to it. To add membership to every available interface, call`socket.addSourceSpecificMembership()` multiple times, once per interface.
*
* When called on an unbound socket, this method will implicitly bind to a random
* port, listening on all interfaces.
* @since v13.1.0, v12.16.0
*/
addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void;
/**
* Instructs the kernel to leave a source-specific multicast channel at the given`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`socket option. This method is
* automatically called by the kernel when the
* socket is closed or the process terminates, so most apps will never have
* reason to call this.
*
* If `multicastInterface` is not specified, the operating system will attempt to
* drop membership on all valid interfaces.
* @since v13.1.0, v12.16.0
*/
dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void;
/**
* events.EventEmitter
* 1. close
* 2. connect
* 3. error
* 4. listening
* 5. message
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: 'close', listener: () => void): this;
addListener(event: 'connect', listener: () => void): this;
addListener(event: 'error', listener: (err: Error) => void): this;
addListener(event: 'listening', listener: () => void): this;
addListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: 'close'): boolean;
emit(event: 'connect'): boolean;
emit(event: 'error', err: Error): boolean;
emit(event: 'listening'): boolean;
emit(event: 'message', msg: Buffer, rinfo: RemoteInfo): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: 'close', listener: () => void): this;
on(event: 'connect', listener: () => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'listening', listener: () => void): this;
on(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: 'close', listener: () => void): this;
once(event: 'connect', listener: () => void): this;
once(event: 'error', listener: (err: Error) => void): this;
once(event: 'listening', listener: () => void): this;
once(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: 'close', listener: () => void): this;
prependListener(event: 'connect', listener: () => void): this;
prependListener(event: 'error', listener: (err: Error) => void): this;
prependListener(event: 'listening', listener: () => void): this;
prependListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'close', listener: () => void): this;
prependOnceListener(event: 'connect', listener: () => void): this;
prependOnceListener(event: 'error', listener: (err: Error) => void): this;
prependOnceListener(event: 'listening', listener: () => void): this;
prependOnceListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
}
}
declare module 'node:dgram' {
export * from 'dgram';
} | the_stack |
export interface Error {
message: string;
type: string;
code: number;
error_subcode: number;
fbtrace_id: string;
}
// Send Api
export type SendAPIRequest = SenderActionRequest | MessageRequest;
export interface SendAPIResponse {
recipient_id: string;
message_id: string;
}
export interface SenderActionRequest {
recipient: Recipient;
sender_action: SenderAction;
}
// Message Request
export interface MessageRequest {
// The messaging type of the message being sent.
messaging_type: MessagingType;
recipient: Recipient;
message: Message;
// Push notification type
// REGULAR: sound/vibration
// SILENT_PUSH: on-screen notification only
// NO_PUSH: no notification
notification_type?: NotificationType;
// The message tag string
tag?: string;
}
export type SenderAction = 'typing_on' | 'typing_off' | 'mark_seen';
export type MessagingType = 'RESPONSE' | 'UPDATE' | 'MESSAGE_TAG';
export type NotificationType = 'REGULAR' | 'SILENT_PUSH' | 'NO_PUSH';
export interface Recipient {
id: string;
phone_number?: string;
user_ref?: string;
name?: RecipientName;
}
export interface RecipientName {
first_name: string;
last_name: string;
}
export interface Message {
text?: string;
attachment?: Attachment;
quick_replies?: QuickReply;
metadata?: string;
}
export interface QuickReply {
content_type: QuickReplyContentType;
title?: string;
payload?: string | number;
image_url?: string;
}
export type QuickReplyContentType = 'text' | 'location' | 'user_phone_number' | 'user_email';
// Webhook API
export interface WebhookEvent {
object: 'page';
entry: WebhookMessagingEntry[];
}
export interface WebhookEntry {
id: string;
time: number;
}
export interface WebhookMessagingEntry extends WebhookEntry {
messaging: WebhookMessagingEvent[];
}
export interface WebhookStandbyEntry extends WebhookEntry {
standby: WebhookStandbyEvent[];
}
export interface WebhookMessagingEvent {
sender?: ConversationParticipant;
receiver: ConversationParticipant;
timestamp: number;
}
export interface WebhookStandbyEvent extends WebhookMessagingEvent {}
export interface MessageReceivedEvent extends WebhookStandbyEvent {
message: {
mid: string;
text?: string;
attachments?: Attachment[];
quick_reply?: {
payload: string;
};
};
}
export interface AccountLinkingEvent extends WebhookMessagingEvent {
account_linking: {
status: 'linked' | 'unlinked';
authorization_code?: string;
};
}
export interface DeliveryEvent extends WebhookStandbyEvent {
delivery: {
mids: string[];
watermark: number;
seq: number;
};
}
export interface MessageEchoEvent extends WebhookMessagingEvent {
message: {
is_echo: boolean;
app_id: string;
metadata: string;
mid: string;
text?: string;
attachments?: Attachment[];
};
}
export interface MessageReadEvent extends WebhookStandbyEvent {
read: {
watermark: number;
seq: number;
};
}
export interface CheckoutUpdateEvent extends WebhookMessagingEvent {
checkout_update: {
payload: string;
shipping_address: Address;
};
}
export interface GamePlayEvent extends WebhookMessagingEvent {
game_play: {
game_id: string;
player_id: string;
context_type: GamePlayContextType;
context_id: string;
score: number;
payload: string;
};
}
export interface PassThreadControlEvent extends WebhookMessagingEvent {
pass_thread_control: {
new_owner_app_id: string;
metadata: string;
};
}
export interface TakeThreadControlEvent extends WebhookMessagingEvent {
take_thread_control: {
previous_owner_app_id: string;
metadata: string;
};
}
export interface RequestThreadControlEvent extends WebhookMessagingEvent {
request_thread_control: {
requested_owner_app_id: string;
metadata: string;
};
}
export interface AppRolesEvent extends WebhookMessagingEvent {
app_roles: {};
}
export interface OptInEvent extends WebhookMessagingEvent {
optin: {
ref: string;
user_ref?: string;
};
}
export interface PaymentEvent extends WebhookMessagingEvent {
payload: string;
requested_user_info: UserInfo;
payment_credential: PaymentCredential;
transaction_amount: TransactionAmount;
}
export interface PolicyEnforcementEvent extends WebhookMessagingEvent {
policy_enforcement: {
action: PolicyEnforcementAction;
reason?: string;
};
}
export interface PostbackEvent extends WebhookStandbyEvent {
title: string;
payload: string;
referral?: Referral;
}
export interface ReferralEvent extends WebhookMessagingEvent {
referral: Referral;
}
export interface Referral {
source: ReferralSource;
type: 'OPEN_THREAD';
ref?: string;
referrer_uri?: string;
ad_id?: string;
}
export interface ConversationParticipant {
id: string;
}
export interface UserInfo {
shipping_address: Address;
contact_name: string;
contact_email: string;
contact_phone: string;
}
export interface PaymentCredential {
provider_type: string;
charge_id: string;
tokenized_card: string;
tokenized_cvv: string;
token_expiry_month: string;
token_expiry_year: string;
fb_payment_id: string;
}
export interface TransactionAmount {
currency: string;
amount: string;
}
export type PolicyEnforcementAction = 'warning' | 'block' | 'unblock';
export type ReferralSource = 'MESSENGER_CODE' | 'DISCOVER_TAB' | 'ADS' | 'SHORTLINK' | 'CUSTOMER_CHAT_PLUGIN';
export type GamePlayContextType = 'SOLO' | 'THREAD' | 'GROUP';
export interface BroadcastMessageCreationRequest {
messages: BroadcastMessage[];
}
export interface DynamicTextMessage {
dynamic_text: {
text: string;
fallback_text: string;
};
}
export type BroadcastMessage = DynamicTextMessage | Message;
export interface BroadcastMessageCreationResponse {
message_creative_id: number;
}
export interface BroadcastMessageSendRequest {
message_creative_id: number;
notification_type: 'REGULAR' | 'SILENT_PUSH' | 'NO_PUSH';
messaging_type: 'MESSAGE_TAG';
tag: 'NON_PROMOTIONAL_SUBSCRIPTION';
}
export interface BroadcastMessageSendResponse {
broadcast_id: number;
}
// Handover protocol
export interface HandoverProtocolRequest {
recipient: {
id: number;
};
metadata?: string;
}
export interface HandoverProtocolSucessResponse {
success: boolean;
}
export interface PassThreadControlRequest extends HandoverProtocolRequest {
target_app_id: number;
}
export type RequestThreadControlRequest = HandoverProtocolRequest;
export type TakeThreadControlRequest = HandoverProtocolRequest;
export interface MessageReceiver {
id: number;
name: string;
}
export interface SecondaryReceiversList {
data: MessageReceiver[];
}
// Profile
export interface ProfileProperties {
account_linking?: string;
get_started?: GetStartedProperty;
greeting?: Greetings[];
whitelisted_domains?: string[];
payment_settings?: PaymentSettings;
target_audience?: TargetAudience;
home_url?: BotHomeUrl;
}
export interface GetStartedProperty {
payload: string;
}
export interface Greetings {
locale: string;
text: string;
}
export interface PaymentSettings {
privacy_url?: string;
public_key?: string;
testers?: number[];
}
export interface TargetAudience {
audience_type: 'all' | 'custom' | 'none';
countries?: TargetCountrySettings;
}
export interface TargetCountrySettings {
blacklist?: string[];
whitelist?: string[];
}
export interface BotHomeUrl {
url: string;
webview_height_ratio: 'tall';
webview_share_button?: 'show' | 'hide';
in_test: boolean;
}
export interface IDMatchingRequest {
page?: number;
app?: number;
access_token: string;
appsecret_proof: string;
}
export interface IDMatchingResponse {
paging: IDMatchingPaging;
}
export interface AppIDMatchingResponse extends IDMatchingResponse {
data: AppIDMatchingData;
}
export interface PageIDMatchingResponse extends IDMatchingResponse {
data: PageIDMatchingData;
}
export interface AppIDMatchingData {
id: string;
app: {
link: string;
name: string;
id: number;
};
}
export interface PageIDMatchingData {
id: string;
page: {
name: string;
id: number;
};
}
export interface IDMatchingPaging {
cursors: {
before: string;
after: string;
};
}
// Code
export interface MessengerCodeRequest {
type: 'standard';
image_size?: number;
data?: {
ref?: string;
};
}
export interface MessengerCodeResponse {
uri: string;
}
export interface FeatureReviewResponse {
data: FeatureReviewResult[];
}
export interface FeatureReviewResult {
feature: string;
status: FeatureReviewStatus;
}
export type FeatureReviewStatus = 'PENDING' | 'REJECTED' | 'APPROVED' | 'LIMITED';
// Insight
export interface InsightsResponse {
data: InsightsResponseData;
}
export interface InsightsResponseData {
name: string;
values: InsightsResponseValue;
}
export interface InsightsResponseValue {
value: number | InsightsResponseValueByType;
end_time: string;
}
export interface InsightsResponseValueByType {
[key: string]: number;
}
// Sponsored Message
export interface SponsoredMessageSendRequest {
message_creative_id: number;
daily_budget: number;
bid_amount: 400;
targeting: any;
}
export interface SponsoredMessageSendResponse {
ad_group_id: number;
broadcast_id: number;
success: boolean;
}
// Attachments
export type Attachment =
| ImageAttachment
| VideoAttachment
| AudioAttachment
| FileAttachment
| LocationAttachment
| FallbackAttachment
| TemplateAttachment;
export interface ImageAttachment {
type: 'image';
payload: MultimediaPayload;
}
export interface VideoAttachment {
type: 'video';
payload: MultimediaPayload;
}
export interface AudioAttachment {
type: 'audio';
payload: MultimediaPayload;
}
export interface FileAttachment {
type: 'file';
payload: MultimediaPayload;
}
export interface LocationAttachment {
type: 'location';
payload: LocationPayload;
}
export interface FallbackAttachment {
type: 'fallback';
payload: null;
title: string;
URL: string;
}
export interface TemplateAttachment {
type: 'template';
payload: TemplatePayload;
}
export interface MultimediaPayload {
url?: string;
is_reusable?: boolean;
attachment_id?: number;
}
export interface LocationPayload {
coordinates: {
lat: number;
long: number;
};
}
export type TemplatePayload =
| ButtonTemplate
| GenericTemplate
| ListTemplate
| MediaTemplate
| OpenGraphTemplate
| ReceiptTemplate
| AirlineBoardingPassTemplate
| AirlineCheckinTemplate
| AirlineItineraryTemplate
| AirlineFlightUpdateTemplate;
export interface ButtonTemplate {
template_type: 'payload';
text: string;
buttons: Button[];
sharable?: boolean;
}
export interface GenericTemplate {
template_type: 'generic';
sharable?: boolean;
image_aspect_ratio?: string;
elements: PayloadElement[];
}
export interface ListTemplate {
template_type: 'list';
top_element_style?: 'compact' | 'large';
buttons?: Button[];
elements: PayloadElement[];
shareable?: boolean;
}
export interface MediaTemplate {
template_type: 'media';
elements: MediaElement[];
sharable?: boolean;
}
export interface OpenGraphTemplate {
template_type: 'open_graph';
elements: OpenGraphElement[];
}
export interface ReceiptTemplate {
template_type: 'receipt';
sharable?: boolean;
recipient_name: string;
merchant_name?: string;
order_number: string;
currency: string;
payment_method: string;
timestamp?: string;
elements: ReceiptElement[];
address?: Address;
summary: ReceiptSummary;
adjustments: ReceiptAdjustment[];
}
export interface AirlineBoardingPassTemplate {
template_type: 'airline_boarding_pass';
intro_message: string;
locale: string;
theme_color?: string;
boarding_pass: BoardingPass[];
}
export interface AirlineCheckinTemplate {
template_time: 'airline_checkin';
intro_message: string;
locale: string;
pnr_number?: string;
checkin_url: string;
flight_info: FlightInfo[];
}
export interface AirlineItineraryTemplate {
template_time: 'airline_itinerary';
intro_message: string;
locale: string;
theme_color?: string;
pnr_number: string;
passenger_info: PassengerInfo[];
flight_info: ItineraryFlightInfo[];
passenger_segment_info: PassengerSegmentInfo[];
price_info?: PriceInfo[];
base_price?: number;
tax?: number;
total_price?: number;
currency: string;
}
export interface AirlineFlightUpdateTemplate {
template_type: 'airline_update';
intro_message: string;
theme_color?: string;
update_type: AirlineFlightUpdateType;
locale: string;
pnr_number?: string;
update_flight_info: FlightInfo;
}
export interface PayloadElement {
title: string;
subtitle?: string;
image_url?: string;
default_action?: Omit<UrlButton, 'title'>;
buttons: Button[];
}
export interface MediaElement {
media_type: 'image' | 'video';
buttons: Button[];
}
export interface MediaElementWithId extends MediaElement {
attachment_id: string;
}
export interface MediaElementWithUrl extends MediaElement {
url: string;
}
export interface OpenGraphElement {
url: string;
buttons: Button[];
}
export interface Address {
id?: string;
street_1: string;
street_2?: string;
city: string;
postal_code: string;
state: string;
country: string;
}
export interface ReceiptSummary {
subtotal?: number;
shipping_cost?: number;
total_tax?: number;
total_cost: number;
}
export interface ReceiptAdjustment {
name: string;
amount: string;
}
export interface ReceiptElement {
title: string;
subtitle?: string;
quatity?: number;
price: number;
currency?: string;
image_url?: string;
}
export interface BoardingPass {
passenger_name: string;
pnr_number: string;
travel_class?: string;
auxiliary_fields: BoardingPassField[];
secondary_fields: BoardingPassField[];
logo_iage_url: string;
header_image_url?: string;
header_text_field?: BoardingPassField;
qr_code?: string;
barcode_image_url?: string;
above_bar_code_image_url: string;
flight_info: FlightInfo;
}
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export interface BoardingPassField {
label: string;
value: string;
}
export interface FlightInfo {
flight_number: string;
departure_airport: Airport;
arrival_airport: Airport;
flight_schedule: FlightSchedule;
}
export interface Airport {
airport_code: string;
city: string;
terminal?: string;
gate?: string;
}
export interface DepartureAirport extends Airport {
terminal: string;
gate: string;
}
export interface FlightSchedule {
boarding_time: string;
departure_time: string;
arrival_time: string;
}
export interface PassengerInfo {
passenger_id: string;
ticket_number?: string;
name: string;
}
export interface ItineraryFlightInfo extends FlightInfo {
connection_id: string;
segment_id: string;
aircraft_type?: string;
travel_class: FlightTravelClass;
}
export interface PassengerSegmentInfo {
segment_id: string;
passenger_id: string;
seat: string;
seat_type: string;
product_info?: string;
}
export interface PriceInfo {
title: string;
amount: number;
currency?: string;
}
export type AirlineFlightUpdateType = 'delay' | 'gate_change' | 'cancellation';
export type FlightTravelClass = 'economy' | 'business' | 'first_class';
// Buttons
export type Button =
| BuyButton
| CallButton
| GameplayButton
| LoginButton
| LogoutButton
| PostbackButton
| ShareButton
| UrlButton;
export interface BuyButton {
type: 'payment';
title: 'buy';
payload: string;
payment_summary: PaymentSummary;
}
export interface CallButton {
type: 'phone_number';
title: string;
payload: string;
}
export interface GameplayButton {
type: 'game_play';
title: string;
payload?: string;
game_metadat?: GameMetadata;
}
export interface LoginButton {
type: 'account_link';
url: string;
}
export interface LogoutButton {
type: 'account_unlink';
}
export interface PostbackButton {
type: 'postback';
title: string;
payload: string;
}
export interface ShareButton {
type: 'element_share';
share_contents: {
attachments: {
type: 'template';
payload: Message;
};
};
}
export interface UrlButton {
type: 'web_url';
title: string;
url: string;
webview_height_ratio?: string;
messenger_extensions?: boolean;
fallback_url?: string;
webview_share_button?: string;
}
export interface PaymentSummary {
currency: string;
is_test_payment?: boolean;
payment_type: 'FIXED_AMOUNT' | 'FLEXIBLE_AMOUNT';
merchant_type: string;
requested_user_info: RequestedUserInfo[];
price_list: PriceList[];
}
export type RequestedUserInfo = 'shipping_address' | 'contact_name' | 'contact_phone' | 'contact_email';
export interface PriceList {
label: string;
amount: string;
}
export interface GameMetadata {
player_id?: string;
context_id?: string;
} | the_stack |
import modelPage from "../../support/pages/model";
import {
entityTypeModal,
entityTypeTable,
graphView,
propertyModal,
propertyTable,
graphViewSidePanel,
relationshipModal
} from "../../support/components/model/index";
import {mappingStepDetail} from "../../support/components/mapping";
import graphVis from "../../support/components/model/graph-vis";
import curatePage from "../../support/pages/curate";
import {confirmationModal, toolbar} from "../../support/components/common/index";
import {ConfirmationType} from "../../support/types/modeling-types";
import {Application} from "../../support/application.config";
import LoginPage from "../../support/pages/login";
import "cypress-wait-until";
describe("Entity Modeling: Graph View", () => {
//Setup hubCentral config for testing
before(() => {
cy.visit("/");
cy.contains(Application.title);
cy.loginAsTestUserWithRoles("hub-central-entity-model-reader", "hub-central-entity-model-writer", "hub-central-mapping-writer", "hub-central-saved-query-user").withRequest();
LoginPage.postLogin();
cy.waitForAsyncRequest();
cy.setupHubCentralConfig();
cy.waitForAsyncRequest();
});
//login with valid account
beforeEach(() => {
cy.visit("/");
cy.contains(Application.title);
cy.loginAsTestUserWithRoles("hub-central-entity-model-reader", "hub-central-entity-model-writer", "hub-central-mapping-writer", "hub-central-saved-query-user").withRequest();
LoginPage.postLogin();
cy.waitForAsyncRequest();
cy.waitUntil(() => toolbar.getModelToolbarIcon()).click();
cy.waitForAsyncRequest();
modelPage.selectView("table");
cy.wait(1000);
entityTypeTable.waitForTableToLoad();
});
afterEach(() => {});
after(() => {
cy.loginAsDeveloper().withRequest();
cy.resetTestUser();
cy.waitForAsyncRequest();
});
it("Create an entity with name having more than 20 chars", () => {
cy.waitUntil(() => toolbar.getModelToolbarIcon()).click({force: true});
modelPage.selectView("table");
entityTypeTable.waitForTableToLoad();
modelPage.getAddEntityButton().should("exist").click();
entityTypeModal.newEntityName("ThisIsVeryLongNameHavingMoreThan20Characters");
entityTypeModal.newEntityDescription("entity description");
cy.waitUntil(() => entityTypeModal.getAddButton().click());
entityTypeTable.viewEntityInGraphView("ThisIsVeryLongNameHavingMoreThan20Characters");
cy.wait(5000);
graphVis.getPositionsOfNodes().then((nodePositions: any) => {
let longNameCoordinates: any = nodePositions["ThisIsVeryLongNameHavingMoreThan20Characters"];
cy.wait(150);
graphVis.getGraphVisCanvas().trigger("mouseover", longNameCoordinates.x, longNameCoordinates.y, {force: true});
// Node shows full name on hover
cy.contains("ThisIsVeryLongNameHavingMoreThan20Characters");
});
graphViewSidePanel.getDeleteIcon("ThisIsVeryLongNameHavingMoreThan20Characters").click();
confirmationModal.getYesButton(ConfirmationType.DeleteEntity);
confirmationModal.getDeleteEntityText().should("not.exist");
cy.waitForAsyncRequest();
graphViewSidePanel.getSelectedEntityHeading("ThisIsVeryLongNameHavingMoreThan20Characters").should("not.exist");
cy.publishEntityModel();
});
it("Create another entity Patients and add a properties", {defaultCommandTimeout: 120000}, () => {
modelPage.selectView("table");
modelPage.getAddEntityButton().should("exist").click();
entityTypeModal.newEntityName("Patients");
entityTypeModal.newEntityDescription("An entity for patients");
entityTypeModal.getAddButton().click();
propertyTable.getAddPropertyButton("Patients").should("be.visible").click();
propertyModal.newPropertyName("patientID");
propertyModal.openPropertyDropdown();
propertyModal.getTypeFromDropdown("More number types").click();
propertyModal.getCascadedTypeFromDropdown("byte").click();
propertyModal.getYesRadio("identifier").click();
//propertyModal.clickCheckbox('wildcard');
propertyModal.getSubmitButton().click();
propertyTable.getIdentifierIcon("patientID").should("exist");
//propertyTable.getWildcardIcon('patientID').should('exist');
propertyTable.getAddPropertyButton("Patients").should("exist");
propertyTable.getAddPropertyButton("Patients").click();
propertyModal.newPropertyName("personType");
propertyModal.openPropertyDropdown();
propertyModal.getTypeFromDropdown("Related Entity").click();
propertyModal.getCascadedTypeFromDropdown("Person").click();
propertyModal.openForeignKeyDropdown();
propertyModal.getForeignKey("id").click();
propertyModal.getSubmitButton().click();
propertyTable.getProperty("personType").should("exist");
//Add second property to Patients Entity and delete it
propertyTable.getAddPropertyButton("Patients").click();
propertyModal.newPropertyName("patientId");
propertyModal.openPropertyDropdown();
propertyModal.getTypeFromDropdown("More number types").click();
propertyModal.getCascadedTypeFromDropdown("byte").click();
propertyModal.getSubmitButton().click();
propertyTable.editProperty("patientId");
propertyModal.getDeleteIcon("patientId").click();
confirmationModal.getDeletePropertyWarnText().should("exist");
confirmationModal.getYesButton(ConfirmationType.DeletePropertyWarn);
propertyTable.getProperty("patientId").should("not.exist");
//Add third property to Patients Entity, publish the changes
propertyTable.getAddPropertyButton("Patients").click();
propertyModal.newPropertyName("health");
propertyModal.openPropertyDropdown();
propertyModal.getTypeFromDropdown("More number types").click();
propertyModal.getCascadedTypeFromDropdown("negativeInteger").click();
propertyModal.clickCheckbox("facetable");
propertyModal.clickCheckbox("sortable");
propertyModal.getSubmitButton().click();
propertyTable.getProperty("health").should("exist");
propertyTable.getFacetIcon("health").should("exist");
propertyTable.getSortIcon("health").should("exist");
//Save Changes
cy.publishEntityModel();
propertyTable.getProperty("patientId").should("not.exist");
propertyTable.getProperty("health").should("exist");
propertyTable.getFacetIcon("health").should("exist");
propertyTable.getSortIcon("health").should("exist");
});
it("Delete an entity from graph view and publish the changes", {defaultCommandTimeout: 120000}, () => {
entityTypeTable.viewEntityInGraphView("Patients");
cy.waitForAsyncRequest();
graphViewSidePanel.getDeleteIcon("Patients").click();
confirmationModal.getYesButton(ConfirmationType.DeleteEntity);
confirmationModal.getDeleteEntityText().should("not.exist");
cy.waitForAsyncRequest();
graphViewSidePanel.getSelectedEntityHeading("Patients").should("not.exist");
cy.wait(150);
//Publish the changes
cy.publishEntityModel();
});
it("Edit a relationship from graph view", {defaultCommandTimeout: 120000}, () => {
modelPage.selectView("project-diagram");
//Fetching the edge coordinates between two nodes and later performing some action on it like hover or click
graphVis.getPositionOfEdgeBetween("Customer,BabyRegistry").then((edgePosition: any) => {
cy.waitUntil(() => graphVis.getGraphVisCanvas().dblclick(edgePosition.x, edgePosition.y));
});
relationshipModal.getModalHeader().should("be.visible");
//edit properties should be populated
relationshipModal.verifyRelationshipValue("ownedBy");
relationshipModal.verifyForeignKeyValue("customerId");
relationshipModal.verifyCardinality("oneToOneIcon").should("be.visible");
//modify properties and save
relationshipModal.editRelationshipName("usedBy");
relationshipModal.toggleCardinality();
relationshipModal.verifyCardinality("oneToManyIcon").should("be.visible");
relationshipModal.editForeignKey("email");
relationshipModal.confirmationOptions("Save");
cy.wait(2000);
cy.waitForAsyncRequest();
relationshipModal.getModalHeader().should("not.exist");
});
it("can enter graph edit mode and add edge relationships via single node click", {defaultCommandTimeout: 120000}, () => {
modelPage.selectView("project-diagram");
//reopen modal to verify previous updates
graphVis.getPositionOfEdgeBetween("Customer,BabyRegistry").then((edgePosition: any) => {
graphVis.getGraphVisCanvas().dblclick(edgePosition.x, edgePosition.y, {force: true});
});
cy.wait(150);
graphVis.getPositionOfEdgeBetween("Customer,BabyRegistry").then((edgePosition: any) => {
graphVis.getGraphVisCanvas().dblclick(edgePosition.x, edgePosition.y, {force: true});
});
relationshipModal.verifyRelationshipValue("usedBy");
relationshipModal.verifyForeignKeyValue("email");
relationshipModal.verifyCardinality("oneToManyIcon").should("be.visible");
//reset the values
relationshipModal.editRelationshipName("ownedBy");
relationshipModal.editForeignKey("customerId");
relationshipModal.toggleCardinality();
relationshipModal.confirmationOptions("Save");
cy.wait(2000);
cy.waitForAsyncRequest();
relationshipModal.getModalHeader().should("not.exist");
graphView.getAddButton().click();
graphView.addNewRelationship().click();
graphView.verifyEditInfoMessage().should("exist");
cy.wait(1000);
//verify create relationship via clicking a node in edit mode
graphVis.getPositionsOfNodes().then((nodePositions: any) => {
let personCoordinates: any = nodePositions["Person"];
graphVis.getGraphVisCanvas().trigger("mouseover", personCoordinates.x, personCoordinates.y);
cy.wait(150);
graphVis.getGraphVisCanvas().dblclick(personCoordinates.x, personCoordinates.y, {force: true});
});
cy.wait(150);
graphVis.getPositionsOfNodes().then((nodePositions: any) => {
let personCoordinates: any = nodePositions["Person"];
graphVis.getGraphVisCanvas().dblclick(personCoordinates.x, personCoordinates.y, {force: true});
});
relationshipModal.getModalHeader().should("be.visible");
relationshipModal.verifySourceEntity("Person").should("be.visible");
relationshipModal.verifyCardinality("oneToOneIcon").should("be.visible");
//target entity node should be placeholder and user can set relationship options
relationshipModal.verifyTargetEntity("Select target entity type*").should("be.visible");
relationshipModal.targetEntityDropdown().click();
//verify dropdown options can be searched
relationshipModal.verifyEntityOption("Customer").should("be.visible");
relationshipModal.verifyEntityOption("Order").should("be.visible");
relationshipModal.verifyEntityOption("Client").should("be.visible");
relationshipModal.searchEntityDropdown("ord");
relationshipModal.verifyEntityOption("Customer").should("not.exist");
relationshipModal.verifyEntityOption("Client").should("not.exist");
relationshipModal.verifyEntityOption("Order").should("be.visible");
relationshipModal.selectTargetEntityOption("Order");
relationshipModal.toggleOptional();
relationshipModal.verifyForeignKeyPlaceholder();
relationshipModal.editRelationshipName("purchased");
relationshipModal.toggleCardinality();
relationshipModal.addRelationshipSubmit();
cy.waitForAsyncRequest();
relationshipModal.getModalHeader().should("not.exist");
//verify relationship was created and properties are present
modelPage.selectView("table");
entityTypeTable.waitForTableToLoad();
entityTypeTable.getExpandEntityIcon("Person");
propertyTable.editProperty("purchased");
propertyModal.getYesRadio("multiple").should("be.checked");
propertyModal.verifyPropertyType("Relationship: Order");
propertyModal.verifyForeignKeyPlaceholder();
propertyModal.getCancelButton();
//verify helpful icon present on the property, should show relationship icon but no foreign key
propertyTable.verifyRelationshipIcon("purchased").should("exist");
propertyTable.verifyForeignKeyIcon("purchased").should("not.exist");
// });
// it("can edit graph edit mode and add edge relationships (with foreign key scenario) via drag/drop", () => {
entityTypeTable.viewEntityInGraphView("Person");
cy.wait(2000);
cy.waitForAsyncRequest();
graphView.getAddButton().click();
cy.waitUntil(() => graphView.addNewRelationship().should("be.visible"));
graphView.addNewRelationship().click({force: true});
cy.waitUntil(() => graphView.verifyEditInfoMessage().should("exist"));
graphVis.getPositionsOfNodes().then((nodePositions: any) => {
let PersonCoordinates: any = nodePositions["Person"];
let ClientCoordinates: any = nodePositions["Client"];
graphVis.getGraphVisCanvas().trigger("pointerdown", PersonCoordinates.x, PersonCoordinates.y, {button: 0});
graphVis.getGraphVisCanvas().trigger("pointermove", ClientCoordinates.x, ClientCoordinates.y, {button: 0});
graphVis.getGraphVisCanvas().trigger("pointerup", ClientCoordinates.x, ClientCoordinates.y, {button: 0});
});
//relationship modal should open with proper source and target nodes in place
relationshipModal.verifySourceEntity("Person").should("be.visible");
relationshipModal.verifyTargetEntity("Client").should("be.visible");
//add relationship properties and save
relationshipModal.editRelationshipName("referredBy");
//open Optional line to edit foreign key field
relationshipModal.toggleOptional();
relationshipModal.editForeignKey("firstname");
relationshipModal.toggleCardinality();
relationshipModal.addRelationshipSubmit();
cy.waitForAsyncRequest();
cy.wait(2000);
graphView.getAddButton().click();
cy.waitUntil(() => graphView.addNewRelationship().should("be.visible"));
graphView.addNewRelationship().click({force: true});
cy.waitUntil(() => graphView.verifyEditInfoMessage().should("exist"));
//add second relationship
graphView.getAddButton().click();
graphView.addNewRelationship().click();
graphView.verifyEditInfoMessage().should("exist");
graphVis.getPositionsOfNodes().then((nodePositions: any) => {
let PersonCoordinates: any = nodePositions["Person"];
let ClientCoordinates: any = nodePositions["Client"];
cy.wait(150);
graphVis.getGraphVisCanvas().trigger("pointerdown", PersonCoordinates.x, PersonCoordinates.y, {button: 0});
graphVis.getGraphVisCanvas().trigger("pointermove", ClientCoordinates.x, ClientCoordinates.y, {button: 0});
graphVis.getGraphVisCanvas().trigger("pointerup", ClientCoordinates.x, ClientCoordinates.y, {button: 0});
});
//relationship modal should open with proper source and target nodes in place
relationshipModal.verifySourceEntity("Person").should("be.visible");
relationshipModal.verifyTargetEntity("Client").should("be.visible");
//add relationship properties and save
relationshipModal.editRelationshipName("recommendedByUserHavingVeryLongName");
//open Optional line to edit foreign key field
relationshipModal.toggleOptional();
relationshipModal.editForeignKey("lastname");
relationshipModal.toggleCardinality();
relationshipModal.addRelationshipSubmit();
cy.waitForAsyncRequest();
relationshipModal.getModalHeader().should("not.exist");
//Both the relationship names must be available
cy.contains("referredBy");
// TODO: this line causes failures, fix this assertion
// cy.contains("recommendedByUserHav...");
//verify relationship was created and properties are present
modelPage.selectView("table");
entityTypeTable.waitForTableToLoad();
propertyTable.editProperty("referredBy");
propertyModal.getYesRadio("multiple").should("be.checked");
propertyModal.verifyPropertyType("Relationship: Client");
propertyModal.verifyForeignKey("firstname");
propertyModal.getCancelButton();
//verify helpful icon present on the property, should show BOTH relationship icon and foreign key
propertyTable.verifyRelationshipIcon("referredBy").should("exist");
propertyTable.verifyForeignKeyIcon("referredBy").should("exist");
entityTypeTable.viewEntityInGraphView("Person");
});
it("relationships are not present in mapping until published", () => {
toolbar.getCurateToolbarIcon().click();
confirmationModal.getNavigationWarnText().should("exist");
confirmationModal.getYesButton(ConfirmationType.NavigationWarn);
cy.waitUntil(() => curatePage.getEntityTypePanel("Person").should("be.visible"));
curatePage.toggleEntityTypeId("Person");
curatePage.openStepDetails("mapPersonJSON");
cy.waitUntil(() => curatePage.dataPresent().should("be.visible"));
//unpublished relationship should not show up in mapping
mappingStepDetail.getMapPropertyName("Person", "purchased").should("not.exist");
mappingStepDetail.getMapPropertyName("Person", "referredBy").should("not.exist");
//return to Model tile and publish
toolbar.getModelToolbarIcon().click();
cy.publishEntityModel();
//verify relationship is visible in mapping
toolbar.getCurateToolbarIcon().click();
confirmationModal.getNavigationWarnText().should("not.exist");
cy.waitUntil(() => curatePage.getEntityTypePanel("Person").should("be.visible"));
curatePage.toggleEntityTypeId("Person");
curatePage.openStepDetails("mapPersonJSON");
cy.waitUntil(() => curatePage.dataPresent().should("be.visible"));
//published relationship should show up in mapping
mappingStepDetail.getMapPropertyName("Person", "purchased").should("exist");
mappingStepDetail.getMapPropertyName("Person", "referredBy").should("exist");
//both icons present in complete relationship
propertyTable.verifyRelationshipIcon("referredBy").should("exist");
propertyTable.verifyForeignKeyIcon("referredBy").should("exist");
//only relationship icon present in incomplete relationship and XPATH field is disabled
propertyTable.verifyRelationshipIcon("purchased").should("exist");
propertyTable.verifyForeignKeyIcon("purchased").should("not.exist");
mappingStepDetail.getXpathExpressionInput("purchased").should("not.exist");
});
it("Delete a relationship from graph view", {defaultCommandTimeout: 120000}, () => {
toolbar.getModelToolbarIcon().click();
modelPage.selectView("project-diagram");
// To delete a relation
cy.wait(1000);
graphVis.getPositionOfEdgeBetween("Person,Order").then((edgePosition: any) => {
graphVis.getGraphVisCanvas().dblclick(edgePosition.x, edgePosition.y);
});
cy.wait(150);
graphVis.getPositionOfEdgeBetween("Person,Order").then((edgePosition: any) => {
graphVis.getGraphVisCanvas().dblclick(edgePosition.x, edgePosition.y, {force: true});
});
cy.wait(1000);
graphVis.getPositionOfEdgeBetween("Person,Order").then((edgePosition: any) => {
graphVis.getGraphVisCanvas().dblclick(edgePosition.x, edgePosition.y, {force: true});
});
confirmationModal.deleteRelationship();
cy.waitUntil(() => cy.findByLabelText("confirm-deletePropertyStepWarn-yes").click());
// To verify that property is not visible
cy.wait(150);
graphVis.getPositionsOfNodes("Person").then((nodePositions: any) => {
let personCoordinates: any = nodePositions["Person"];
cy.waitUntil(() => graphVis.getGraphVisCanvas().click(personCoordinates.x, personCoordinates.y));
});
graphViewSidePanel.getPropertyName("purchased").should("not.exist");
});
}); | the_stack |
namespace lcd {
//% shim=lcd::__write8
function __write8(value: number, char_mode: boolean): void {
}
// Commands
const _LCD_CLEARDISPLAY = 0x01
const _LCD_RETURNHOME = 0x02
const _LCD_ENTRYMODESET = 0x04
const _LCD_DISPLAYCONTROL = 0x08
const _LCD_CURSORSHIFT = 0x10
const _LCD_FUNCTIONSET = 0x20
const _LCD_SETCGRAMADDR = 0x40
const _LCD_SETDDRAMADDR = 0x80
// Entry flags
const _LCD_ENTRYLEFT = 0x02
const _LCD_ENTRYSHIFTDECREMENT = 0x00
// Control flags
const _LCD_DISPLAYON = 0x04
const _LCD_CURSORON = 0x02
const _LCD_CURSOROFF = 0x00
const _LCD_BLINKON = 0x01
const _LCD_BLINKOFF = 0x00
// Move flags
const _LCD_DISPLAYMOVE = 0x08
const _LCD_MOVERIGHT = 0x04
const _LCD_MOVELEFT = 0x00
// Function set flags
const _LCD_4BITMODE = 0x00
const _LCD_2LINE = 0x08
const _LCD_1LINE = 0x00
const _LCD_5X8DOTS = 0x00
// Offset for up to 4 rows.
const _LCD_ROW_OFFSETS = [0x00, 0x40, 0x14, 0x54]
export class CharacterLCD {
columns: number
lines: number
reset: DigitalInOutPin;
enable: DigitalInOutPin;
dl4: DigitalInOutPin;
dl5: DigitalInOutPin;
dl6: DigitalInOutPin;
dl7: DigitalInOutPin;
displaycontrol: number
displayfunction: number
displaymode: number
_message: string;
_enable: boolean;
_rtl: boolean;
// pylint: disable-msg=too-many-arguments
constructor(rs: DigitalInOutPin, en: DigitalInOutPin,
d4: DigitalInOutPin, d5: DigitalInOutPin, d6: DigitalInOutPin, d7: DigitalInOutPin,
columns: number, lines: number) {
this._rtl = false;
this.columns = columns;
this.lines = lines;
// save pin numbers
this.reset = rs;
this.enable = en;
this.dl4 = d4;
this.dl5 = d5;
this.dl6 = d6;
this.dl7 = d7;
// set all pins as outputs
for (const pin of [rs, en, d4, d5, d6, d7]) {
pin.digitalWrite(false);
}
// Initialise the display
this._write8(0x33)
this._write8(0x32)
// Initialise display control
this.displaycontrol = _LCD_DISPLAYON | _LCD_CURSOROFF | _LCD_BLINKOFF
// Initialise display function
this.displayfunction = _LCD_4BITMODE | _LCD_1LINE | _LCD_2LINE | _LCD_5X8DOTS
// Initialise display mode
this.displaymode = _LCD_ENTRYLEFT | _LCD_ENTRYSHIFTDECREMENT
// Write to displaycontrol
this._write8(_LCD_DISPLAYCONTROL | this.displaycontrol)
// Write to displayfunction
this._write8(_LCD_FUNCTIONSET | this.displayfunction)
// Set entry mode
this._write8(_LCD_ENTRYMODESET | this.displaymode)
this.clear()
this._message = ""
this._enable = null
}
/**
* Moves the cursor "home" to position (1, 1).
**/
public home(): void {
this._write8(_LCD_RETURNHOME)
pause(3)
}
/** Clears everything displayed on the LCD.
* The following example displays, "Hello, world!", then clears the LCD.
**/
public clear(): void {
this._write8(_LCD_CLEARDISPLAY)
this._message = "";
pause(3)
}
/**
* True if cursor is visible. False to stop displaying the cursor.
*/
get cursor(): boolean {
return (this.displaycontrol & _LCD_CURSORON) == _LCD_CURSORON;
}
set cursor(show: boolean) {
const dc = this.displaycontrol;
if (show)
this.displaycontrol |= _LCD_CURSORON
else
this.displaycontrol &= ~_LCD_CURSORON
if (dc != this.displaycontrol)
this._write8(_LCD_DISPLAYCONTROL | this.displaycontrol)
}
/**
* Move the cursor to position ``column``, ``row``
**/
public setCursorPosition(column: number, row: number): void {
column = Math.max(0, Math.min(this.columns - 1, column | 0));
row = Math.max(0, Math.min(this.lines - 1, row | 0));
//console.log(`cursor ${_LCD_SETDDRAMADDR | column + _LCD_ROW_OFFSETS[row]}`)
this._write8(_LCD_SETDDRAMADDR | column + _LCD_ROW_OFFSETS[row])
}
/**
* Blink the cursor. True to blink the cursor. False to stop blinking.
*/
get blink(): boolean {
return (this.displaycontrol & _LCD_BLINKON) == _LCD_BLINKON
}
set blink(value: boolean) {
const dc = this.displaycontrol;
if (value)
this.displaycontrol |= _LCD_BLINKON
else
this.displaycontrol &= ~_LCD_BLINKON
if (dc != this.displaycontrol)
this._write8(_LCD_DISPLAYCONTROL | this.displaycontrol)
}
/**
* Enable or disable the display. True to enable the display. False to disable the display.
*/
get display(): boolean {
return (this.displaycontrol & _LCD_DISPLAYON) == _LCD_DISPLAYON
}
set display(enable: boolean) {
const dc = this.displaycontrol;
if (enable)
this.displaycontrol |= _LCD_DISPLAYON
else
this.displaycontrol &= ~_LCD_DISPLAYON
if (dc != this.displaycontrol)
this._write8(_LCD_DISPLAYCONTROL | this.displaycontrol)
}
/**
* Display a string of text on the character LCD.
*/
get message(): string {
return this._message
}
set message(message: string) {
if (message === undefined || message === null) message = "";
if (this._message === message) return; // nothing to do here
const oldMessage = this._message;
this._message = message;
//console.log(`'${oldMessage}' => '${message}'`);
const ltr = !!(this.displaymode & _LCD_ENTRYLEFT);
const oldLines = oldMessage.split('\n');
const lines = this._message.split('\n');
const rn = Math.min(this.lines, Math.max(oldLines.length, lines.length));
let cursorrow = -1;
let cursorcol = -1;
for (let row = 0; row < rn; ++row) {
let oldLine = oldLines[row];
if (oldLine === undefined) oldLine = "";
let line = lines[row];
if (line === undefined) line = "";
const cn = Math.min(this.columns, Math.max(oldLine.length, line.length));
for (let column = 0; column < cn; ++column) {
const oc = oldLine.charCodeAt(column);
const c = line.charCodeAt(column);
if (oc !== c) {
// letter is already shown, skip
// move cursor if needed
if (row != cursorrow || column != cursorcol) {
//console.log(`set cursor pos ${column}, ${row}`);
this.setCursorPosition(ltr ? column : this.columns - 1 - column, row);
cursorrow = row;
cursorcol = column;
}
//console.log(`write ${String.fromCharCode(c)} (${String.fromCharCode(oc)}) at ${cursorcol}, ${cursorrow}`);
if (column >= line.length)
this._write8(32 /* space */, true);
else
this._write8(c, true);
cursorcol++;
}
}
}
}
/**
* Moves displayed text left one column.
**/
public moveLeft(): void {
this._write8(_LCD_CURSORSHIFT | _LCD_DISPLAYMOVE | _LCD_MOVELEFT)
}
/**
* Moves displayed text right one column.
**/
public moveRight(): void {
this._write8(_LCD_CURSORSHIFT | _LCD_DISPLAYMOVE | _LCD_MOVERIGHT)
}
get rightToLeft(): boolean {
return this._rtl;
}
set rightToLeft(direction: boolean) {
if (this._rtl != direction) {
this._rtl = direction;
if (this._rtl)
this._right_to_left();
else
this._left_to_right();
}
}
private _left_to_right(): void {
// Displays text from left to right on the LCD.
this.displaymode |= _LCD_ENTRYLEFT
this._write8(_LCD_ENTRYMODESET | this.displaymode)
}
private _right_to_left(): void {
// Displays text from right to left on the LCD.
this.displaymode &= ~_LCD_ENTRYLEFT
this._write8(_LCD_ENTRYMODESET | this.displaymode)
}
/**
* Fill one of the first 8 CGRAM locations with custom characters.
* The location parameter should be between 0 and 7 and pattern should
* provide an array of 8 bytes containing the pattern. E.g. you can easily
* design your custom character at http://www.quinapalus.com/hd44780udg.html
* To show your custom character use, for example, ``lcd.message = ""``
*/
public create_char(location: number, pattern: Buffer): void {
// only position 0..7 are allowed
location &= 0x7
this._write8(_LCD_SETCGRAMADDR | location << 3)
for (let i = 0; i < 8; ++i) {
this._write8(pattern[i], true)
}
}
/**
* Sends 8b ``value`` in ``char_mode``.
* @param value bytes
* @param char_mode character/data mode selector. False (default) for data only, True for character bits.
*/
private _write8(value: number, char_mode = false): void {
__write8(value, char_mode);
// one ms delay to prevent writing too quickly.
pause(1)
// set character/data bit. (charmode = False)
this.reset.digitalWrite(char_mode)
// WRITE upper 4 bits
this.dl4.digitalWrite(!!(value >> 4 & 1));
this.dl5.digitalWrite(!!(value >> 5 & 1));
this.dl6.digitalWrite(!!(value >> 6 & 1));
this.dl7.digitalWrite(!!(value >> 7 & 1));
// send command
this._pulse_enable()
// WRITE lower 4 bits
this.dl4.digitalWrite(!!(value & 1));
this.dl5.digitalWrite(!!(value >> 1 & 1));
this.dl6.digitalWrite(!!(value >> 2 & 1));
this.dl7.digitalWrite(!!(value >> 3 & 1));
this._pulse_enable()
}
private _pulse_enable(): void {
// Pulses (lo->hi->lo) to send commands.
this.enable.digitalWrite(false);
control.waitMicros(1);
this.enable.digitalWrite(true);
control.waitMicros(1);
this.enable.digitalWrite(false);
control.waitMicros(1);
}
}
} | the_stack |
declare class DKAsset extends NSObject {
static alloc(): DKAsset; // inherited from NSObject
static new(): DKAsset; // inherited from NSObject
readonly duration: number;
error: NSError;
fileName: string;
fileSize: number;
localIdentifier: string;
localTemporaryPath: NSURL;
readonly location: CLLocation;
readonly originalAsset: PHAsset;
readonly pixelHeight: number;
readonly pixelWidth: number;
progress: number;
readonly type: DKAssetType;
cancelRequests(): void;
fetchAVAssetWithOptionsCompleteBlock(options: PHVideoRequestOptions, completeBlock: (p1: AVAsset, p2: NSDictionary<any, any>) => void): void;
fetchFullScreenImageWithCompleteBlock(completeBlock: (p1: UIImage, p2: NSDictionary<any, any>) => void): void;
fetchImageDataWithOptionsCompleteBlock(options: PHImageRequestOptions, completeBlock: (p1: NSData, p2: NSDictionary<any, any>) => void): void;
fetchImageWithOptionsContentModeCompleteBlock(size: CGSize, options: PHImageRequestOptions, contentMode: PHImageContentMode, completeBlock: (p1: UIImage, p2: NSDictionary<any, any>) => void): void;
fetchOriginalImageWithOptionsCompleteBlock(options: PHImageRequestOptions, completeBlock: (p1: UIImage, p2: NSDictionary<any, any>) => void): void;
}
declare class DKAssetGroup extends NSObject {
static alloc(): DKAssetGroup; // inherited from NSObject
static new(): DKAssetGroup; // inherited from NSObject
}
interface DKAssetGroupCellItemProtocol {
asset: DKAsset;
selectedIndex: number;
thumbnailImage: UIImage;
thumbnailImageView: UIImageView;
}
declare var DKAssetGroupCellItemProtocol: {
prototype: DKAssetGroupCellItemProtocol;
};
interface DKAssetGroupCellType {
configureWithTagDataManagerImageRequestOptions(assetGroup: DKAssetGroup, tag: number, dataManager: DKImageGroupDataManager, imageRequestOptions: PHImageRequestOptions): void;
}
declare var DKAssetGroupCellType: {
prototype: DKAssetGroupCellType;
preferredHeight(): number;
};
declare class DKAssetGroupDetailBaseCell extends UICollectionViewCell implements DKAssetGroupCellItemProtocol {
static alloc(): DKAssetGroupDetailBaseCell; // inherited from NSObject
static appearance(): DKAssetGroupDetailBaseCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): DKAssetGroupDetailBaseCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): DKAssetGroupDetailBaseCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): DKAssetGroupDetailBaseCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): DKAssetGroupDetailBaseCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): DKAssetGroupDetailBaseCell; // inherited from UIAppearance
static new(): DKAssetGroupDetailBaseCell; // inherited from NSObject
asset: DKAsset; // inherited from DKAssetGroupCellItemProtocol
selectedIndex: number; // inherited from DKAssetGroupCellItemProtocol
thumbnailImage: UIImage; // inherited from DKAssetGroupCellItemProtocol
readonly thumbnailImageView: UIImageView; // inherited from DKAssetGroupCellItemProtocol
}
declare class DKAssetGroupDetailCameraCell extends DKAssetGroupDetailBaseCell {
static alloc(): DKAssetGroupDetailCameraCell; // inherited from NSObject
static appearance(): DKAssetGroupDetailCameraCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): DKAssetGroupDetailCameraCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): DKAssetGroupDetailCameraCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): DKAssetGroupDetailCameraCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): DKAssetGroupDetailCameraCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): DKAssetGroupDetailCameraCell; // inherited from UIAppearance
static cellReuseIdentifier(): string;
static new(): DKAssetGroupDetailCameraCell; // inherited from NSObject
}
declare class DKAssetGroupDetailImageCell extends DKAssetGroupDetailBaseCell {
static alloc(): DKAssetGroupDetailImageCell; // inherited from NSObject
static appearance(): DKAssetGroupDetailImageCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): DKAssetGroupDetailImageCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): DKAssetGroupDetailImageCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): DKAssetGroupDetailImageCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): DKAssetGroupDetailImageCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): DKAssetGroupDetailImageCell; // inherited from UIAppearance
static cellReuseIdentifier(): string;
static new(): DKAssetGroupDetailImageCell; // inherited from NSObject
}
declare class DKAssetGroupDetailVC extends UIViewController implements DKImagePickerControllerAware, UICollectionViewDataSource, UICollectionViewDelegate, UIGestureRecognizerDelegate {
static alloc(): DKAssetGroupDetailVC; // inherited from NSObject
static new(): DKAssetGroupDetailVC; // inherited from NSObject
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
imagePickerController: DKImagePickerController; // inherited from DKImagePickerControllerAware
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
collectionViewCanFocusItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewCanMoveItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewCanPerformActionForItemAtIndexPathWithSender(collectionView: UICollectionView, action: string, indexPath: NSIndexPath, sender: any): boolean;
collectionViewCellForItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): UICollectionViewCell;
collectionViewContextMenuConfigurationForItemAtIndexPathPoint(collectionView: UICollectionView, indexPath: NSIndexPath, point: CGPoint): UIContextMenuConfiguration;
collectionViewDidBeginMultipleSelectionInteractionAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidDeselectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidEndDisplayingCellForItemAtIndexPath(collectionView: UICollectionView, cell: UICollectionViewCell, indexPath: NSIndexPath): void;
collectionViewDidEndDisplayingSupplementaryViewForElementOfKindAtIndexPath(collectionView: UICollectionView, view: UICollectionReusableView, elementKind: string, indexPath: NSIndexPath): void;
collectionViewDidEndMultipleSelectionInteraction(collectionView: UICollectionView): void;
collectionViewDidHighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidSelectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidUnhighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidUpdateFocusInContextWithAnimationCoordinator(collectionView: UICollectionView, context: UICollectionViewFocusUpdateContext, coordinator: UIFocusAnimationCoordinator): void;
collectionViewIndexPathForIndexTitleAtIndex(collectionView: UICollectionView, title: string, index: number): NSIndexPath;
collectionViewMoveItemAtIndexPathToIndexPath(collectionView: UICollectionView, sourceIndexPath: NSIndexPath, destinationIndexPath: NSIndexPath): void;
collectionViewNumberOfItemsInSection(collectionView: UICollectionView, section: number): number;
collectionViewPerformActionForItemAtIndexPathWithSender(collectionView: UICollectionView, action: string, indexPath: NSIndexPath, sender: any): void;
collectionViewPreviewForDismissingContextMenuWithConfiguration(collectionView: UICollectionView, configuration: UIContextMenuConfiguration): UITargetedPreview;
collectionViewPreviewForHighlightingContextMenuWithConfiguration(collectionView: UICollectionView, configuration: UIContextMenuConfiguration): UITargetedPreview;
collectionViewShouldBeginMultipleSelectionInteractionAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldDeselectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldHighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldSelectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldShowMenuForItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldSpringLoadItemAtIndexPathWithContext(collectionView: UICollectionView, indexPath: NSIndexPath, context: UISpringLoadedInteractionContext): boolean;
collectionViewShouldUpdateFocusInContext(collectionView: UICollectionView, context: UICollectionViewFocusUpdateContext): boolean;
collectionViewTargetContentOffsetForProposedContentOffset(collectionView: UICollectionView, proposedContentOffset: CGPoint): CGPoint;
collectionViewTargetIndexPathForMoveFromItemAtIndexPathToProposedIndexPath(collectionView: UICollectionView, originalIndexPath: NSIndexPath, proposedIndexPath: NSIndexPath): NSIndexPath;
collectionViewTransitionLayoutForOldLayoutNewLayout(collectionView: UICollectionView, fromLayout: UICollectionViewLayout, toLayout: UICollectionViewLayout): UICollectionViewTransitionLayout;
collectionViewViewForSupplementaryElementOfKindAtIndexPath(collectionView: UICollectionView, kind: string, indexPath: NSIndexPath): UICollectionReusableView;
collectionViewWillCommitMenuWithAnimator(collectionView: UICollectionView, animator: UIContextMenuInteractionCommitAnimating): void;
collectionViewWillDisplayCellForItemAtIndexPath(collectionView: UICollectionView, cell: UICollectionViewCell, indexPath: NSIndexPath): void;
collectionViewWillDisplaySupplementaryViewForElementKindAtIndexPath(collectionView: UICollectionView, view: UICollectionReusableView, elementKind: string, indexPath: NSIndexPath): void;
collectionViewWillPerformPreviewActionForMenuWithConfigurationAnimator(collectionView: UICollectionView, configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating): void;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
gestureRecognizerShouldBeRequiredToFailByGestureRecognizer(gestureRecognizer: UIGestureRecognizer, otherGestureRecognizer: UIGestureRecognizer): boolean;
gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer): boolean;
gestureRecognizerShouldReceivePress(gestureRecognizer: UIGestureRecognizer, press: UIPress): boolean;
gestureRecognizerShouldReceiveTouch(gestureRecognizer: UIGestureRecognizer, touch: UITouch): boolean;
gestureRecognizerShouldRecognizeSimultaneouslyWithGestureRecognizer(gestureRecognizer: UIGestureRecognizer, otherGestureRecognizer: UIGestureRecognizer): boolean;
gestureRecognizerShouldRequireFailureOfGestureRecognizer(gestureRecognizer: UIGestureRecognizer, otherGestureRecognizer: UIGestureRecognizer): boolean;
indexPathForPreferredFocusedViewInCollectionView(collectionView: UICollectionView): NSIndexPath;
indexTitlesForCollectionView(collectionView: UICollectionView): NSArray<string>;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
numberOfSectionsInCollectionView(collectionView: UICollectionView): number;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
reload(): void;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
scrollViewDidChangeAdjustedContentInset(scrollView: UIScrollView): void;
scrollViewDidEndDecelerating(scrollView: UIScrollView): void;
scrollViewDidEndDraggingWillDecelerate(scrollView: UIScrollView, decelerate: boolean): void;
scrollViewDidEndScrollingAnimation(scrollView: UIScrollView): void;
scrollViewDidEndZoomingWithViewAtScale(scrollView: UIScrollView, view: UIView, scale: number): void;
scrollViewDidScroll(scrollView: UIScrollView): void;
scrollViewDidScrollToTop(scrollView: UIScrollView): void;
scrollViewDidZoom(scrollView: UIScrollView): void;
scrollViewShouldScrollToTop(scrollView: UIScrollView): boolean;
scrollViewWillBeginDecelerating(scrollView: UIScrollView): void;
scrollViewWillBeginDragging(scrollView: UIScrollView): void;
scrollViewWillBeginZoomingWithView(scrollView: UIScrollView, view: UIView): void;
scrollViewWillEndDraggingWithVelocityTargetContentOffset(scrollView: UIScrollView, velocity: CGPoint, targetContentOffset: interop.Pointer | interop.Reference<CGPoint>): void;
self(): this;
viewForZoomingInScrollView(scrollView: UIScrollView): UIView;
}
declare class DKAssetGroupDetailVideoCell extends DKAssetGroupDetailImageCell {
static alloc(): DKAssetGroupDetailVideoCell; // inherited from NSObject
static appearance(): DKAssetGroupDetailVideoCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): DKAssetGroupDetailVideoCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): DKAssetGroupDetailVideoCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): DKAssetGroupDetailVideoCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): DKAssetGroupDetailVideoCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): DKAssetGroupDetailVideoCell; // inherited from UIAppearance
static new(): DKAssetGroupDetailVideoCell; // inherited from NSObject
}
declare class DKAssetGroupGridLayout extends UICollectionViewFlowLayout {
static alloc(): DKAssetGroupGridLayout; // inherited from NSObject
static new(): DKAssetGroupGridLayout; // inherited from NSObject
}
declare const enum DKAssetType {
Photo = 0,
Video = 1
}
declare class DKImageAssetExporter extends DKImageBaseManager {
static alloc(): DKImageAssetExporter; // inherited from NSObject
static new(): DKImageAssetExporter; // inherited from NSObject
static readonly sharedInstance: DKImageAssetExporter;
constructor(o: { configuration: DKImageAssetExporterConfiguration; });
cancelAll(): void;
cancelWithRequestID(requestID: number): void;
exportAssetsAsynchronouslyWithAssetsCompletion(assets: NSArray<DKAsset> | DKAsset[], completion: (p1: NSDictionary<any, any>) => void): number;
initWithConfiguration(configuration: DKImageAssetExporterConfiguration): this;
}
declare class DKImageAssetExporterConfiguration extends NSObject implements NSCopying {
static alloc(): DKImageAssetExporterConfiguration; // inherited from NSObject
static new(): DKImageAssetExporterConfiguration; // inherited from NSObject
avOutputFileType: string;
exportDirectory: NSURL;
imageExportPreset: DKImageExportPresent;
videoExportPreset: string;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
}
declare const enum DKImageAssetExporterError {
Cancelled = 0,
ExportFailed = 1
}
interface DKImageAssetExporterObserver {
exporterDidEndExportingWithExporterAsset?(exporter: DKImageAssetExporter, asset: DKAsset): void;
exporterDidUpdateProgressWithExporterAsset?(exporter: DKImageAssetExporter, asset: DKAsset): void;
exporterWillBeginExportingWithExporterAsset?(exporter: DKImageAssetExporter, asset: DKAsset): void;
}
declare var DKImageAssetExporterObserver: {
prototype: DKImageAssetExporterObserver;
};
declare class DKImageBaseExtension extends NSObject {
static alloc(): DKImageBaseExtension; // inherited from NSObject
static new(): DKImageBaseExtension; // inherited from NSObject
}
declare class DKImageBaseManager extends NSObject {
static alloc(): DKImageBaseManager; // inherited from NSObject
static new(): DKImageBaseManager; // inherited from NSObject
addWithObserver(object: any): void;
removeWithObserver(object: any): void;
}
declare const enum DKImageExportPresent {
Compatible = 0,
Current = 1
}
declare class DKImageExtensionCamera extends DKImageBaseExtension {
static alloc(): DKImageExtensionCamera; // inherited from NSObject
static new(): DKImageExtensionCamera; // inherited from NSObject
}
declare class DKImageExtensionController extends NSObject {
static alloc(): DKImageExtensionController; // inherited from NSObject
static new(): DKImageExtensionController; // inherited from NSObject
static registerExtensionWithExtensionClassFor(extensionClass: typeof NSObject, type: DKImageExtensionType): void;
static unregisterExtensionFor(type: DKImageExtensionType): void;
}
declare class DKImageExtensionGallery extends DKImageBaseExtension implements DKPhotoGalleryDelegate {
static alloc(): DKImageExtensionGallery; // inherited from NSObject
static new(): DKImageExtensionGallery; // inherited from NSObject
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
dismissGallery(): void;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
photoGalleryDidShow(gallery: DKPhotoGallery, index: number): void;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
selectAssetFromGalleryWithButton(button: UIButton): void;
self(): this;
}
declare class DKImageExtensionInlineCamera extends DKImageBaseExtension {
static alloc(): DKImageExtensionInlineCamera; // inherited from NSObject
static new(): DKImageExtensionInlineCamera; // inherited from NSObject
}
declare class DKImageExtensionNone extends DKImageBaseExtension {
static alloc(): DKImageExtensionNone; // inherited from NSObject
static new(): DKImageExtensionNone; // inherited from NSObject
}
declare class DKImageExtensionPhotoCropper extends DKImageBaseExtension {
static alloc(): DKImageExtensionPhotoCropper; // inherited from NSObject
static new(): DKImageExtensionPhotoCropper; // inherited from NSObject
}
declare const enum DKImageExtensionType {
Gallery = 0,
Camera = 1,
InlineCamera = 2,
PhotoEditor = 3
}
declare class DKImageGroupDataManager extends DKImageBaseManager implements PHPhotoLibraryChangeObserver {
static alloc(): DKImageGroupDataManager; // inherited from NSObject
static new(): DKImageGroupDataManager; // inherited from NSObject
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
photoLibraryDidChange(changeInstance: PHChange): void;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
}
declare class DKImageGroupDataManagerConfiguration extends NSObject implements NSCopying {
static alloc(): DKImageGroupDataManagerConfiguration; // inherited from NSObject
static new(): DKImageGroupDataManagerConfiguration; // inherited from NSObject
assetFetchOptions: PHFetchOptions;
fetchLimit: number;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
}
declare class DKImagePickerController extends DKUINavigationController implements UIAdaptivePresentationControllerDelegate {
static alloc(): DKImagePickerController; // inherited from NSObject
static new(): DKImagePickerController; // inherited from NSObject
UIDelegate: DKImagePickerControllerBaseUIDelegate;
allowMultipleTypes: boolean;
allowSelectAll: boolean;
allowSwipeToSelect: boolean;
allowsLandscape: boolean;
assetType: DKImagePickerControllerAssetType;
autoCloseOnSingleSelect: boolean;
didCancel: () => void;
didSelectAssets: (p1: NSArray<DKAsset>) => void;
readonly exportStatus: DKImagePickerControllerExportStatus;
exportStatusChanged: (p1: DKImagePickerControllerExportStatus) => void;
exporter: DKImageAssetExporter;
exportsWhenCompleted: boolean;
fetchLimit: number;
readonly groupDataManager: DKImageGroupDataManager;
inline_: boolean;
maxSelectableCount: number;
permissionViewColors: DKPermissionViewColors;
readonly selectedAssets: NSArray<DKAsset>;
selectedChanged: () => void;
shouldDismissViaUserAction: boolean;
showsCancelButton: boolean;
showsEmptyAlbums: boolean;
singleSelect: boolean;
sourceType: DKImagePickerControllerSourceType;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
adaptivePresentationStyleForPresentationController(controller: UIPresentationController): UIModalPresentationStyle;
adaptivePresentationStyleForPresentationControllerTraitCollection(controller: UIPresentationController, traitCollection: UITraitCollection): UIModalPresentationStyle;
canSelectWithAssetShowAlert(asset: DKAsset, showAlert: boolean): boolean;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
containsWithAsset(asset: DKAsset): boolean;
deselectAll(): void;
deselectWithAsset(asset: DKAsset): void;
dismiss(): void;
dismissCamera(): void;
done(): void;
handleSelectAll(): void;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
makeRootVC(): UIViewController;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
presentCamera(): void;
presentationControllerDidAttemptToDismiss(presentationController: UIPresentationController): void;
presentationControllerDidDismiss(presentationController: UIPresentationController): void;
presentationControllerShouldDismiss(presentationController: UIPresentationController): boolean;
presentationControllerViewControllerForAdaptivePresentationStyle(controller: UIPresentationController, style: UIModalPresentationStyle): UIViewController;
presentationControllerWillDismiss(presentationController: UIPresentationController): void;
presentationControllerWillPresentWithAdaptiveStyleTransitionCoordinator(presentationController: UIPresentationController, style: UIModalPresentationStyle, transitionCoordinator: UIViewControllerTransitionCoordinator): void;
reloadWith(dataManager: DKImageGroupDataManager): void;
removeSelectionWithAsset(asset: DKAsset): void;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
saveImage(image: UIImage, metadata: NSDictionary<any, any>, completeBlock: (p1: DKAsset) => void): void;
saveImageDataToAlbumForiOS8(imageData: NSData, metadata: NSDictionary<any, any>, completeBlock: (p1: DKAsset) => void): void;
saveImageDataToAlbumForiOS9(imageDataWithMetadata: NSData, completeBlock: (p1: DKAsset) => void): void;
saveImageToAlbum(image: UIImage, completeBlock: (p1: DKAsset) => void): void;
scrollToAnimated(indexPath: NSIndexPath, animated: boolean): void;
scrollToLastTappedIndexPathWithAnimated(animated: boolean): void;
selectWithAsset(asset: DKAsset): void;
selectWithAssets(assets: NSArray<DKAsset> | DKAsset[]): void;
self(): this;
setSelectedAssetsWithAssets(assets: NSArray<DKAsset> | DKAsset[]): void;
writeMetadataInto(metadata: NSDictionary<any, any>, imageData: NSData): NSData;
}
declare const enum DKImagePickerControllerAssetType {
AllPhotos = 0,
AllVideos = 1,
AllAssets = 2
}
interface DKImagePickerControllerAware {
imagePickerController: DKImagePickerController;
reload(): void;
}
declare var DKImagePickerControllerAware: {
prototype: DKImagePickerControllerAware;
};
declare class DKImagePickerControllerBaseUIDelegate extends NSObject implements DKImagePickerControllerUIDelegate {
static alloc(): DKImagePickerControllerBaseUIDelegate; // inherited from NSObject
static new(): DKImagePickerControllerBaseUIDelegate; // inherited from NSObject
imagePickerControllerCollectionCameraCell(): typeof NSObject;
imagePickerControllerCollectionImageCell(): typeof NSObject;
imagePickerControllerCollectionVideoCell(): typeof NSObject;
imagePickerControllerCollectionViewBackgroundColor(): UIColor;
imagePickerControllerDidDeselectAssets(imagePickerController: DKImagePickerController, didDeselectAssets: NSArray<DKAsset> | DKAsset[]): void;
imagePickerControllerDidReachMaxLimit(imagePickerController: DKImagePickerController): void;
imagePickerControllerDidSelectAssets(imagePickerController: DKImagePickerController, didSelectAssets: NSArray<DKAsset> | DKAsset[]): void;
imagePickerControllerFooterView(imagePickerController: DKImagePickerController): UIView;
imagePickerControllerGroupCell(): typeof NSObject;
imagePickerControllerGroupListPresentationStyle(): DKImagePickerGroupListPresentationStyle;
imagePickerControllerHeaderView(imagePickerController: DKImagePickerController): UIView;
imagePickerControllerHidesCancelButtonForVC(imagePickerController: DKImagePickerController, vc: UIViewController): void;
imagePickerControllerPrepareGroupListViewController(listViewController: UITableViewController): void;
imagePickerControllerSelectGroupButtonSelectedGroup(imagePickerController: DKImagePickerController, selectedGroup: DKAssetGroup): UIButton;
imagePickerControllerShowsCancelButtonForVC(imagePickerController: DKImagePickerController, vc: UIViewController): void;
layoutForImagePickerController(imagePickerController: DKImagePickerController): typeof NSObject;
prepareLayoutVc(imagePickerController: DKImagePickerController, vc: UIViewController): void;
}
declare const enum DKImagePickerControllerExportStatus {
None = 0,
Exporting = 1
}
declare class DKImagePickerControllerResource extends NSObject {
static alloc(): DKImagePickerControllerResource; // inherited from NSObject
static new(): DKImagePickerControllerResource; // inherited from NSObject
static setCustomImageBlock(value: (p1: string) => UIImage): void;
static setCustomLocalizationBlock(value: (p1: string) => string): void;
static customImageBlock: (p1: string) => UIImage;
static customLocalizationBlock: (p1: string) => string;
}
declare const enum DKImagePickerControllerSourceType {
Camera = 0,
Photo = 1,
Both = 2
}
interface DKImagePickerControllerUIDelegate {
imagePickerControllerCollectionCameraCell(): typeof NSObject;
imagePickerControllerCollectionImageCell(): typeof NSObject;
imagePickerControllerCollectionVideoCell(): typeof NSObject;
imagePickerControllerCollectionViewBackgroundColor(): UIColor;
imagePickerControllerDidDeselectAssets(imagePickerController: DKImagePickerController, didDeselectAssets: NSArray<DKAsset> | DKAsset[]): void;
imagePickerControllerDidReachMaxLimit(imagePickerController: DKImagePickerController): void;
imagePickerControllerDidSelectAssets(imagePickerController: DKImagePickerController, didSelectAssets: NSArray<DKAsset> | DKAsset[]): void;
imagePickerControllerFooterView(imagePickerController: DKImagePickerController): UIView;
imagePickerControllerGroupCell(): typeof NSObject;
imagePickerControllerGroupListPresentationStyle(): DKImagePickerGroupListPresentationStyle;
imagePickerControllerHeaderView(imagePickerController: DKImagePickerController): UIView;
imagePickerControllerHidesCancelButtonForVC(imagePickerController: DKImagePickerController, vc: UIViewController): void;
imagePickerControllerPrepareGroupListViewController(listViewController: UITableViewController): void;
imagePickerControllerSelectGroupButtonSelectedGroup(imagePickerController: DKImagePickerController, selectedGroup: DKAssetGroup): UIButton;
imagePickerControllerShowsCancelButtonForVC(imagePickerController: DKImagePickerController, vc: UIViewController): void;
layoutForImagePickerController(imagePickerController: DKImagePickerController): typeof NSObject;
prepareLayoutVc(imagePickerController: DKImagePickerController, vc: UIViewController): void;
}
declare var DKImagePickerControllerUIDelegate: {
prototype: DKImagePickerControllerUIDelegate;
};
declare var DKImagePickerControllerVersionNumber: number;
declare var DKImagePickerControllerVersionString: interop.Reference<number>;
declare const enum DKImagePickerGroupListPresentationStyle {
Popover = 0,
Presented = 1
}
declare class DKPermissionView extends UIView {
static alloc(): DKPermissionView; // inherited from NSObject
static appearance(): DKPermissionView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): DKPermissionView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): DKPermissionView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): DKPermissionView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): DKPermissionView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): DKPermissionView; // inherited from UIAppearance
static new(): DKPermissionView; // inherited from NSObject
gotoSettings(): void;
}
declare class DKPermissionViewColors extends NSObject {
static alloc(): DKPermissionViewColors; // inherited from NSObject
static new(): DKPermissionViewColors; // inherited from NSObject
}
declare class DKPopoverViewController extends UIViewController {
static alloc(): DKPopoverViewController; // inherited from NSObject
static dismissPopoverViewController(): void;
static new(): DKPopoverViewController; // inherited from NSObject
static popoverViewControllerFromViewArrowColor(viewController: UIViewController, fromView: UIView, arrowColor: UIColor): void;
arrowColor: UIColor;
}
declare class DKUINavigationController extends UINavigationController {
static alloc(): DKUINavigationController; // inherited from NSObject
static new(): DKUINavigationController; // inherited from NSObject
} | the_stack |
import '../../../test/common-test-setup-karma';
import './gr-settings-view';
import {GrSettingsView} from './gr-settings-view';
import {flush} from '@polymer/polymer/lib/legacy/polymer.dom';
import {GerritView} from '../../../services/router/router-model';
import {queryAll, queryAndAssert, stubRestApi} from '../../../test/test-utils';
import {
AuthInfo,
AccountDetailInfo,
EmailAddress,
PreferencesInfo,
ServerInfo,
TopMenuItemInfo,
} from '../../../types/common';
import {
createDefaultPreferences,
DateFormat,
DefaultBase,
DiffViewMode,
EmailFormat,
EmailStrategy,
TimeFormat,
} from '../../../constants/constants';
import * as MockInteractions from '@polymer/iron-test-helpers/mock-interactions';
import {
createAccountDetailWithId,
createPreferences,
createServerInfo,
} from '../../../test/test-data-generators';
import {GrSelect} from '../../shared/gr-select/gr-select';
import {AppElementSettingsParam} from '../../gr-app-types';
const basicFixture = fixtureFromElement('gr-settings-view');
const blankFixture = fixtureFromElement('div');
suite('gr-settings-view tests', () => {
let element: GrSettingsView;
let account: AccountDetailInfo;
let preferences: PreferencesInfo;
let config: ServerInfo;
function valueOf(title: string, id: string) {
const sections = element.root?.querySelectorAll(`#${id} section`) ?? [];
let titleEl;
for (let i = 0; i < sections.length; i++) {
titleEl = sections[i].querySelector('.title');
if (titleEl?.textContent?.trim() === title) {
const el = sections[i].querySelector('.value');
if (el) return el;
}
}
assert.fail(`element with title ${title} not found`);
}
// Because deepEqual isn't behaving in Safari.
function assertMenusEqual(
actual?: TopMenuItemInfo[],
expected?: TopMenuItemInfo[]
) {
if (actual === undefined) {
assert.fail("assertMenusEqual 'actual' param is undefined");
} else if (expected === undefined) {
assert.fail("assertMenusEqual 'expected' param is undefined");
}
assert.equal(actual.length, expected.length);
for (let i = 0; i < actual.length; i++) {
assert.equal(actual[i].name, expected[i].name);
assert.equal(actual[i].url, expected[i].url);
}
}
function stubAddAccountEmail(statusCode: number) {
return stubRestApi('addAccountEmail').callsFake(() =>
Promise.resolve({status: statusCode} as Response)
);
}
setup(async () => {
account = {
...createAccountDetailWithId(123),
name: 'user name',
email: 'user@email' as EmailAddress,
username: 'user username',
};
preferences = {
...createPreferences(),
changes_per_page: 25,
date_format: DateFormat.UK,
time_format: TimeFormat.HHMM_12,
diff_view: DiffViewMode.UNIFIED,
email_strategy: EmailStrategy.ENABLED,
email_format: EmailFormat.HTML_PLAINTEXT,
default_base_for_merges: DefaultBase.FIRST_PARENT,
relative_date_in_change_table: false,
size_bar_in_change_table: true,
my: [
{url: '/first/url', name: 'first name', target: '_blank'},
{url: '/second/url', name: 'second name', target: '_blank'},
] as TopMenuItemInfo[],
change_table: [],
};
config = createServerInfo();
stubRestApi('getAccount').returns(Promise.resolve(account));
stubRestApi('getPreferences').returns(Promise.resolve(preferences));
stubRestApi('getAccountEmails').returns(Promise.resolve(undefined));
stubRestApi('getConfig').returns(Promise.resolve(config));
element = basicFixture.instantiate();
// Allow the element to render.
if (element._testOnly_loadingPromise)
await element._testOnly_loadingPromise;
});
test('theme changing', async () => {
const reloadStub = sinon.stub(element, 'reloadPage');
window.localStorage.removeItem('dark-theme');
assert.isFalse(window.localStorage.getItem('dark-theme') === 'true');
const themeToggle = queryAndAssert(
element,
'.darkToggle paper-toggle-button'
);
MockInteractions.tap(themeToggle);
assert.isTrue(window.localStorage.getItem('dark-theme') === 'true');
assert.isTrue(reloadStub.calledOnce);
element._isDark = true;
await flush();
MockInteractions.tap(themeToggle);
assert.isFalse(window.localStorage.getItem('dark-theme') === 'true');
assert.isTrue(reloadStub.calledTwice);
});
test('calls the title-change event', () => {
const titleChangedStub = sinon.stub();
// Create a new view.
const newElement = document.createElement('gr-settings-view');
newElement.addEventListener('title-change', titleChangedStub);
const blank = blankFixture.instantiate();
blank.appendChild(newElement);
flush();
assert.isTrue(titleChangedStub.called);
assert.equal(titleChangedStub.getCall(0).args[0].detail.title, 'Settings');
});
test('user preferences', async () => {
// Rendered with the expected preferences selected.
assert.equal(
Number(
(
valueOf('Changes per page', 'preferences')!
.firstElementChild as GrSelect
).bindValue
),
preferences.changes_per_page
);
assert.equal(
(
valueOf('Date/time format', 'preferences')!
.firstElementChild as GrSelect
).bindValue,
preferences.date_format
);
assert.equal(
(valueOf('Date/time format', 'preferences')!.lastElementChild as GrSelect)
.bindValue,
preferences.time_format
);
assert.equal(
(
valueOf('Email notifications', 'preferences')!
.firstElementChild as GrSelect
).bindValue,
preferences.email_strategy
);
assert.equal(
(valueOf('Email format', 'preferences')!.firstElementChild as GrSelect)
.bindValue,
preferences.email_format
);
assert.equal(
(
valueOf('Default Base For Merges', 'preferences')!
.firstElementChild as GrSelect
).bindValue,
preferences.default_base_for_merges
);
assert.equal(
(
valueOf('Show Relative Dates In Changes Table', 'preferences')!
.firstElementChild as HTMLInputElement
).checked,
false
);
assert.equal(
(valueOf('Diff view', 'preferences')!.firstElementChild as GrSelect)
.bindValue,
preferences.diff_view
);
assert.equal(
(
valueOf('Show size bars in file list', 'preferences')!
.firstElementChild as HTMLInputElement
).checked,
true
);
assert.equal(
(
valueOf('Publish comments on push', 'preferences')!
.firstElementChild as HTMLInputElement
).checked,
false
);
assert.equal(
(
valueOf(
'Set new changes to "work in progress" by default',
'preferences'
)!.firstElementChild as HTMLInputElement
).checked,
false
);
assert.equal(
(
valueOf('Disable token highlighting on hover', 'preferences')!
.firstElementChild as HTMLInputElement
).checked,
false
);
assert.equal(
(
valueOf(
'Insert Signed-off-by Footer For Inline Edit Changes',
'preferences'
)!.firstElementChild as HTMLInputElement
).checked,
false
);
assert.isFalse(element._prefsChanged);
assert.isFalse(element._menuChanged);
const publishOnPush = valueOf('Publish comments on push', 'preferences')!
.firstElementChild!;
MockInteractions.tap(publishOnPush);
assert.isTrue(element._prefsChanged);
assert.isFalse(element._menuChanged);
stubRestApi('savePreferences').callsFake(prefs => {
assertMenusEqual(prefs.my, preferences.my);
assert.equal(prefs.publish_comments_on_push, true);
return Promise.resolve(createDefaultPreferences());
});
// Save the change.
await element._handleSavePreferences();
assert.isFalse(element._prefsChanged);
assert.isFalse(element._menuChanged);
});
test('publish comments on push', async () => {
const publishCommentsOnPush = valueOf(
'Publish comments on push',
'preferences'
)!.firstElementChild!;
MockInteractions.tap(publishCommentsOnPush);
assert.isFalse(element._menuChanged);
assert.isTrue(element._prefsChanged);
stubRestApi('savePreferences').callsFake(prefs => {
assert.equal(prefs.publish_comments_on_push, true);
return Promise.resolve(createDefaultPreferences());
});
// Save the change.
await element._handleSavePreferences();
assert.isFalse(element._prefsChanged);
assert.isFalse(element._menuChanged);
});
test('set new changes work-in-progress', async () => {
const newChangesWorkInProgress = valueOf(
'Set new changes to "work in progress" by default',
'preferences'
)!.firstElementChild!;
MockInteractions.tap(newChangesWorkInProgress);
assert.isFalse(element._menuChanged);
assert.isTrue(element._prefsChanged);
stubRestApi('savePreferences').callsFake(prefs => {
assert.equal(prefs.work_in_progress_by_default, true);
return Promise.resolve(createDefaultPreferences());
});
// Save the change.
await element._handleSavePreferences();
assert.isFalse(element._prefsChanged);
assert.isFalse(element._menuChanged);
});
test('menu', async () => {
assert.isFalse(element._menuChanged);
assert.isFalse(element._prefsChanged);
assertMenusEqual(element._localMenu, preferences.my);
const menu = element.$.menu.firstElementChild!;
let tableRows = queryAll(menu, 'tbody tr');
// let tableRows = menu.root.querySelectorAll('tbody tr');
assert.equal(tableRows.length, preferences.my.length);
// Add a menu item:
element.splice('_localMenu', 1, 0, {name: 'foo', url: 'bar', target: ''});
flush();
// tableRows = menu.root.querySelectorAll('tbody tr');
tableRows = queryAll(menu, 'tbody tr');
assert.equal(tableRows.length, preferences.my.length + 1);
assert.isTrue(element._menuChanged);
assert.isFalse(element._prefsChanged);
stubRestApi('savePreferences').callsFake(prefs => {
assertMenusEqual(prefs.my, element._localMenu);
return Promise.resolve(createDefaultPreferences());
});
await element._handleSaveMenu();
assert.isFalse(element._menuChanged);
assert.isFalse(element._prefsChanged);
assertMenusEqual(element.prefs.my, element._localMenu);
});
test('add email validation', () => {
assert.isFalse(element._isNewEmailValid('invalid email'));
assert.isTrue(element._isNewEmailValid('vaguely@valid.email'));
assert.isFalse(
element._computeAddEmailButtonEnabled('invalid email', true)
);
assert.isFalse(
element._computeAddEmailButtonEnabled('vaguely@valid.email', true)
);
assert.isTrue(
element._computeAddEmailButtonEnabled('vaguely@valid.email', false)
);
});
test('add email does not save invalid', () => {
const addEmailStub = stubAddAccountEmail(201);
assert.isFalse(element._addingEmail);
assert.isNotOk(element._lastSentVerificationEmail);
element._newEmail = 'invalid email';
element._handleAddEmailButton();
assert.isFalse(element._addingEmail);
assert.isFalse(addEmailStub.called);
assert.isNotOk(element._lastSentVerificationEmail);
assert.isFalse(addEmailStub.called);
});
test('add email does save valid', async () => {
const addEmailStub = stubAddAccountEmail(201);
assert.isFalse(element._addingEmail);
assert.isNotOk(element._lastSentVerificationEmail);
element._newEmail = 'valid@email.com';
element._handleAddEmailButton();
assert.isTrue(element._addingEmail);
assert.isTrue(addEmailStub.called);
assert.isTrue(addEmailStub.called);
await addEmailStub.lastCall.returnValue;
assert.isOk(element._lastSentVerificationEmail);
});
test('add email does not set last-email if error', async () => {
const addEmailStub = stubAddAccountEmail(500);
assert.isNotOk(element._lastSentVerificationEmail);
element._newEmail = 'valid@email.com';
element._handleAddEmailButton();
assert.isTrue(addEmailStub.called);
await addEmailStub.lastCall.returnValue;
assert.isNotOk(element._lastSentVerificationEmail);
});
test('emails are loaded without emailToken', () => {
const emailEditorLoadDataStub = sinon.stub(
element.$.emailEditor,
'loadData'
);
element.params = {
view: GerritView.SETTINGS,
} as AppElementSettingsParam;
element.connectedCallback();
assert.isTrue(emailEditorLoadDataStub.calledOnce);
});
test('_handleSaveChangeTable', () => {
let newColumns = ['Owner', 'Project', 'Branch'];
element._localChangeTableColumns = newColumns.slice(0);
element._showNumber = false;
element._handleSaveChangeTable();
assert.deepEqual(element.prefs.change_table, newColumns);
assert.isNotOk(element.prefs.legacycid_in_change_table);
newColumns = ['Size'];
element._localChangeTableColumns = newColumns;
element._showNumber = true;
element._handleSaveChangeTable();
assert.deepEqual(element.prefs.change_table, newColumns);
assert.isTrue(element.prefs.legacycid_in_change_table);
});
test('reset menu item back to default', async () => {
const originalMenu = {
...createDefaultPreferences(),
my: [
{url: '/first/url', name: 'first name', target: '_blank'},
{url: '/second/url', name: 'second name', target: '_blank'},
{url: '/third/url', name: 'third name', target: '_blank'},
] as TopMenuItemInfo[],
};
stubRestApi('getDefaultPreferences').returns(Promise.resolve(originalMenu));
const updatedMenu = [
{url: '/first/url', name: 'first name', target: '_blank'},
{url: '/second/url', name: 'second name', target: '_blank'},
{url: '/third/url', name: 'third name', target: '_blank'},
{url: '/fourth/url', name: 'fourth name', target: '_blank'},
];
element.set('_localMenu', updatedMenu);
await element._handleResetMenuButton();
assertMenusEqual(element._localMenu, originalMenu.my);
});
test('test that reset button is called', () => {
const overlayOpen = sinon.stub(element, '_handleResetMenuButton');
MockInteractions.tap(element.$.resetButton);
assert.isTrue(overlayOpen.called);
});
test('_showHttpAuth', () => {
const serverConfig: ServerInfo = {
...createServerInfo(),
auth: {
git_basic_auth_policy: 'HTTP',
} as AuthInfo,
};
assert.isTrue(element._showHttpAuth(serverConfig));
serverConfig.auth.git_basic_auth_policy = 'HTTP_LDAP';
assert.isTrue(element._showHttpAuth(serverConfig));
serverConfig.auth.git_basic_auth_policy = 'LDAP';
assert.isFalse(element._showHttpAuth(serverConfig));
serverConfig.auth.git_basic_auth_policy = 'OAUTH';
assert.isFalse(element._showHttpAuth(serverConfig));
assert.isFalse(element._showHttpAuth(undefined));
});
suite('_getFilterDocsLink', () => {
test('with http: docs base URL', () => {
const base = 'http://example.com/';
const result = element._getFilterDocsLink(base);
assert.equal(result, 'http://example.com/user-notify.html');
});
test('with http: docs base URL without slash', () => {
const base = 'http://example.com';
const result = element._getFilterDocsLink(base);
assert.equal(result, 'http://example.com/user-notify.html');
});
test('with https: docs base URL', () => {
const base = 'https://example.com/';
const result = element._getFilterDocsLink(base);
assert.equal(result, 'https://example.com/user-notify.html');
});
test('without docs base URL', () => {
const result = element._getFilterDocsLink(null);
assert.equal(
result,
'https://gerrit-review.googlesource.com/' +
'Documentation/user-notify.html'
);
});
test('ignores non HTTP links', () => {
const base = 'javascript://alert("evil");';
const result = element._getFilterDocsLink(base);
assert.equal(
result,
'https://gerrit-review.googlesource.com/' +
'Documentation/user-notify.html'
);
});
});
suite('when email verification token is provided', () => {
let resolveConfirm: (
value: string | PromiseLike<string | null> | null
) => void;
let confirmEmailStub: sinon.SinonStub;
let emailEditorLoadDataStub: sinon.SinonStub;
setup(() => {
emailEditorLoadDataStub = sinon.stub(element.$.emailEditor, 'loadData');
confirmEmailStub = stubRestApi('confirmEmail').returns(
new Promise(resolve => {
resolveConfirm = resolve;
})
);
element.params = {view: GerritView.SETTINGS, emailToken: 'foo'};
element.connectedCallback();
});
test('it is used to confirm email via rest API', () => {
assert.isTrue(confirmEmailStub.calledOnce);
assert.isTrue(confirmEmailStub.calledWith('foo'));
});
test('emails are not loaded initially', () => {
assert.isFalse(emailEditorLoadDataStub.called);
});
test('user emails are loaded after email confirmed', async () => {
resolveConfirm('bar');
await element._testOnly_loadingPromise;
assert.isTrue(emailEditorLoadDataStub.calledOnce);
});
test('show-alert is fired when email is confirmed', async () => {
const dispatchEventSpy = sinon.spy(element, 'dispatchEvent');
resolveConfirm('bar');
await element._testOnly_loadingPromise;
assert.equal(
(dispatchEventSpy.lastCall.args[0] as CustomEvent).type,
'show-alert'
);
assert.deepEqual(
(dispatchEventSpy.lastCall.args[0] as CustomEvent).detail,
{message: 'bar'}
);
});
});
}); | the_stack |
import {Feed, StepStateChangeEvent} from "../../../model/feed/feed.model";
import {DefineFeedService, FeedEditStateChangeEvent} from "../services/define-feed.service";
import {StateService, Transition} from "@uirouter/angular";
import {OnDestroy, OnInit, TemplateRef} from "@angular/core";
import {SaveFeedResponse} from "../model/save-feed-response.model";
import {AbstractControl, FormGroup} from "@angular/forms";
import {Step} from "../../../model/feed/feed-step.model";
import {FEED_DEFINITION_STATE_NAME, FEED_DEFINITION_SUMMARY_STATE_NAME, FEED_SETUP_GUIDE_STATE_NAME} from "../../../model/feed/feed-constants";
import {FeedLoadingService} from "../services/feed-loading-service";
import {TdDialogService} from "@covalent/core/dialogs";
import {FeedSideNavService} from "../services/feed-side-nav.service";
import {Observable} from "rxjs/Observable";
import {ISubscription} from "rxjs/Subscription";
import 'rxjs/add/operator/distinctUntilChanged';
import * as _ from "underscore"
import {CloneUtil} from "../../../../common/utils/clone-util";
import {StringUtils} from "../../../../common/utils/StringUtils";
export abstract class AbstractFeedStepComponent implements OnInit, OnDestroy {
/**
* The feed
*/
public feed: Feed;
/**
* The step
*/
public step: Step;
/**
* The name of this step
* @return {string}
*/
public abstract getStepName(): string;
/**
* flag indicate that the form is valid for this step
*/
public formValid: boolean;
/**
* indicate that this step is subscribing to form changes
*/
private subscribingToFormChanges: boolean;
private feedEditStateChangeEvent: ISubscription;
private feedStepStateChangeSubscription:ISubscription;
protected redirectAfterSave:boolean = true;
protected constructor(protected defineFeedService: DefineFeedService, protected stateService: StateService,
protected feedLoadingService: FeedLoadingService, protected dialogService: TdDialogService,
protected feedSideNavService: FeedSideNavService) {
this.feedEditStateChangeEvent = this.defineFeedService.subscribeToFeedEditStateChangeEvent(this._onFeedEditStateChange.bind(this))
}
/**
* component initialized
* run thing base logic then fire public init method
*/
ngOnInit() {
this.initData();
this.init();
}
/**
* Component is getting destroyed.
* Call any callbacks
*/
ngOnDestroy() {
try {
if (this.feedEditStateChangeEvent) {
this.feedEditStateChangeEvent.unsubscribe();
}
if(this.feedStepStateChangeSubscription){
this.feedStepStateChangeSubscription.unsubscribe();
}
this.destroy();
} catch (err) {
console.error("error in destroy", err);
}
}
private _onFeedEditStateChange(event: FeedEditStateChangeEvent) {
this.feed.readonly = event.readonly;
this.feed.accessControl = event.accessControl;
this.feedStateChange(event);
}
orignalVal: string;
/**
* Allow users to subscribe to their form and mark for changes
* @param {FormGroup} formGroup
* @param {number} debounceTime
*/
subscribeToFormChanges(formGroup: AbstractControl, debounceTime: number = 500) {
this.subscribingToFormChanges = true;
// initialize stream
const formValueChanges$ = formGroup.statusChanges;
// subscribe to the stream
formValueChanges$.debounceTime(debounceTime).subscribe(changes => {
this.formValid = changes == "VALID" //&& this.tableForm.validate(undefined);
this.step.valid = this.formValid;
this.step.validator.hasFormErrors = !this.formValid;
//callback
this.onFormStatusChanged(this.formValid);
});
}
subscribeToFormDirtyCheck(formGroup: AbstractControl, debounceTime: number = 500) {
//watch for form changes and mark dirty
//start watching for form changes after init time
formGroup.valueChanges.debounceTime(debounceTime).subscribe(change => {
const changeStringVal = StringUtils.stringify(change);
if(!formGroup.dirty) {
//stringify without circular ref
this.orignalVal = changeStringVal
}
else if(this.orignalVal !==changeStringVal){
this.onFormChanged(change);
}
});
}
public goToSetupGuideSummary(){
let redirectState = FEED_SETUP_GUIDE_STATE_NAME;
this.stateService.go(redirectState,{feedId:this.feed.id, refresh:false}, {location:'replace'})
}
/**
* When a feed changes from read only to edit
* @param {FeedEditStateChangeEvent} event
*/
public feedStateChange(event: FeedEditStateChangeEvent) {
}
public onStepStateChangeEvent(event:StepStateChangeEvent){
this.defineFeedService.onStepStateChangeEvent(event)
}
/**
* Initialize the component
*/
public init() {
}
/**
* called when the user moves away from this step
*/
public destroy() {
}
/**
* Callback when a form changes state
*/
public onFormChanged(change: any) {
if (!this.feed.readonly) {
this.step.markDirty();
}
}
/**
* Callback when a form changes state
*/
public onFormStatusChanged(valid: boolean) {
this.step.setComplete(valid);
}
/**
* Override and return a template ref that will be displayed and used in the toolbar
* @return {TemplateRef<any>}
*/
getToolbarTemplateRef(): TemplateRef<any> {
return undefined;
}
/**
* Called before save to apply updates to the feed model
*/
protected applyUpdatesToFeed(): (Observable<any> | boolean | null) {
return null;
}
/**
* When a feed edit is cancelled, reset the forms
* @param {Feed} feed
*/
protected cancelFeedEdit(markAsReadOnly: boolean = false, openSideNav:boolean = true) {
//get the old feed
if (markAsReadOnly) {
this.defineFeedService.markFeedAsReadonly();
}
this.feed = this.defineFeedService.getFeed();
if(openSideNav){
this.defineFeedService.sideNavStateChanged({opened:true})
}
this.goToSetupGuideSummary();
}
registerLoading(): void {
this.feedLoadingService.registerLoading();
}
resolveLoading(): void {
this.feedLoadingService.resolveLoading();
}
onSave() {
this.registerLoading();
let saveCall = () => {
//notify the subscribers on the actual save call so they can listen when the save finishes
this.defineFeedService.saveFeed(this.feed, false,this.step).subscribe((response: SaveFeedResponse) => {
this.defineFeedService.openSnackBar("Saved the feed ", 3000);
this.resolveLoading();
this.step.clearDirty();
if(this.redirectAfterSave) {
this.goToSetupGuideSummary();
}
}, error1 => {
this.resolveLoading()
this.defineFeedService.openSnackBar("Error saving the feed ", 3000);
})
}
let updates = this.applyUpdatesToFeed();
if (updates == false) {
//no op. errors applying update
this.resolveLoading();
}
else if (updates && updates instanceof Observable) {
updates.subscribe(
(response: any) => {
if((response != undefined && typeof response == "boolean" && response == false)) {
//skip since response is false
this.resolveLoading();
} else {
saveCall();
}
},
(error: any) => {
console.warn("Failed to save feed", error);
this.resolveLoading();
});
}
else {
saveCall();
}
}
/**
* public method called from the step-card.component
*/
onCancelEdit() {
this.cancelFeedEdit();
/*
//warn if there are pending changes
if ((this.subscribingToFormChanges && this.step.isDirty()) || !this.subscribingToFormChanges) {
this.dialogService.openConfirm({
message: 'Are you sure you want to canel editing ' + this.feed.feedName + '? All pending edits will be lost.',
disableClose: true,
title: 'Confirm Cancel Edit', //OPTIONAL, hides if not provided
cancelButton: 'No', //OPTIONAL, defaults to 'CANCEL'
acceptButton: 'Yes', //OPTIONAL, defaults to 'ACCEPT'
width: '500px', //OPTIONAL, defaults to 400px
}).afterClosed().subscribe((accept: boolean) => {
if (accept) {
this.cancelFeedEdit();
} else {
// DO SOMETHING ELSE
}
});
}
else {
this.cancelFeedEdit();
}
*/
}
/**
* is the user allowed to leave this component and transition to a new state?
* @return {boolean}
*/
uiCanExit(newTransition: Transition): (Promise<any> | boolean) {
return this.defineFeedService.uiCanExit(this.step, newTransition)
}
protected initData() {
if (this.feed == undefined) {
this.feed = this.defineFeedService.getFeed();
if (this.feed == undefined) {
this.stateService.go(FEED_DEFINITION_STATE_NAME + ".select-template")
}
}
this.feedStepStateChangeSubscription = this.feed.subscribeToStepStateChanges(this.onStepStateChangeEvent.bind(this))
this.step = this.feed.steps.find(step => step.systemName == this.getStepName());
if (this.step) {
this.step.dirty = false;
this.step.visited = true;
//register any custom toolbar actions
let toolbarActionTemplate = this.getToolbarTemplateRef();
if (toolbarActionTemplate) {
this.feedSideNavService.registerStepToolbarActionTemplate(this.step.name, toolbarActionTemplate)
}
this.defineFeedService.setCurrentStep(this.step)
let valid = this.feed.validate(true);
}
else {
//ERROR OUT
}
}
} | the_stack |
import {
IExecuteFunctions,
} from 'n8n-core';
import {
IDataObject,
ILoadOptionsFunctions,
INodeExecutionData,
INodePropertyOptions,
INodeType,
INodeTypeDescription,
NodeApiError,
} from 'n8n-workflow';
import {
adjustAddresses,
getFilterQuery,
getOrderFields,
getProductAttributes,
magentoApiRequest,
magentoApiRequestAllItems,
sort,
validateJSON,
} from './GenericFunctions';
import {
customerFields,
customerOperations,
} from './CustomerDescription';
import {
orderFields,
orderOperations,
} from './OrderDescription';
import {
productFields,
productOperations,
} from './ProductDescription';
import {
invoiceFields,
invoiceOperations,
} from './InvoiceDescription';
import {
CustomAttribute,
CustomerAttributeMetadata,
Filter,
NewCustomer,
NewProduct,
Search,
} from './Types';
import {
capitalCase,
} from 'change-case';
export class Magento2 implements INodeType {
description: INodeTypeDescription = {
displayName: 'Magento 2',
name: 'magento2',
icon: 'file:magento.svg',
group: ['input'],
version: 1,
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
description: 'Consume Magento API',
defaults: {
name: 'Magento 2',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'magento2Api',
required: true,
},
],
properties: [
{
displayName: 'Resource',
name: 'resource',
type: 'options',
options: [
{
name: 'Customer',
value: 'customer',
},
{
name: 'Invoice',
value: 'invoice',
},
{
name: 'Order',
value: 'order',
},
{
name: 'Product',
value: 'product',
},
],
default: 'customer',
description: 'The resource to operate on',
},
...customerOperations,
...customerFields,
...invoiceOperations,
...invoiceFields,
...orderOperations,
...orderFields,
...productOperations,
...productFields,
],
};
methods = {
loadOptions: {
async getCountries(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
//https://magento.redoc.ly/2.3.7-admin/tag/directorycountries
const countries = await magentoApiRequest.call(this, 'GET', '/rest/default/V1/directory/countries');
const returnData: INodePropertyOptions[] = [];
for (const country of countries) {
returnData.push({
name: country.full_name_english,
value: country.id,
});
}
returnData.sort(sort);
return returnData;
},
async getGroups(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
//https://magento.redoc.ly/2.3.7-admin/tag/customerGroupsdefault#operation/customerGroupManagementV1GetDefaultGroupGet
const group = await magentoApiRequest.call(this, 'GET', '/rest/default/V1/customerGroups/default');
const returnData: INodePropertyOptions[] = [];
returnData.push({
name: group.code,
value: group.id,
});
returnData.sort(sort);
return returnData;
},
async getStores(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
//https://magento.redoc.ly/2.3.7-admin/tag/storestoreConfigs
const stores = await magentoApiRequest.call(this, 'GET', '/rest/default/V1/store/storeConfigs');
const returnData: INodePropertyOptions[] = [];
for (const store of stores) {
returnData.push({
name: store.base_url,
value: store.id,
});
}
returnData.sort(sort);
return returnData;
},
async getWebsites(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
//https://magento.redoc.ly/2.3.7-admin/tag/storewebsites
const websites = await magentoApiRequest.call(this, 'GET', '/rest/default/V1/store/websites');
const returnData: INodePropertyOptions[] = [];
for (const website of websites) {
returnData.push({
name: website.name,
value: website.id,
});
}
returnData.sort(sort);
return returnData;
},
async getCustomAttributes(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
//https://magento.redoc.ly/2.3.7-admin/tag/attributeMetadatacustomer#operation/customerCustomerMetadataV1GetAllAttributesMetadataGet
const resource = this.getCurrentNodeParameter('resource') as string;
const attributes = await magentoApiRequest.call(this, 'GET', `/rest/default/V1/attributeMetadata/${resource}`) as CustomerAttributeMetadata[];
const returnData: INodePropertyOptions[] = [];
for (const attribute of attributes) {
if (attribute.system === false && attribute.frontend_label !== '') {
returnData.push({
name: attribute.frontend_label as string,
value: attribute.attribute_code as string,
});
}
}
returnData.sort(sort);
return returnData;
},
async getSystemAttributes(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
//https://magento.redoc.ly/2.3.7-admin/tag/attributeMetadatacustomer#operation/customerCustomerMetadataV1GetAllAttributesMetadataGet
const resource = this.getCurrentNodeParameter('resource') as string;
const attributes = await magentoApiRequest.call(this, 'GET', `/rest/default/V1/attributeMetadata/${resource}`) as CustomerAttributeMetadata[];
const returnData: INodePropertyOptions[] = [];
for (const attribute of attributes) {
if (attribute.system === true && attribute.frontend_label !== null) {
returnData.push({
name: attribute.frontend_label as string,
value: attribute.attribute_code as string,
});
}
}
returnData.sort(sort);
return returnData;
},
async getProductTypes(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
//https://magento.redoc.ly/2.3.7-admin/tag/productslinkstypes
const types = await magentoApiRequest.call(this, 'GET', `/rest/default/V1/products/types`) as IDataObject[];
const returnData: INodePropertyOptions[] = [];
for (const type of types) {
returnData.push({
name: type.label as string,
value: type.name as string,
});
}
returnData.sort(sort);
return returnData;
},
async getCategories(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
//https://magento.redoc.ly/2.3.7-admin/tag/categories#operation/catalogCategoryManagementV1GetTreeGet
const { items: categories } = await magentoApiRequest.call(this, 'GET', `/rest/default/V1/categories/list`, {}, {
search_criteria: {
filter_groups: [
{
filters: [
{
field: 'is_active',
condition_type: 'eq',
value: 1,
},
],
},
],
},
}) as { items: IDataObject[] };
const returnData: INodePropertyOptions[] = [];
for (const category of categories) {
returnData.push({
name: category.name as string,
value: category.id as string,
});
}
returnData.sort(sort);
return returnData;
},
async getAttributeSets(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
//https://magento.redoc.ly/2.3.7-admin/tag/productsattribute-setssetslist#operation/catalogAttributeSetRepositoryV1GetListGet
const { items: attributeSets } = await magentoApiRequest.call(this, 'GET', `/rest/default/V1/products/attribute-sets/sets/list`, {}, {
search_criteria: 0,
}) as { items: IDataObject[] };
const returnData: INodePropertyOptions[] = [];
for (const attributeSet of attributeSets) {
returnData.push({
name: attributeSet.attribute_set_name as string,
value: attributeSet.attribute_set_id as string,
});
}
returnData.sort(sort);
return returnData;
},
async getFilterableCustomerAttributes(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
return getProductAttributes.call(this, (attribute) => attribute.is_filterable === true);
},
async getProductAttributes(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
return getProductAttributes.call(this);
},
// async getProductAttributesFields(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
// return getProductAttributes.call(this, undefined, { name: '*', value: '*', description: 'All properties' });
// },
async getFilterableProductAttributes(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
return getProductAttributes.call(this, (attribute) => attribute.is_searchable === '1');
},
async getSortableProductAttributes(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
return getProductAttributes.call(this, (attribute) => attribute.used_for_sort_by === true);
},
async getOrderAttributes(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
return getOrderFields().map(field => ({ name: capitalCase(field), value: field })).sort(sort);
},
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: IDataObject[] = [];
const length = (items.length as unknown) as number;
const timezone = this.getTimezone();
let responseData;
const resource = this.getNodeParameter('resource', 0) as string;
const operation = this.getNodeParameter('operation', 0) as string;
for (let i = 0; i < length; i++) {
try {
if (resource === 'customer') {
if (operation === 'create') {
// https://magento.redoc.ly/2.3.7-admin/tag/customerscustomerId#operation/customerCustomerRepositoryV1SavePut
const email = this.getNodeParameter('email', i) as string;
const firstname = this.getNodeParameter('firstname', i) as string;
const lastname = this.getNodeParameter('lastname', i) as string;
const {
addresses,
customAttributes,
password,
...rest
} = this.getNodeParameter('additionalFields', i) as {
addresses: {
address: [{
street: string,
}]
};
customAttributes: {
customAttribute: CustomAttribute[],
},
password: string,
};
const body: NewCustomer = {
customer: {
email,
firstname,
lastname,
},
};
body.customer!.addresses = adjustAddresses(addresses?.address || []);
body.customer!.custom_attributes = customAttributes?.customAttribute || {};
body.customer!.extension_attributes = ['amazon_id', 'is_subscribed', 'vertex_customer_code', 'vertex_customer_country']
// tslint:disable-next-line: no-any
.reduce((obj, value: string): any => {
if ((rest as IDataObject).hasOwnProperty(value)) {
const data = Object.assign(obj, { [value]: (rest as IDataObject)[value] });
delete (rest as IDataObject)[value];
return data;
} else {
return obj;
}
}, {});
if (password) {
body.password = password;
}
Object.assign(body.customer, rest);
responseData = await magentoApiRequest.call(this, 'POST', '/rest/V1/customers', body);
}
if (operation === 'delete') {
//https://magento.redoc.ly/2.3.7-admin/tag/customerscustomerId#operation/customerCustomerRepositoryV1SavePut
const customerId = this.getNodeParameter('customerId', i) as string;
responseData = await magentoApiRequest.call(this, 'DELETE', `/rest/default/V1/customers/${customerId}`);
responseData = { success: true };
}
if (operation === 'get') {
//https://magento.redoc.ly/2.3.7-admin/tag/customerscustomerId#operation/customerCustomerRepositoryV1GetByIdGet
const customerId = this.getNodeParameter('customerId', i) as string;
responseData = await magentoApiRequest.call(this, 'GET', `/rest/default/V1/customers/${customerId}`);
}
if (operation === 'getAll') {
//https://magento.redoc.ly/2.3.7-admin/tag/customerssearch
const filterType = this.getNodeParameter('filterType', i) as string;
const sort = this.getNodeParameter('options.sort', i, {}) as { sort: [{ direction: string, field: string }] };
const returnAll = this.getNodeParameter('returnAll', 0) as boolean;
let qs: Search = {};
if (filterType === 'manual') {
const filters = this.getNodeParameter('filters', i) as { conditions: Filter[] };
const matchType = this.getNodeParameter('matchType', i) as string;
qs = getFilterQuery(Object.assign(filters, { matchType }, sort));
} else if (filterType === 'json') {
const filterJson = this.getNodeParameter('filterJson', i) as string;
if (validateJSON(filterJson) !== undefined) {
qs = JSON.parse(filterJson);
} else {
throw new NodeApiError(this.getNode(), { message: 'Filter (JSON) must be a valid json' });
}
} else {
qs = {
search_criteria: {},
};
if (Object.keys(sort).length !== 0) {
qs.search_criteria = {
sort_orders: sort.sort,
};
}
}
if (returnAll === true) {
qs.search_criteria!.page_size = 100;
responseData = await magentoApiRequestAllItems.call(this, 'items', 'GET', `/rest/default/V1/customers/search`, {}, qs as unknown as IDataObject);
} else {
const limit = this.getNodeParameter('limit', 0) as number;
qs.search_criteria!.page_size = limit;
responseData = await magentoApiRequest.call(this, 'GET', `/rest/default/V1/customers/search`, {}, qs as unknown as IDataObject);
responseData = responseData.items;
}
}
if (operation === 'update') {
//https://magento.redoc.ly/2.3.7-admin/tag/customerscustomerId#operation/customerCustomerRepositoryV1SavePut
const customerId = this.getNodeParameter('customerId', i) as string;
const firstName = this.getNodeParameter('firstName', i) as string;
const lastName = this.getNodeParameter('lastName', i) as string;
const email = this.getNodeParameter('email', i) as string;
const {
addresses,
customAttributes,
password,
...rest
} = this.getNodeParameter('updateFields', i) as {
addresses: {
address: [{
street: string,
}]
};
customAttributes: {
customAttribute: CustomAttribute[],
},
password: string,
};
const body: NewCustomer = {
customer: {
email,
firstname: firstName,
lastname: lastName,
id: parseInt(customerId, 10),
website_id: 0,
},
};
body.customer!.addresses = adjustAddresses(addresses?.address || []);
body.customer!.custom_attributes = customAttributes?.customAttribute || {};
body.customer!.extension_attributes = ['amazon_id', 'is_subscribed', 'vertex_customer_code', 'vertex_customer_country']
// tslint:disable-next-line: no-any
.reduce((obj, value: string): any => {
if ((rest as IDataObject).hasOwnProperty(value)) {
const data = Object.assign(obj, { [value]: (rest as IDataObject)[value] });
delete (rest as IDataObject)[value];
return data;
} else {
return obj;
}
}, {});
if (password) {
body.password = password;
}
Object.assign(body.customer, rest);
responseData = await magentoApiRequest.call(this, 'PUT', `/rest/V1/customers/${customerId}`, body);
}
}
if (resource === 'invoice') {
if (operation === 'create') {
///https://magento.redoc.ly/2.3.7-admin/tag/orderorderIdinvoice
const orderId = this.getNodeParameter('orderId', i) as string;
responseData = await magentoApiRequest.call(this, 'POST', `/rest/default/V1/order/${orderId}/invoice`);
responseData = { success: true };
}
}
if (resource === 'order') {
if (operation === 'cancel') {
//https://magento.redoc.ly/2.3.7-admin/tag/ordersidcancel
const orderId = this.getNodeParameter('orderId', i) as string;
responseData = await magentoApiRequest.call(this, 'POST', `/rest/default/V1/orders/${orderId}/cancel`);
responseData = { success: true };
}
if (operation === 'get') {
//https://magento.redoc.ly/2.3.7-admin/tag/ordersid#operation/salesOrderRepositoryV1GetGet
const orderId = this.getNodeParameter('orderId', i) as string;
responseData = await magentoApiRequest.call(this, 'GET', `/rest/default/V1/orders/${orderId}`);
}
if (operation === 'ship') {
///https://magento.redoc.ly/2.3.7-admin/tag/orderorderIdship#operation/salesShipOrderV1ExecutePost
const orderId = this.getNodeParameter('orderId', i) as string;
responseData = await magentoApiRequest.call(this, 'POST', `/rest/default/V1/order/${orderId}/ship`);
responseData = { success: true };
}
if (operation === 'getAll') {
//https://magento.redoc.ly/2.3.7-admin/tag/orders#operation/salesOrderRepositoryV1GetListGet
const filterType = this.getNodeParameter('filterType', i) as string;
const sort = this.getNodeParameter('options.sort', i, {}) as { sort: [{ direction: string, field: string }] };
const returnAll = this.getNodeParameter('returnAll', 0) as boolean;
let qs: Search = {};
if (filterType === 'manual') {
const filters = this.getNodeParameter('filters', i) as { conditions: Filter[] };
const matchType = this.getNodeParameter('matchType', i) as string;
qs = getFilterQuery(Object.assign(filters, { matchType }, sort));
} else if (filterType === 'json') {
const filterJson = this.getNodeParameter('filterJson', i) as string;
if (validateJSON(filterJson) !== undefined) {
qs = JSON.parse(filterJson);
} else {
throw new NodeApiError(this.getNode(), { message: 'Filter (JSON) must be a valid json' });
}
} else {
qs = {
search_criteria: {},
};
if (Object.keys(sort).length !== 0) {
qs.search_criteria = {
sort_orders: sort.sort,
};
}
}
if (returnAll === true) {
qs.search_criteria!.page_size = 100;
responseData = await magentoApiRequestAllItems.call(this, 'items', 'GET', `/rest/default/V1/orders`, {}, qs as unknown as IDataObject);
} else {
const limit = this.getNodeParameter('limit', 0) as number;
qs.search_criteria!.page_size = limit;
responseData = await magentoApiRequest.call(this, 'GET', `/rest/default/V1/orders`, {}, qs as unknown as IDataObject);
responseData = responseData.items;
}
}
}
if (resource === 'product') {
if (operation === 'create') {
// https://magento.redoc.ly/2.3.7-admin/tag/products#operation/catalogProductRepositoryV1SavePost
const sku = this.getNodeParameter('sku', i) as string;
const name = this.getNodeParameter('name', i) as string;
const attributeSetId = this.getNodeParameter('attributeSetId', i) as string;
const price = this.getNodeParameter('price', i) as number;
const {
customAttributes,
category,
...rest
} = this.getNodeParameter('additionalFields', i) as {
customAttributes: {
customAttribute: CustomAttribute[],
},
category: string,
};
const body: NewProduct = {
product: {
sku,
name,
attribute_set_id: parseInt(attributeSetId, 10),
price,
},
};
body.product!.custom_attributes = customAttributes?.customAttribute || {};
Object.assign(body.product, rest);
responseData = await magentoApiRequest.call(this, 'POST', '/rest/default/V1/products', body);
}
if (operation === 'delete') {
//https://magento.redoc.ly/2.3.7-admin/tag/productssku#operation/catalogProductRepositoryV1DeleteByIdDelete
const sku = this.getNodeParameter('sku', i) as string;
responseData = await magentoApiRequest.call(this, 'DELETE', `/rest/default/V1/products/${sku}`);
responseData = { success: true };
}
if (operation === 'get') {
//https://magento.redoc.ly/2.3.7-admin/tag/productssku#operation/catalogProductRepositoryV1GetGet
const sku = this.getNodeParameter('sku', i) as string;
responseData = await magentoApiRequest.call(this, 'GET', `/rest/default/V1/products/${sku}`);
}
if (operation === 'getAll') {
//https://magento.redoc.ly/2.3.7-admin/tag/customerssearch
const filterType = this.getNodeParameter('filterType', i) as string;
const sort = this.getNodeParameter('options.sort', i, {}) as { sort: [{ direction: string, field: string }] };
const returnAll = this.getNodeParameter('returnAll', 0) as boolean;
let qs: Search = {};
if (filterType === 'manual') {
const filters = this.getNodeParameter('filters', i) as { conditions: Filter[] };
const matchType = this.getNodeParameter('matchType', i) as string;
qs = getFilterQuery(Object.assign(filters, { matchType }, sort));
} else if (filterType === 'json') {
const filterJson = this.getNodeParameter('filterJson', i) as string;
if (validateJSON(filterJson) !== undefined) {
qs = JSON.parse(filterJson);
} else {
throw new NodeApiError(this.getNode(), { message: 'Filter (JSON) must be a valid json' });
}
} else {
qs = {
search_criteria: {},
};
if (Object.keys(sort).length !== 0) {
qs.search_criteria = {
sort_orders: sort.sort,
};
}
}
if (returnAll === true) {
qs.search_criteria!.page_size = 100;
responseData = await magentoApiRequestAllItems.call(this, 'items', 'GET', `/rest/default/V1/products`, {}, qs as unknown as IDataObject);
} else {
const limit = this.getNodeParameter('limit', 0) as number;
qs.search_criteria!.page_size = limit;
responseData = await magentoApiRequest.call(this, 'GET', `/rest/default/V1/products`, {}, qs as unknown as IDataObject);
responseData = responseData.items;
}
}
if (operation === 'update') {
//https://magento.redoc.ly/2.3.7-admin/tag/productssku#operation/catalogProductRepositoryV1SavePut
const sku = this.getNodeParameter('sku', i) as string;
const {
customAttributes,
...rest
} = this.getNodeParameter('updateFields', i) as {
customAttributes: {
customAttribute: CustomAttribute[],
},
};
if (!Object.keys(rest).length) {
throw new NodeApiError(this.getNode(), { message: 'At least one parameter has to be updated' });
}
const body: NewProduct = {
product: {
sku,
},
};
body.product!.custom_attributes = customAttributes?.customAttribute || {};
Object.assign(body.product, rest);
responseData = await magentoApiRequest.call(this, 'PUT', `/rest/default/V1/products/${sku}`, body);
}
}
Array.isArray(responseData)
? returnData.push(...responseData)
: returnData.push(responseData);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.message });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
} | the_stack |
import { basename, dirname, extname, relative, sep } from 'path';
import {
ArrayLiteralExpression,
CallExpression,
ClassDeclaration,
createClassDeclaration,
createIdentifier,
createNamedImports,
Decorator,
Expression,
Identifier,
ImportDeclaration,
ImportSpecifier,
NamedImports,
Node,
NodeArray,
ObjectLiteralExpression,
PropertyAccessExpression,
PropertyAssignment,
SourceFile,
StringLiteral,
SyntaxKind,
TransformationContext,
TransformerFactory,
updateCall,
updateClassDeclaration,
updateImportClause,
updateImportDeclaration,
updateSourceFile,
visitEachChild,
VisitResult
} from 'typescript';
import { Logger } from '../logger/logger';
import * as Constants from '../util/constants';
import { FileCache } from '../util/file-cache';
import { changeExtension, getParsedDeepLinkConfig, getStringPropertyValue, replaceAll, toUnixPath } from '../util/helpers';
import { BuildContext, ChangedFile, DeepLinkConfigEntry, DeepLinkDecoratorAndClass, DeepLinkPathInfo, File } from '../util/interfaces';
import {
NG_MODULE_DECORATOR_TEXT,
appendAfter,
findNodes,
getClassDeclarations,
getNgModuleClassName,
getNgModuleDecorator,
getNgModuleObjectLiteralArg,
getTypescriptSourceFile,
getNodeStringContent,
replaceNode,
} from '../util/typescript-utils';
import { transpileTsString } from '../transpile';
export function getDeepLinkData(appNgModuleFilePath: string, fileCache: FileCache, isAot: boolean): Map<string, DeepLinkConfigEntry> {
// we only care about analyzing a subset of typescript files, so do that for efficiency
const typescriptFiles = filterTypescriptFilesForDeepLinks(fileCache);
const deepLinkConfigEntries = new Map<string, DeepLinkConfigEntry>();
const segmentSet = new Set<string>();
typescriptFiles.forEach(file => {
const sourceFile = getTypescriptSourceFile(file.path, file.content);
const deepLinkDecoratorData = getDeepLinkDecoratorContentForSourceFile(sourceFile);
if (deepLinkDecoratorData) {
// sweet, the page has a DeepLinkDecorator, which means it meets the criteria to process that bad boy
const pathInfo = getNgModuleDataFromPage(appNgModuleFilePath, file.path, deepLinkDecoratorData.className, fileCache, isAot);
const deepLinkConfigEntry = Object.assign({}, deepLinkDecoratorData, pathInfo);
if (deepLinkConfigEntries.has(deepLinkConfigEntry.name)) {
// gadzooks, it's a duplicate name
throw new Error(`There are multiple entries in the deeplink config with the name of ${deepLinkConfigEntry.name}`);
}
if (segmentSet.has(deepLinkConfigEntry.segment)) {
// gadzooks, it's a duplicate segment
throw new Error(`There are multiple entries in the deeplink config with the segment of ${deepLinkConfigEntry.segment}`);
}
segmentSet.add(deepLinkConfigEntry.segment);
deepLinkConfigEntries.set(deepLinkConfigEntry.name, deepLinkConfigEntry);
}
});
return deepLinkConfigEntries;
}
export function filterTypescriptFilesForDeepLinks(fileCache: FileCache): File[] {
return fileCache.getAll().filter(file => isDeepLinkingFile(file.path));
}
export function isDeepLinkingFile(filePath: string) {
const deepLinksDir = getStringPropertyValue(Constants.ENV_VAR_DEEPLINKS_DIR) + sep;
const moduleSuffix = getStringPropertyValue(Constants.ENV_NG_MODULE_FILE_NAME_SUFFIX);
const result = extname(filePath) === '.ts' && filePath.indexOf(moduleSuffix) === -1 && filePath.indexOf(deepLinksDir) >= 0;
return result;
}
export function getNgModulePathFromCorrespondingPage(filePath: string) {
const newExtension = getStringPropertyValue(Constants.ENV_NG_MODULE_FILE_NAME_SUFFIX);
return changeExtension(filePath, newExtension);
}
export function getRelativePathToPageNgModuleFromAppNgModule(pathToAppNgModule: string, pathToPageNgModule: string) {
return relative(dirname(pathToAppNgModule), pathToPageNgModule);
}
export function getNgModuleDataFromPage(appNgModuleFilePath: string, filePath: string, className: string, fileCache: FileCache, isAot: boolean): DeepLinkPathInfo {
const ngModulePath = getNgModulePathFromCorrespondingPage(filePath);
let ngModuleFile = fileCache.get(ngModulePath);
if (!ngModuleFile) {
throw new Error(`${filePath} has a @IonicPage decorator, but it does not have a corresponding "NgModule" at ${ngModulePath}`);
}
// get the class declaration out of NgModule class content
const exportedClassName = getNgModuleClassName(ngModuleFile.path, ngModuleFile.content);
const relativePathToAppNgModule = getRelativePathToPageNgModuleFromAppNgModule(appNgModuleFilePath, ngModulePath);
const absolutePath = isAot ? changeExtension(ngModulePath, '.ngfactory.js') : changeExtension(ngModulePath, '.ts');
const userlandModulePath = isAot ? changeExtension(relativePathToAppNgModule, '.ngfactory') : changeExtension(relativePathToAppNgModule, '');
const namedExport = isAot ? `${exportedClassName}NgFactory` : exportedClassName;
return {
absolutePath: absolutePath,
userlandModulePath: toUnixPath(userlandModulePath),
className: namedExport
};
}
export function getDeepLinkDecoratorContentForSourceFile(sourceFile: SourceFile): DeepLinkDecoratorAndClass {
const classDeclarations = getClassDeclarations(sourceFile);
const defaultSegment = basename(changeExtension(sourceFile.fileName, ''));
const list: DeepLinkDecoratorAndClass[] = [];
classDeclarations.forEach(classDeclaration => {
if (classDeclaration.decorators) {
classDeclaration.decorators.forEach(decorator => {
const className = (classDeclaration.name as Identifier).text;
if (decorator.expression && (decorator.expression as CallExpression).expression && ((decorator.expression as CallExpression).expression as Identifier).text === DEEPLINK_DECORATOR_TEXT) {
const deepLinkArgs = (decorator.expression as CallExpression).arguments;
let deepLinkObject: ObjectLiteralExpression = null;
if (deepLinkArgs && deepLinkArgs.length) {
deepLinkObject = deepLinkArgs[0] as ObjectLiteralExpression;
}
let propertyList: Node[] = [];
if (deepLinkObject && deepLinkObject.properties) {
propertyList = deepLinkObject.properties as any as Node[]; // TODO this typing got jacked up
}
const deepLinkName = getStringValueFromDeepLinkDecorator(sourceFile, propertyList, className, DEEPLINK_DECORATOR_NAME_ATTRIBUTE);
const deepLinkSegment = getStringValueFromDeepLinkDecorator(sourceFile, propertyList, defaultSegment, DEEPLINK_DECORATOR_SEGMENT_ATTRIBUTE);
const deepLinkPriority = getStringValueFromDeepLinkDecorator(sourceFile, propertyList, 'low', DEEPLINK_DECORATOR_PRIORITY_ATTRIBUTE);
const deepLinkDefaultHistory = getArrayValueFromDeepLinkDecorator(sourceFile, propertyList, [], DEEPLINK_DECORATOR_DEFAULT_HISTORY_ATTRIBUTE);
const rawStringContent = getNodeStringContent(sourceFile, decorator.expression);
list.push({
name: deepLinkName,
segment: deepLinkSegment,
priority: deepLinkPriority,
defaultHistory: deepLinkDefaultHistory,
rawString: rawStringContent,
className: className
});
}
});
}
});
if (list.length > 1) {
throw new Error('Only one @IonicPage decorator is allowed per file.');
}
if (list.length === 1) {
return list[0];
}
return null;
}
function getStringValueFromDeepLinkDecorator(sourceFile: SourceFile, propertyNodeList: Node[], defaultValue: string, identifierToLookFor: string) {
try {
let valueToReturn = defaultValue;
Logger.debug(`[DeepLinking util] getNameValueFromDeepLinkDecorator: Setting default deep link ${identifierToLookFor} to ${defaultValue}`);
propertyNodeList.forEach(propertyNode => {
if (propertyNode && (propertyNode as PropertyAssignment).name && ((propertyNode as PropertyAssignment).name as Identifier).text === identifierToLookFor) {
const initializer = ((propertyNode as PropertyAssignment).initializer as Expression);
let stringContent = getNodeStringContent(sourceFile, initializer);
stringContent = replaceAll(stringContent, '\'', '');
stringContent = replaceAll(stringContent, '`', '');
stringContent = replaceAll(stringContent, '"', '');
stringContent = stringContent.trim();
valueToReturn = stringContent;
}
});
Logger.debug(`[DeepLinking util] getNameValueFromDeepLinkDecorator: DeepLink ${identifierToLookFor} set to ${valueToReturn}`);
return valueToReturn;
} catch (ex) {
Logger.error(`Failed to parse the @IonicPage decorator. The ${identifierToLookFor} must be an array of strings`);
throw ex;
}
}
function getArrayValueFromDeepLinkDecorator(sourceFile: SourceFile, propertyNodeList: Node[], defaultValue: string[], identifierToLookFor: string) {
try {
let valueToReturn = defaultValue;
Logger.debug(`[DeepLinking util] getArrayValueFromDeepLinkDecorator: Setting default deep link ${identifierToLookFor} to ${defaultValue}`);
propertyNodeList.forEach(propertyNode => {
if (propertyNode && (propertyNode as PropertyAssignment).name && ((propertyNode as PropertyAssignment).name as Identifier).text === identifierToLookFor) {
const initializer = ((propertyNode as PropertyAssignment).initializer as ArrayLiteralExpression);
if (initializer && initializer.elements) {
const stringArray = initializer.elements.map((element: Identifier) => {
let elementText = element.text;
elementText = replaceAll(elementText, '\'', '');
elementText = replaceAll(elementText, '`', '');
elementText = replaceAll(elementText, '"', '');
elementText = elementText.trim();
return elementText;
});
valueToReturn = stringArray;
}
}
});
Logger.debug(`[DeepLinking util] getNameValueFromDeepLinkDecorator: DeepLink ${identifierToLookFor} set to ${valueToReturn}`);
return valueToReturn;
} catch (ex) {
Logger.error(`Failed to parse the @IonicPage decorator. The ${identifierToLookFor} must be an array of strings`);
throw ex;
}
}
export function hasExistingDeepLinkConfig(appNgModuleFilePath: string, appNgModuleFileContent: string) {
const sourceFile = getTypescriptSourceFile(appNgModuleFilePath, appNgModuleFileContent);
const decorator = getNgModuleDecorator(appNgModuleFilePath, sourceFile);
const functionCall = getIonicModuleForRootCall(decorator);
if (functionCall.arguments.length <= 2) {
return false;
}
const deepLinkConfigArg = functionCall.arguments[2];
if (deepLinkConfigArg.kind === SyntaxKind.NullKeyword || deepLinkConfigArg.kind === SyntaxKind.UndefinedKeyword) {
return false;
}
if (deepLinkConfigArg.kind === SyntaxKind.ObjectLiteralExpression) {
return true;
}
if ((deepLinkConfigArg as Identifier).text && (deepLinkConfigArg as Identifier).text.length > 0) {
return true;
}
}
function getIonicModuleForRootCall(decorator: Decorator) {
const argument = getNgModuleObjectLiteralArg(decorator);
const properties = argument.properties.filter((property: PropertyAssignment) => {
return (property.name as Identifier).text === NG_MODULE_IMPORT_DECLARATION;
});
if (properties.length === 0) {
throw new Error('Could not find "import" property in NgModule arguments');
}
if (properties.length > 1) {
throw new Error('Found multiple "import" properties in NgModule arguments. Only one is allowed');
}
const property = properties[0] as PropertyAssignment;
const importArrayLiteral = property.initializer as ArrayLiteralExpression;
const functionsInImport = importArrayLiteral.elements.filter(element => {
return element.kind === SyntaxKind.CallExpression;
});
const ionicModuleFunctionCalls = functionsInImport.filter((functionNode: CallExpression) => {
return (functionNode.expression
&& (functionNode.expression as PropertyAccessExpression).name
&& (functionNode.expression as PropertyAccessExpression).name.text === FOR_ROOT_METHOD
&& ((functionNode.expression as PropertyAccessExpression).expression as Identifier)
&& ((functionNode.expression as PropertyAccessExpression).expression as Identifier).text === IONIC_MODULE_NAME);
});
if (ionicModuleFunctionCalls.length === 0) {
throw new Error('Could not find IonicModule.forRoot call in "imports"');
}
if (ionicModuleFunctionCalls.length > 1) {
throw new Error('Found multiple IonicModule.forRoot calls in "imports". Only one is allowed');
}
return ionicModuleFunctionCalls[0] as CallExpression;
}
export function convertDeepLinkConfigEntriesToString(entries: Map<string, DeepLinkConfigEntry>) {
const individualLinks: string[] = [];
entries.forEach(entry => {
individualLinks.push(convertDeepLinkEntryToJsObjectString(entry));
});
const deepLinkConfigString =
`
{
links: [
${individualLinks.join(',\n ')}
]
}`;
return deepLinkConfigString;
}
export function convertDeepLinkEntryToJsObjectString(entry: DeepLinkConfigEntry) {
const defaultHistoryWithQuotes = entry.defaultHistory.map(defaultHistoryEntry => `'${defaultHistoryEntry}'`);
const segmentString = entry.segment && entry.segment.length ? `'${entry.segment}'` : null;
return `{ loadChildren: '${entry.userlandModulePath}${LOAD_CHILDREN_SEPARATOR}${entry.className}', name: '${entry.name}', segment: ${segmentString}, priority: '${entry.priority}', defaultHistory: [${defaultHistoryWithQuotes.join(', ')}] }`;
}
export function updateAppNgModuleWithDeepLinkConfig(context: BuildContext, deepLinkString: string, changedFiles: ChangedFile[]) {
const appNgModulePath = getStringPropertyValue(Constants.ENV_APP_NG_MODULE_PATH);
const appNgModuleFile = context.fileCache.get(appNgModulePath);
if (!appNgModuleFile) {
throw new Error(`App NgModule ${appNgModulePath} not found in cache`);
}
const updatedAppNgModuleContent = getUpdatedAppNgModuleContentWithDeepLinkConfig(appNgModulePath, appNgModuleFile.content, deepLinkString);
context.fileCache.set(appNgModulePath, { path: appNgModulePath, content: updatedAppNgModuleContent});
if (changedFiles) {
changedFiles.push({
event: 'change',
filePath: appNgModulePath,
ext: extname(appNgModulePath).toLowerCase()
});
}
}
export function getUpdatedAppNgModuleContentWithDeepLinkConfig(appNgModuleFilePath: string, appNgModuleFileContent: string, deepLinkStringContent: string) {
let sourceFile = getTypescriptSourceFile(appNgModuleFilePath, appNgModuleFileContent);
let decorator = getNgModuleDecorator(appNgModuleFilePath, sourceFile);
let functionCall = getIonicModuleForRootCall(decorator);
if (functionCall.arguments.length === 1) {
appNgModuleFileContent = addDefaultSecondArgumentToAppNgModule(appNgModuleFileContent, functionCall);
sourceFile = getTypescriptSourceFile(appNgModuleFilePath, appNgModuleFileContent);
decorator = getNgModuleDecorator(appNgModuleFilePath, sourceFile);
functionCall = getIonicModuleForRootCall(decorator);
}
if (functionCall.arguments.length === 2) {
// we need to add the node
return addDeepLinkArgumentToAppNgModule(appNgModuleFileContent, functionCall, deepLinkStringContent);
}
// we need to replace whatever node exists here with the deeplink config
return replaceNode(appNgModuleFilePath, appNgModuleFileContent, functionCall.arguments[2], deepLinkStringContent);
}
export function getUpdatedAppNgModuleFactoryContentWithDeepLinksConfig(appNgModuleFactoryFileContent: string, deepLinkStringContent: string) {
// tried to do this with typescript API, wasn't clear on how to do it
const regex = /this.*?DeepLinkConfigToken.*?=([\s\S]*?);/g;
const results = regex.exec(appNgModuleFactoryFileContent);
if (results && results.length === 2) {
const actualString = results[0];
const chunkToReplace = results[1];
const fullStringToReplace = actualString.replace(chunkToReplace, deepLinkStringContent);
return appNgModuleFactoryFileContent.replace(actualString, fullStringToReplace);
}
throw new Error('The RegExp to find the DeepLinkConfigToken did not return valid data');
}
export function addDefaultSecondArgumentToAppNgModule(appNgModuleFileContent: string, ionicModuleForRoot: CallExpression) {
const argOneNode = ionicModuleForRoot.arguments[0];
const updatedFileContent = appendAfter(appNgModuleFileContent, argOneNode, ', {}');
return updatedFileContent;
}
export function addDeepLinkArgumentToAppNgModule(appNgModuleFileContent: string, ionicModuleForRoot: CallExpression, deepLinkString: string) {
const argTwoNode = ionicModuleForRoot.arguments[1];
const updatedFileContent = appendAfter(appNgModuleFileContent, argTwoNode, `, ${deepLinkString}`);
return updatedFileContent;
}
export function generateDefaultDeepLinkNgModuleContent(pageFilePath: string, className: string) {
const importFrom = basename(pageFilePath, '.ts');
return `
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { ${className} } from './${importFrom}';
@NgModule({
declarations: [
${className},
],
imports: [
IonicPageModule.forChild(${className})
]
})
export class ${className}Module {}
`;
}
export function purgeDeepLinkDecoratorTSTransform(): TransformerFactory<SourceFile> {
return purgeDeepLinkDecoratorTSTransformImpl;
}
export function purgeDeepLinkDecoratorTSTransformImpl(transformContext: TransformationContext) {
function visitClassDeclaration(classDeclaration: ClassDeclaration) {
let hasDeepLinkDecorator = false;
const diffDecorators: Decorator[] = [];
for (const decorator of classDeclaration.decorators || []) {
if (decorator.expression && (decorator.expression as CallExpression).expression
&& ((decorator.expression as CallExpression).expression as Identifier).text === DEEPLINK_DECORATOR_TEXT) {
hasDeepLinkDecorator = true;
} else {
diffDecorators.push(decorator);
}
}
if (hasDeepLinkDecorator) {
return updateClassDeclaration(
classDeclaration,
diffDecorators,
classDeclaration.modifiers,
classDeclaration.name,
classDeclaration.typeParameters,
classDeclaration.heritageClauses,
classDeclaration.members
);
}
return classDeclaration;
}
function visitImportDeclaration(importDeclaration: ImportDeclaration, sourceFile: SourceFile): ImportDeclaration {
if (importDeclaration.moduleSpecifier
&& (importDeclaration.moduleSpecifier as StringLiteral).text === 'ionic-angular'
&& importDeclaration.importClause
&& importDeclaration.importClause.namedBindings
&& (importDeclaration.importClause.namedBindings as NamedImports).elements
) {
// loop over each import and store it
const importSpecifiers: ImportSpecifier[] = [];
(importDeclaration.importClause.namedBindings as NamedImports).elements.forEach((importSpecifier: ImportSpecifier) => {
if (importSpecifier.name.text !== DEEPLINK_DECORATOR_TEXT) {
importSpecifiers.push(importSpecifier);
}
});
const emptyNamedImports = createNamedImports(importSpecifiers);
const newImportClause = updateImportClause(importDeclaration.importClause, importDeclaration.importClause.name, emptyNamedImports);
return updateImportDeclaration(
importDeclaration,
importDeclaration.decorators,
importDeclaration.modifiers,
newImportClause,
importDeclaration.moduleSpecifier
);
}
return importDeclaration;
}
function visit(node: Node, sourceFile: SourceFile): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
return visitClassDeclaration(node as ClassDeclaration);
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(node as ImportDeclaration, sourceFile);
default:
return visitEachChild(node, (node) => {
return visit(node, sourceFile);
}, transformContext);
}
}
return (sourceFile: SourceFile) => {
return visit(sourceFile, sourceFile) as SourceFile;
};
}
export function purgeDeepLinkDecorator(inputText: string): string {
const sourceFile = getTypescriptSourceFile('', inputText);
const classDeclarations = getClassDeclarations(sourceFile);
const toRemove: Node[] = [];
let toReturn: string = inputText;
for (const classDeclaration of classDeclarations) {
for (const decorator of classDeclaration.decorators || []) {
if (decorator.expression && (decorator.expression as CallExpression).expression
&& ((decorator.expression as CallExpression).expression as Identifier).text === DEEPLINK_DECORATOR_TEXT) {
toRemove.push(decorator);
}
}
}
toRemove.forEach(node => {
toReturn = replaceNode('', inputText, node, '');
});
toReturn = purgeDeepLinkImport(toReturn);
return toReturn;
}
export function purgeDeepLinkImport(inputText: string): string {
const sourceFile = getTypescriptSourceFile('', inputText);
const importDeclarations = findNodes(sourceFile, sourceFile, SyntaxKind.ImportDeclaration) as ImportDeclaration[];
importDeclarations.forEach(importDeclaration => {
if (importDeclaration.moduleSpecifier
&& (importDeclaration.moduleSpecifier as StringLiteral).text === 'ionic-angular'
&& importDeclaration.importClause
&& importDeclaration.importClause.namedBindings
&& (importDeclaration.importClause.namedBindings as NamedImports).elements
) {
// loop over each import and store it
let decoratorIsImported = false;
const namedImportStrings: string[] = [];
(importDeclaration.importClause.namedBindings as NamedImports).elements.forEach((importSpecifier: ImportSpecifier) => {
if (importSpecifier.name.text === DEEPLINK_DECORATOR_TEXT) {
decoratorIsImported = true;
} else {
namedImportStrings.push(importSpecifier.name.text as string);
}
});
// okay, cool. If namedImportStrings is empty, then just remove the entire import statement
// otherwise, just replace the named imports with the namedImportStrings separated by a comma
if (decoratorIsImported) {
if (namedImportStrings.length) {
// okay cool, we only want to remove some of these homies
const stringRepresentation = namedImportStrings.join(', ');
const namedImportString = `{ ${stringRepresentation} }`;
inputText = replaceNode('', inputText, importDeclaration.importClause.namedBindings, namedImportString);
} else {
// remove the entire import statement
inputText = replaceNode('', inputText, importDeclaration, '');
}
}
}
});
return inputText;
}
export function getInjectDeepLinkConfigTypescriptTransform() {
const deepLinkString = convertDeepLinkConfigEntriesToString(getParsedDeepLinkConfig());
const appNgModulePath = toUnixPath(getStringPropertyValue(Constants.ENV_APP_NG_MODULE_PATH));
return injectDeepLinkConfigTypescriptTransform(deepLinkString, appNgModulePath);
}
export function injectDeepLinkConfigTypescriptTransform(deepLinkString: string, appNgModuleFilePath: string): TransformerFactory<SourceFile> {
function visitDecoratorNode(decorator: Decorator, sourceFile: SourceFile): Decorator {
if (decorator.expression && (decorator.expression as CallExpression).expression && ((decorator.expression as CallExpression).expression as Identifier).text === NG_MODULE_DECORATOR_TEXT) {
// okay cool, we have the ng module
let functionCall = getIonicModuleForRootCall(decorator);
const updatedArgs: any[] = functionCall.arguments as any as any[];
if (updatedArgs.length === 1) {
updatedArgs.push(createIdentifier('{ }'));
}
if (updatedArgs.length === 2) {
updatedArgs.push(createIdentifier(deepLinkString));
}
functionCall = updateCall(
functionCall,
functionCall.expression,
functionCall.typeArguments,
updatedArgs
);
// loop over the parent elements and replace the IonicModule expression with ours'
for (let i = 0; i < ((functionCall.parent as any).elements || []).length; i++) {
const element = (functionCall.parent as any).elements[i];
if (element.king === SyntaxKind.CallExpression
&& element.expression
&& element.expression.expression
&& element.expression.expression.escapedText === 'IonicModule'
) {
(functionCall.parent as any).elements[i] = functionCall;
}
}
}
return decorator;
}
return (transformContext: TransformationContext) => {
function visit(node: Node, sourceFile: SourceFile, sourceFilePath: string): VisitResult<Node> {
if (sourceFilePath !== appNgModuleFilePath) {
return node;
}
switch (node.kind) {
case SyntaxKind.Decorator:
return visitDecoratorNode(node as Decorator, sourceFile);
default:
return visitEachChild(node, (node) => {
return visit(node, sourceFile, sourceFilePath);
}, transformContext);
}
}
return (sourceFile: SourceFile) => {
return visit(sourceFile, sourceFile, sourceFile.fileName) as SourceFile;
};
};
}
const DEEPLINK_DECORATOR_TEXT = 'IonicPage';
const DEEPLINK_DECORATOR_NAME_ATTRIBUTE = 'name';
const DEEPLINK_DECORATOR_SEGMENT_ATTRIBUTE = 'segment';
const DEEPLINK_DECORATOR_PRIORITY_ATTRIBUTE = 'priority';
const DEEPLINK_DECORATOR_DEFAULT_HISTORY_ATTRIBUTE = 'defaultHistory';
const NG_MODULE_IMPORT_DECLARATION = 'imports';
const IONIC_MODULE_NAME = 'IonicModule';
const FOR_ROOT_METHOD = 'forRoot';
const LOAD_CHILDREN_SEPARATOR = '#'; | the_stack |
import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as doctrine from 'doctrine';
const RULE_NAME = 'valid-jsdoc';
let OPTIONS: any;
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING = {
missingBrace: 'JSDoc type missing brace',
syntaxError: 'JSDoc syntax error',
missingParameterType: (name: string) => `missing JSDoc parameter type for '${name}'`,
missingParameterDescription: (name: string) => `missing JSDoc parameter description for '${name}'`,
duplicateParameter: (name: string) => `duplicate JSDoc parameter '${name}'`,
unexpectedTag: (title: string) => `unexpected @${title} tag; function has no return statement`,
missingReturnType: 'missing JSDoc return type',
missingReturnDescription: 'missing JSDoc return description',
prefer: (name: string) => `use @${name} instead`,
missingReturn: (param: string) => `missing JSDoc @${param || 'returns'} for function`,
wrongParam: (expected: string, actual: string) => `expected JSDoc for '${expected}' but found '${actual}'`,
missingParam: (name: string) => `missing JSDoc for parameter '${name}'`,
wrongDescription: 'JSDoc description does not satisfy the regex pattern',
invalidRegexDescription: (error: string) => `configured matchDescription is an invalid RegExp. Error: ${error}`
};
public static metadata: Lint.IRuleMetadata = {
ruleName: RULE_NAME,
hasFix: false,
description: 'enforce valid JSDoc comments',
rationale: Lint.Utils.dedent`
[JSDoc](http://usejsdoc.org/) generates application programming interface (API) documentation
from specially-formatted comments in JavaScript code. So does [typedoc](http://typedoc.org/).
If comments are invalid because of typing mistakes, then documentation will be incomplete.
If comments are inconsistent because they are not updated when function definitions are
modified, then readers might become confused.
`,
optionsDescription: Lint.Utils.dedent`
This rule has an object option:
* \`"prefer"\` enforces consistent documentation tags specified by an object whose properties
mean instead of key use value (for example, \`"return": "returns"\` means
instead of \`@return\` use \`@returns\`)
* \`"preferType"\` enforces consistent type strings specified by an object whose properties
mean instead of key use value (for example, \`"object": "Object"\` means
instead of \`object\` use \`Object\`)
* \`"requireReturn"\` requires a return tag:
* \`true\` (default) *even if* the function or method does not have a return statement
(this option value does not apply to constructors)
* \`false\` *if and only if* the function or method has a return statement (this option
value does apply to constructors)
* \`"requireParamType"\`: \`false\` allows missing type in param tags
* \`"requireReturnType"\`: \`false\` allows missing type in return tags
* \`"matchDescription"\` specifies (as a string) a regular expression to match the description
in each JSDoc comment (for example, \`".+"\` requires a description;
this option does not apply to descriptions in parameter or return
tags)
* \`"requireParamDescription"\`: \`false\` allows missing description in parameter tags
* \`"requireReturnDescription"\`: \`false\` allows missing description in return tags
`,
options: {
type: 'object',
properties: {
prefer: {
type: 'object',
additionalProperties: {
type: 'string'
}
},
preferType: {
type: 'object',
additionalProperties: {
type: 'string'
}
},
requireReturn: {
type: 'boolean'
},
requireParamDescription: {
type: 'boolean'
},
requireReturnDescription: {
type: 'boolean'
},
matchDescription: {
type: 'string'
},
requireParamType: {
type: 'boolean'
},
requireReturnType: {
type: 'boolean'
}
},
additionalProperties: false
},
optionExamples: [
Lint.Utils.dedent`
"${RULE_NAME}": [true]
`,
Lint.Utils.dedent`
"${RULE_NAME}": [true, {
"prefer": {
"return": "returns"
},
"requireReturn": false,
"requireParamDescription": true,
"requireReturnDescription": true,
"matchDescription": "^[A-Z][A-Za-z0-9\\\\s]*[.]$"
}]
`
],
typescriptOnly: false,
type: 'maintainability'
};
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
let opts = this.getOptions().ruleArguments;
OPTIONS = {
prefer: {},
requireReturn: true,
requireParamType: true,
requireReturnType: true,
requireParamDescription: true,
requireReturnDescription: true,
matchDescription: ''
};
if (opts && opts.length > 0) {
if (opts[0].prefer) {
OPTIONS.prefer = opts[0].prefer;
}
OPTIONS.requireReturn = opts[0].requireReturn !== false;
OPTIONS.requireParamType = opts[0].requireParamType !== false;
OPTIONS.requireReturnType = opts[0].requireReturnType !== false;
OPTIONS.requireParamDescription = opts[0].requireParamDescription !== false;
OPTIONS.requireReturnDescription = opts[0].requireReturnDescription !== false;
OPTIONS.matchDescription = opts[0].matchDescription;
}
const walker = new ValidJsdocWalker(sourceFile, this.getOptions());
return this.applyWithWalker(walker);
}
}
declare interface IReturnPresent {
node: ts.Node;
returnPresent: boolean;
isVoidOrNever: boolean;
}
interface IJSComment {
comments?: string;
start?: number;
width?: number;
}
class ValidJsdocWalker extends Lint.RuleWalker {
private fns: Array<IReturnPresent> = [];
protected visitSourceFile(node: ts.SourceFile) {
super.visitSourceFile(node);
}
protected visitNode(node: ts.Node) {
if (node.kind === ts.SyntaxKind.ClassExpression) {
this.visitClassExpression(node as ts.ClassExpression);
}
else {
super.visitNode(node);
}
}
protected visitArrowFunction(node: ts.ArrowFunction) {
this.startFunction(node);
super.visitArrowFunction(node);
this.checkJSDoc(node);
}
protected visitFunctionExpression(node: ts.FunctionExpression) {
this.startFunction(node);
super.visitFunctionExpression(node);
this.checkJSDoc(node);
}
protected visitFunctionDeclaration(node: ts.FunctionDeclaration) {
this.startFunction(node);
super.visitFunctionDeclaration(node);
this.checkJSDoc(node);
}
protected visitClassExpression(node: ts.ClassExpression) {
this.startFunction(node);
super.visitClassExpression(node);
this.checkJSDoc(node);
}
protected visitClassDeclaration(node: ts.ClassDeclaration) {
this.startFunction(node);
super.visitClassDeclaration(node);
this.checkJSDoc(node);
}
protected visitMethodDeclaration(node: ts.MethodDeclaration) {
this.startFunction(node);
super.visitMethodDeclaration(node);
this.checkJSDoc(node);
}
protected visitConstructorDeclaration(node: ts.ConstructorDeclaration) {
this.startFunction(node);
super.visitConstructorDeclaration(node);
this.checkJSDoc(node);
}
protected visitReturnStatement(node: ts.ReturnStatement) {
this.addReturn(node);
super.visitReturnStatement(node);
}
private startFunction(node: ts.Node) {
let returnPresent = false;
let isVoidOrNever = false;
let returnType: ts.TypeNode | undefined;
if (node.kind === ts.SyntaxKind.ArrowFunction && (node as ts.ArrowFunction).body.kind !== ts.SyntaxKind.Block)
returnPresent = true;
if (this.isTypeClass(node))
returnPresent = true;
returnType = (node as ts.SignatureDeclaration).type;
if (returnType !== undefined) {
switch (returnType.kind) {
case ts.SyntaxKind.VoidKeyword:
case ts.SyntaxKind.NeverKeyword:
isVoidOrNever = true;
break;
}
}
this.fns.push({ node, returnPresent, isVoidOrNever });
}
private addReturn(node: ts.ReturnStatement) {
let parent: ts.Node | undefined = node;
let nodes = this.fns.map(fn => fn.node);
while (parent && nodes.indexOf(parent) === -1)
parent = parent.parent;
if (parent && node.expression) {
this.fns[nodes.indexOf(parent)].returnPresent = true;
}
}
private isTypeClass(node: ts.Node) {
return node.kind === ts.SyntaxKind.ClassExpression || node.kind === ts.SyntaxKind.ClassDeclaration;
}
private isValidReturnType(tag: doctrine.IJSDocTag) {
return tag.type && (tag.type.name === 'void' || tag.type.type === 'UndefinedLiteral');
}
private getJSDocComment(node: ts.Node): IJSComment {
const ALLOWED_PARENTS = [
ts.SyntaxKind.BinaryExpression,
ts.SyntaxKind.VariableDeclaration,
ts.SyntaxKind.VariableDeclarationList,
ts.SyntaxKind.VariableStatement
];
if (!/^\/\*\*/.test(node.getFullText().trim())) {
if (node.parent && ALLOWED_PARENTS.indexOf(node.parent.kind) !== -1) {
return this.getJSDocComment(node.parent);
}
return {};
}
let comments = node.getFullText();
let offset = comments.indexOf('/**');
comments = comments.substring(offset);
comments = comments.substring(0, comments.indexOf('*/') + 2);
let start = node.pos + offset;
let width = comments.length;
if (!/^\/\*\*/.test(comments) || !/\*\/$/.test(comments)) {
return {};
}
return { comments, start, width };
}
private checkJSDoc(node: ts.Node) {
const { comments, start, width } = this.getJSDocComment(node);
if (!comments || start === undefined || width === undefined)
return;
let jsdoc: doctrine.IJSDocComment;
try {
jsdoc = doctrine.parse(comments, {
strict: true,
unwrap: true,
sloppy: true
});
}
catch (e) {
if (/braces/i.test(e.message)) {
this.addFailure(this.createFailure(start, width, Rule.FAILURE_STRING.missingBrace));
}
else {
this.addFailure(this.createFailure(start, width, Rule.FAILURE_STRING.syntaxError));
}
return;
}
let fn = this.fns.filter(f => node === f.node)[0];
let params = {};
let hasReturns = false;
let hasConstructor = false;
let isOverride = false;
let isAbstract = false;
for (let tag of jsdoc.tags) {
switch (tag.title) {
case 'param':
case 'arg':
case 'argument':
if (!tag.type && OPTIONS.requireParamType) {
this.addFailure(this.createFailure(start, width, Rule.FAILURE_STRING.missingParameterType(tag.name)));
}
if (!tag.description && OPTIONS.requireParamDescription) {
this.addFailure(this.createFailure(start, width, Rule.FAILURE_STRING.missingParameterDescription(tag.name)));
}
if (params[tag.name]) {
this.addFailure(this.createFailure(start, width, Rule.FAILURE_STRING.duplicateParameter(tag.name)));
}
else if (tag.name.indexOf('.') === -1) {
params[tag.name] = true;
}
break;
case 'return':
case 'returns':
hasReturns = true;
isAbstract = Lint.hasModifier(fn.node.modifiers, ts.SyntaxKind.AbstractKeyword);
if (!isAbstract && !OPTIONS.requireReturn && !fn.returnPresent && tag.type && tag.type.name !== 'void' && tag.type.name !== 'undefined') {
this.addFailure(this.createFailure(start, width, Rule.FAILURE_STRING.unexpectedTag(tag.title)));
}
else {
if (!tag.type && OPTIONS.requireReturnType) {
this.addFailure(this.createFailure(start, width, Rule.FAILURE_STRING.missingReturnType));
}
if (!this.isValidReturnType(tag) && !tag.description && OPTIONS.requireReturnDescription) {
this.addFailure(this.createFailure(start, width, Rule.FAILURE_STRING.missingReturnDescription));
}
}
break;
case 'constructor':
case 'class':
hasConstructor = true;
break;
case 'override':
case 'inheritdoc':
case 'inheritDoc':
isOverride = true;
break;
}
// check prefer (we need to ensure it has the property and not inherit from Object - e.g: constructor)
let title = OPTIONS.prefer[tag.title];
if (OPTIONS.prefer.hasOwnProperty(tag.title) && tag.title !== title) {
this.addFailure(this.createFailure(start, width, Rule.FAILURE_STRING.prefer(title)));
}
}
// check for functions missing @returns
if (!isOverride && !hasReturns && !hasConstructor && node.parent && node.parent.kind !== ts.SyntaxKind.GetKeyword && !this.isTypeClass(node)) {
if (OPTIONS.requireReturn || (fn.returnPresent && !fn.isVoidOrNever)) {
this.addFailure(this.createFailure(start, width, Rule.FAILURE_STRING.missingReturn(OPTIONS.prefer['returns'])));
}
}
// check the parameters
const jsdocParams = Object.keys(params);
const parameters = (node as ts.SignatureDeclaration).parameters;
if (parameters) {
parameters.forEach((param, i) => {
if (param.name.kind === ts.SyntaxKind.Identifier) {
let name = (param.name as ts.Identifier).text;
if (jsdocParams[i] && name !== jsdocParams[i]) {
this.addFailure(this.createFailure(start, width, Rule.FAILURE_STRING.wrongParam(name, jsdocParams[i])));
}
else if (!params[name] && !isOverride) {
this.addFailure(this.createFailure(start, width, Rule.FAILURE_STRING.missingParam(name)));
}
}
});
}
if (OPTIONS.matchDescription) {
try {
const regex = new RegExp(OPTIONS.matchDescription);
if (!regex.test(jsdoc.description)) {
this.addFailure(this.createFailure(start, width, Rule.FAILURE_STRING.wrongDescription));
}
}
catch (e) {
this.addFailure(this.createFailure(start, width, e.message));
}
}
}
} | the_stack |
import { expect } from "chai";
import {
EnumerationChoice, IconEditorParams, PropertyDescriptionHelper, PropertyEditorParamTypes, RangeEditorParams, SuppressLabelEditorParams,
} from "../../appui-abstract";
// cSpell:ignore Picklist
describe("PropertyDescriptionHelper", () => {
const testName = "name";
const testLabel = "label";
const additionParam = [{
type: PropertyEditorParamTypes.SuppressEditorLabel,
suppressLabelPlaceholder: true,
} as SuppressLabelEditorParams];
describe("WeightPicker Description", () => {
const typename = "number";
it("should build correctly", () => {
const editor = "weight-picker";
const editorDescription = PropertyDescriptionHelper.buildWeightPickerDescription(testName, testLabel);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(0);
});
it("should build with additional editor params correctly", () => {
const editor = "weight-picker";
const editorDescription = PropertyDescriptionHelper.buildWeightPickerDescription(testName, testLabel, additionParam);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(1);
expect(editorDescription.editor?.params?.[0].type).to.eq(PropertyEditorParamTypes.SuppressEditorLabel);
});
});
describe("TextEditor Description", () => {
const typename = "string";
it("should build correctly", () => {
const editor = undefined;
const editorDescription = PropertyDescriptionHelper.buildTextEditorDescription(testName, testLabel);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(0);
});
it("should build with additional editor params correctly", () => {
const editor = undefined;
const editorDescription = PropertyDescriptionHelper.buildTextEditorDescription(testName, testLabel, additionParam);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(1);
expect(editorDescription.editor?.params?.[0].type).to.eq(PropertyEditorParamTypes.SuppressEditorLabel);
});
});
describe("NumberEditor Description", () => {
const typename = "number";
it("should build correctly", () => {
const editor = "numeric-input";
const editorDescription = PropertyDescriptionHelper.buildNumberEditorDescription(testName, testLabel);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(1);
expect(editorDescription.editor?.params?.[0].type).to.eq(PropertyEditorParamTypes.Range);
});
it("should build with additional editor params correctly", () => {
const editor = "numeric-input";
const numberParam = {
type: PropertyEditorParamTypes.Range,
step: 2,
precision: 0,
minimum: 0,
maximum: 1000,
} as RangeEditorParams;
const editorDescription = PropertyDescriptionHelper.buildNumberEditorDescription(testName, testLabel, numberParam, additionParam);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(2);
expect(editorDescription.editor?.params?.[0].type).to.eq(PropertyEditorParamTypes.Range);
expect(editorDescription.editor?.params?.[1].type).to.eq(PropertyEditorParamTypes.SuppressEditorLabel);
});
});
describe("EnumPicklistEditor Description", () => {
const choices = [
{ label: "Red", value: 1 },
{ label: "White", value: 2 },
{ label: "Blue", value: 3 },
{ label: "Yellow", value: 4 },
];
const typename = "enum";
it("should build correctly", () => {
const editor = undefined;
const editorDescription = PropertyDescriptionHelper.buildEnumPicklistEditorDescription(testName, testLabel, choices);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params).to.eq(undefined);
expect(editorDescription.enum?.choices).to.eq(choices);
});
it("should build with additional editor params correctly", () => {
const editor = undefined;
const editorDescription = PropertyDescriptionHelper.buildEnumPicklistEditorDescription(testName, testLabel, choices, additionParam);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.enum?.choices).to.eq(choices);
expect(editorDescription.editor?.params?.length).to.eq(1);
expect(editorDescription.editor?.params?.[0].type).to.eq(PropertyEditorParamTypes.SuppressEditorLabel);
});
});
describe("ColorPickerEditor Description", () => {
const colors = [0x0000ff, 0xff0000, 0x00ff00];
const typename = "number";
it("should build correctly", () => {
const editor = "color-picker";
const editorDescription = PropertyDescriptionHelper.buildColorPickerDescription(testName, testLabel, colors, 1);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(1);
expect(editorDescription.editor?.params?.[0].type).to.eq(PropertyEditorParamTypes.ColorData);
});
it("should build with additional editor params correctly", () => {
const editor = "color-picker";
const editorDescription = PropertyDescriptionHelper.buildColorPickerDescription(testName, testLabel, colors, 1, additionParam);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(2);
expect(editorDescription.editor?.params?.[0].type).to.eq(PropertyEditorParamTypes.ColorData);
expect(editorDescription.editor?.params?.[1].type).to.eq(PropertyEditorParamTypes.SuppressEditorLabel);
});
});
describe("Toggle Description", () => {
const typename = "boolean";
it("should build correctly", () => {
const editor = "toggle";
const editorDescription = PropertyDescriptionHelper.buildToggleDescription(testName, testLabel);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(0);
});
it("should build with additional editor params correctly", () => {
const editor = "toggle";
const editorDescription = PropertyDescriptionHelper.buildToggleDescription(testName, testLabel, additionParam);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(1);
expect(editorDescription.editor?.params?.[0].type).to.eq(PropertyEditorParamTypes.SuppressEditorLabel);
});
});
describe("ImageCheckBox Description", () => {
const typename = "boolean";
const imageOff = "off";
const imageOn = "on";
it("should build correctly", () => {
const editor = "image-check-box";
const editorDescription = PropertyDescriptionHelper.buildImageCheckBoxDescription(testName, testLabel, imageOff, imageOn);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(1);
expect(editorDescription.editor?.params?.[0].type).to.eq(PropertyEditorParamTypes.CheckBoxImages);
});
it("should build with additional editor params correctly", () => {
const editor = "image-check-box";
const editorDescription = PropertyDescriptionHelper.buildImageCheckBoxDescription(testName, testLabel, imageOff, testLabel, additionParam);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(2);
expect(editorDescription.editor?.params?.[0].type).to.eq(PropertyEditorParamTypes.CheckBoxImages);
expect(editorDescription.editor?.params?.[1].type).to.eq(PropertyEditorParamTypes.SuppressEditorLabel);
});
});
describe("Checkbox Description", () => {
const typename = "boolean";
it("should build correctly", () => {
const editor = undefined;
const editorDescription = PropertyDescriptionHelper.buildCheckboxDescription(testName, testLabel);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(0);
});
it("should build with additional editor params correctly", () => {
const editor = undefined;
const editorDescription = PropertyDescriptionHelper.buildCheckboxDescription(testName, testLabel, additionParam);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq(testLabel);
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(1);
expect(editorDescription.editor?.params?.[0].type).to.eq(PropertyEditorParamTypes.SuppressEditorLabel);
});
it("should build a standard lock property description", () => {
const editor = undefined;
const editorDescription = PropertyDescriptionHelper.buildLockPropertyDescription(testName);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq("");
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(1);
expect(editorDescription.editor?.params?.[0].type).to.eq(PropertyEditorParamTypes.SuppressEditorLabel);
});
it("should build a standard lock property description with additional editor params correctly", () => {
// Note: additional params just for testing, currently there are no additional params used by the lock checkbox.
const lockAdditionParam = [{
type: PropertyEditorParamTypes.Icon,
definition: { iconSpec: "icon-test" },
} as IconEditorParams];
const editor = undefined;
const editorDescription = PropertyDescriptionHelper.buildLockPropertyDescription(testName, lockAdditionParam);
expect(editorDescription.name).to.eq(testName);
expect(editorDescription.typename).to.eq(typename);
expect(editorDescription.displayLabel).to.eq("");
expect(editorDescription.editor?.name).to.eq(editor);
expect(editorDescription.editor?.params?.length).to.eq(2);
expect(editorDescription.editor?.params?.[0].type).to.eq(PropertyEditorParamTypes.SuppressEditorLabel);
});
});
describe("bumpEnumProperty", () => {
const noChoices: EnumerationChoice[] = [
];
const choices = [
{ label: "Red", value: 1 },
{ label: "White", value: 2 },
{ label: "Blue", value: 3 },
{ label: "Yellow", value: 4 },
];
const stringChoices = async (): Promise<EnumerationChoice[]> => {
return [
{ label: "Red", value: "red" },
{ label: "White", value: "white" },
{ label: "Blue", value: "blue" },
{ label: "Yellow", value: "yellow" },
];
};
it("should bump numeric value correctly", async () => {
const enumDescription = PropertyDescriptionHelper.buildEnumPicklistEditorDescription(testName, testLabel, choices);
expect(enumDescription.enum?.choices).to.eq(choices);
let newValue = await PropertyDescriptionHelper.bumpEnumProperty(enumDescription, 1);
expect(newValue).to.eq(2);
newValue = await PropertyDescriptionHelper.bumpEnumProperty(enumDescription, 4);
expect(newValue).to.eq(1);
newValue = await PropertyDescriptionHelper.bumpEnumProperty(enumDescription, 0);
expect(newValue).to.eq(0);
});
it("should bump string value correctly", async () => {
const enumDescription = PropertyDescriptionHelper.buildEnumPicklistEditorDescription(testName, testLabel, stringChoices());
expect(enumDescription.enum?.choices).not.to.be.undefined;
let newValue = await PropertyDescriptionHelper.bumpEnumProperty(enumDescription, "red");
expect(newValue).to.eq("white");
newValue = await PropertyDescriptionHelper.bumpEnumProperty(enumDescription, "yellow");
expect(newValue).to.eq("red");
newValue = await PropertyDescriptionHelper.bumpEnumProperty(enumDescription, "");
expect(newValue).to.eq("");
});
it("should not bump with wrong type description", async () => {
const booleanDescription = PropertyDescriptionHelper.buildCheckboxDescription(testName, testLabel);
const newValue = await PropertyDescriptionHelper.bumpEnumProperty(booleanDescription, 1);
expect(newValue).to.eq(1);
});
it("should not bump with no choices", async () => {
const enumDescription = PropertyDescriptionHelper.buildEnumPicklistEditorDescription(testName, testLabel, noChoices);
expect(enumDescription.enum?.choices).to.eq(noChoices);
const newValue = await PropertyDescriptionHelper.bumpEnumProperty(enumDescription, 1);
expect(newValue).to.eq(1);
});
});
}); | the_stack |
import { assert, isArray, eqNaN, isFunction } from 'zrender/src/core/util';
import Scale from '../scale/Scale';
import { AxisBaseModel } from './AxisBaseModel';
import { parsePercent } from 'zrender/src/contain/text';
import { AxisBaseOption, CategoryAxisBaseOption } from './axisCommonTypes';
import { ScaleDataValue } from '../util/types';
export interface ScaleRawExtentResult {
// `min`/`max` defines data available range, determined by
// `dataMin`/`dataMax` and explicit specified min max related option.
// The final extent will be based on the `min`/`max` and may be enlarge
// a little (say, "nice strategy", e.g., niceScale, boundaryGap).
// Ensure `min`/`max` be finite number or NaN here.
// (not to be null/undefined) `NaN` means min/max axis is blank.
readonly min: number;
readonly max: number;
// `minFixed`/`maxFixed` marks that `min`/`max` should be used
// in the final extent without other "nice strategy".
readonly minFixed: boolean;
readonly maxFixed: boolean;
// Mark that the axis should be blank.
readonly isBlank: boolean;
}
export class ScaleRawExtentInfo {
private _needCrossZero: boolean;
private _isOrdinal: boolean;
private _axisDataLen: number;
private _boundaryGapInner: number[];
// Accurate raw value get from model.
private _modelMinRaw: AxisBaseOption['min'];
private _modelMaxRaw: AxisBaseOption['max'];
// Can be `finite number`/`null`/`undefined`/`NaN`
private _modelMinNum: number;
private _modelMaxNum: number;
// Range union by series data on this axis.
// May be modified if data is filtered.
private _dataMin: number;
private _dataMax: number;
// Highest priority if specified.
private _determinedMin: number;
private _determinedMax: number;
// Make that the `rawExtentInfo` can not be modified any more.
readonly frozen: boolean;
constructor(
scale: Scale,
model: AxisBaseModel,
// Usually: data extent from all series on this axis.
originalExtent: number[]
) {
this._prepareParams(scale, model, originalExtent);
}
/**
* Parameters depending on ouside (like model, user callback)
* are prepared and fixed here.
*/
private _prepareParams(
scale: Scale,
model: AxisBaseModel,
// Usually: data extent from all series on this axis.
dataExtent: number[]
) {
if (dataExtent[1] < dataExtent[0]) {
dataExtent = [NaN, NaN];
}
this._dataMin = dataExtent[0];
this._dataMax = dataExtent[1];
const isOrdinal = this._isOrdinal = scale.type === 'ordinal';
this._needCrossZero = model.getNeedCrossZero && model.getNeedCrossZero();
const modelMinRaw = this._modelMinRaw = model.get('min', true);
if (isFunction(modelMinRaw)) {
// This callback alway provide users the full data extent (before data filtered).
this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
min: dataExtent[0],
max: dataExtent[1]
}));
}
else if (modelMinRaw !== 'dataMin') {
this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
}
const modelMaxRaw = this._modelMaxRaw = model.get('max', true);
if (isFunction(modelMaxRaw)) {
// This callback alway provide users the full data extent (before data filtered).
this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
min: dataExtent[0],
max: dataExtent[1]
}));
}
else if (modelMaxRaw !== 'dataMax') {
this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
}
if (isOrdinal) {
// FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
// and progressive rendering is using, here the category result might just only contain
// the processed chunk rather than the entire result.
this._axisDataLen = model.getCategories().length;
}
else {
const boundaryGap = (model as AxisBaseModel<CategoryAxisBaseOption>).get('boundaryGap');
const boundaryGapArr = isArray(boundaryGap)
? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
if (__DEV__) {
console.warn('Boolean type for boundaryGap is only '
+ 'allowed for ordinal axis. Please use string in '
+ 'percentage instead, e.g., "20%". Currently, '
+ 'boundaryGap is set to be 0.');
}
this._boundaryGapInner = [0, 0];
}
else {
this._boundaryGapInner = [
parsePercent(boundaryGapArr[0], 1),
parsePercent(boundaryGapArr[1], 1)
];
}
}
}
/**
* Calculate extent by prepared parameters.
* This method has no external dependency and can be called duplicatedly,
* getting the same result.
* If parameters changed, should call this method to recalcuate.
*/
calculate(): ScaleRawExtentResult {
// Notice: When min/max is not set (that is, when there are null/undefined,
// which is the most common case), these cases should be ensured:
// (1) For 'ordinal', show all axis.data.
// (2) For others:
// + `boundaryGap` is applied (if min/max set, boundaryGap is
// disabled).
// + If `needCrossZero`, min/max should be zero, otherwise, min/max should
// be the result that originalExtent enlarged by boundaryGap.
// (3) If no data, it should be ensured that `scale.setBlank` is set.
const isOrdinal = this._isOrdinal;
const dataMin = this._dataMin;
const dataMax = this._dataMax;
const axisDataLen = this._axisDataLen;
const boundaryGapInner = this._boundaryGapInner;
const span = !isOrdinal
? ((dataMax - dataMin) || Math.abs(dataMin))
: null;
// Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
// `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
let min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
let max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum;
// If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
let minFixed = min != null;
let maxFixed = max != null;
if (min == null) {
min = isOrdinal
? (axisDataLen ? 0 : NaN)
: dataMin - boundaryGapInner[0] * span;
}
if (max == null) {
max = isOrdinal
? (axisDataLen ? axisDataLen - 1 : NaN)
: dataMax + boundaryGapInner[1] * span;
}
(min == null || !isFinite(min)) && (min = NaN);
(max == null || !isFinite(max)) && (max = NaN);
if (min > max) {
min = NaN;
max = NaN;
}
const isBlank = eqNaN(min)
|| eqNaN(max)
|| (isOrdinal && !axisDataLen);
// If data extent modified, need to recalculated to ensure cross zero.
if (this._needCrossZero) {
// Axis is over zero and min is not set
if (min > 0 && max > 0 && !minFixed) {
min = 0;
// minFixed = true;
}
// Axis is under zero and max is not set
if (min < 0 && max < 0 && !maxFixed) {
max = 0;
// maxFixed = true;
}
// PENDING:
// When `needCrossZero` and all data is positive/negative, should it be ensured
// that the results processed by boundaryGap are positive/negative?
// If so, here `minFixed`/`maxFixed` need to be set.
}
const determinedMin = this._determinedMin;
const determinedMax = this._determinedMax;
if (determinedMin != null) {
min = determinedMin;
minFixed = true;
}
if (determinedMax != null) {
max = determinedMax;
maxFixed = true;
}
// Ensure min/max be finite number or NaN here. (not to be null/undefined)
// `NaN` means min/max axis is blank.
return {
min: min,
max: max,
minFixed: minFixed,
maxFixed: maxFixed,
isBlank: isBlank
};
}
modifyDataMinMax(minMaxName: 'min' | 'max', val: number): void {
if (__DEV__) {
assert(!this.frozen);
}
this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
}
setDeterminedMinMax(minMaxName: 'min' | 'max', val: number): void {
const attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
if (__DEV__) {
assert(
!this.frozen
// Earse them usually means logic flaw.
&& (this[attr] == null)
);
}
this[attr] = val;
}
freeze() {
// @ts-ignore
this.frozen = true;
}
}
const DETERMINED_MIN_MAX_ATTR = { min: '_determinedMin', max: '_determinedMax' } as const;
const DATA_MIN_MAX_ATTR = { min: '_dataMin', max: '_dataMax' } as const;
/**
* Get scale min max and related info only depends on model settings.
* This method can be called after coordinate system created.
* For example, in data processing stage.
*
* Scale extent info probably be required multiple times during a workflow.
* For example:
* (1) `dataZoom` depends it to get the axis extent in "100%" state.
* (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
* (3) `coordSys.update` use it to finally decide the scale extent.
* But the callback of `min`/`max` should not be called multiple times.
* The code below should not be implemented repeatedly either.
* So we cache the result in the scale instance, which will be recreated at the begining
* of the workflow (because `scale` instance will be recreated each round of the workflow).
*/
export function ensureScaleRawExtentInfo(
scale: Scale,
model: AxisBaseModel,
// Usually: data extent from all series on this axis.
originalExtent: number[]
): ScaleRawExtentInfo {
// Do not permit to recreate.
let rawExtentInfo = scale.rawExtentInfo;
if (rawExtentInfo) {
return rawExtentInfo;
}
rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent);
// @ts-ignore
scale.rawExtentInfo = rawExtentInfo;
return rawExtentInfo;
}
export function parseAxisModelMinMax(scale: Scale, minMax: ScaleDataValue): number {
return minMax == null ? null
: eqNaN(minMax) ? NaN
: scale.parse(minMax);
} | the_stack |
import {ResourceBase, ResourceTag} from '../resource'
import {Value, List} from '../dataTypes'
export class CustomArtifactConfiguration {
MavenReference?: MavenReference
S3ContentLocation?: S3ContentLocation
ArtifactType!: Value<string>
constructor(properties: CustomArtifactConfiguration) {
Object.assign(this, properties)
}
}
export class S3ContentLocation {
BucketARN?: Value<string>
FileKey?: Value<string>
ObjectVersion?: Value<string>
constructor(properties: S3ContentLocation) {
Object.assign(this, properties)
}
}
export class DeployAsApplicationConfiguration {
S3ContentLocation!: S3ContentBaseLocation
constructor(properties: DeployAsApplicationConfiguration) {
Object.assign(this, properties)
}
}
export class PropertyGroup {
PropertyMap?: {[key: string]: any}
PropertyGroupId?: Value<string>
constructor(properties: PropertyGroup) {
Object.assign(this, properties)
}
}
export class MappingParameters {
JSONMappingParameters?: JSONMappingParameters
CSVMappingParameters?: CSVMappingParameters
constructor(properties: MappingParameters) {
Object.assign(this, properties)
}
}
export class InputParallelism {
Count?: Value<number>
constructor(properties: InputParallelism) {
Object.assign(this, properties)
}
}
export class FlinkApplicationConfiguration {
CheckpointConfiguration?: CheckpointConfiguration
ParallelismConfiguration?: ParallelismConfiguration
MonitoringConfiguration?: MonitoringConfiguration
constructor(properties: FlinkApplicationConfiguration) {
Object.assign(this, properties)
}
}
export class Input {
NamePrefix!: Value<string>
InputSchema!: InputSchema
KinesisStreamsInput?: KinesisStreamsInput
KinesisFirehoseInput?: KinesisFirehoseInput
InputProcessingConfiguration?: InputProcessingConfiguration
InputParallelism?: InputParallelism
constructor(properties: Input) {
Object.assign(this, properties)
}
}
export class ApplicationSnapshotConfiguration {
SnapshotsEnabled!: Value<boolean>
constructor(properties: ApplicationSnapshotConfiguration) {
Object.assign(this, properties)
}
}
export class KinesisFirehoseInput {
ResourceARN!: Value<string>
constructor(properties: KinesisFirehoseInput) {
Object.assign(this, properties)
}
}
export class InputSchema {
RecordEncoding?: Value<string>
RecordColumns!: List<RecordColumn>
RecordFormat!: RecordFormat
constructor(properties: InputSchema) {
Object.assign(this, properties)
}
}
export class ParallelismConfiguration {
ConfigurationType!: Value<string>
ParallelismPerKPU?: Value<number>
AutoScalingEnabled?: Value<boolean>
Parallelism?: Value<number>
constructor(properties: ParallelismConfiguration) {
Object.assign(this, properties)
}
}
export class MonitoringConfiguration {
ConfigurationType!: Value<string>
MetricsLevel?: Value<string>
LogLevel?: Value<string>
constructor(properties: MonitoringConfiguration) {
Object.assign(this, properties)
}
}
export type CustomArtifactsConfiguration = List<CustomArtifactConfiguration>
export class SqlApplicationConfiguration {
Inputs?: List<Input>
constructor(properties: SqlApplicationConfiguration) {
Object.assign(this, properties)
}
}
export class InputProcessingConfiguration {
InputLambdaProcessor?: InputLambdaProcessor
constructor(properties: InputProcessingConfiguration) {
Object.assign(this, properties)
}
}
export class ApplicationCodeConfiguration {
CodeContentType!: Value<string>
CodeContent!: CodeContent
constructor(properties: ApplicationCodeConfiguration) {
Object.assign(this, properties)
}
}
export class ZeppelinApplicationConfiguration {
CatalogConfiguration?: CatalogConfiguration
MonitoringConfiguration?: ZeppelinMonitoringConfiguration
DeployAsApplicationConfiguration?: DeployAsApplicationConfiguration
CustomArtifactsConfiguration?: CustomArtifactsConfiguration
constructor(properties: ZeppelinApplicationConfiguration) {
Object.assign(this, properties)
}
}
export class MavenReference {
ArtifactId!: Value<string>
Version!: Value<string>
GroupId!: Value<string>
constructor(properties: MavenReference) {
Object.assign(this, properties)
}
}
export class KinesisStreamsInput {
ResourceARN!: Value<string>
constructor(properties: KinesisStreamsInput) {
Object.assign(this, properties)
}
}
export class CheckpointConfiguration {
ConfigurationType!: Value<string>
CheckpointInterval?: Value<number>
MinPauseBetweenCheckpoints?: Value<number>
CheckpointingEnabled?: Value<boolean>
constructor(properties: CheckpointConfiguration) {
Object.assign(this, properties)
}
}
export class ZeppelinMonitoringConfiguration {
LogLevel?: Value<string>
constructor(properties: ZeppelinMonitoringConfiguration) {
Object.assign(this, properties)
}
}
export class S3ContentBaseLocation {
BucketARN!: Value<string>
BasePath!: Value<string>
constructor(properties: S3ContentBaseLocation) {
Object.assign(this, properties)
}
}
export class InputLambdaProcessor {
ResourceARN!: Value<string>
constructor(properties: InputLambdaProcessor) {
Object.assign(this, properties)
}
}
export class RecordColumn {
Mapping?: Value<string>
SqlType!: Value<string>
Name!: Value<string>
constructor(properties: RecordColumn) {
Object.assign(this, properties)
}
}
export class CSVMappingParameters {
RecordRowDelimiter!: Value<string>
RecordColumnDelimiter!: Value<string>
constructor(properties: CSVMappingParameters) {
Object.assign(this, properties)
}
}
export class RecordFormat {
MappingParameters?: MappingParameters
RecordFormatType!: Value<string>
constructor(properties: RecordFormat) {
Object.assign(this, properties)
}
}
export class GlueDataCatalogConfiguration {
DatabaseARN?: Value<string>
constructor(properties: GlueDataCatalogConfiguration) {
Object.assign(this, properties)
}
}
export class JSONMappingParameters {
RecordRowPath!: Value<string>
constructor(properties: JSONMappingParameters) {
Object.assign(this, properties)
}
}
export class CodeContent {
ZipFileContent?: Value<string>
S3ContentLocation?: S3ContentLocation
TextContent?: Value<string>
constructor(properties: CodeContent) {
Object.assign(this, properties)
}
}
export class ApplicationConfiguration {
ApplicationCodeConfiguration?: ApplicationCodeConfiguration
EnvironmentProperties?: EnvironmentProperties
FlinkApplicationConfiguration?: FlinkApplicationConfiguration
SqlApplicationConfiguration?: SqlApplicationConfiguration
ZeppelinApplicationConfiguration?: ZeppelinApplicationConfiguration
ApplicationSnapshotConfiguration?: ApplicationSnapshotConfiguration
constructor(properties: ApplicationConfiguration) {
Object.assign(this, properties)
}
}
export class EnvironmentProperties {
PropertyGroups?: List<PropertyGroup>
constructor(properties: EnvironmentProperties) {
Object.assign(this, properties)
}
}
export class CatalogConfiguration {
GlueDataCatalogConfiguration?: GlueDataCatalogConfiguration
constructor(properties: CatalogConfiguration) {
Object.assign(this, properties)
}
}
export interface ApplicationProperties {
ApplicationName?: Value<string>
RuntimeEnvironment: Value<string>
ApplicationMode?: Value<string>
ApplicationConfiguration?: ApplicationConfiguration
ApplicationDescription?: Value<string>
Tags?: List<ResourceTag>
ServiceExecutionRole: Value<string>
}
export default class Application extends ResourceBase<ApplicationProperties> {
static CustomArtifactConfiguration = CustomArtifactConfiguration
static S3ContentLocation = S3ContentLocation
static DeployAsApplicationConfiguration = DeployAsApplicationConfiguration
static PropertyGroup = PropertyGroup
static MappingParameters = MappingParameters
static InputParallelism = InputParallelism
static FlinkApplicationConfiguration = FlinkApplicationConfiguration
static Input = Input
static ApplicationSnapshotConfiguration = ApplicationSnapshotConfiguration
static KinesisFirehoseInput = KinesisFirehoseInput
static InputSchema = InputSchema
static ParallelismConfiguration = ParallelismConfiguration
static MonitoringConfiguration = MonitoringConfiguration
static SqlApplicationConfiguration = SqlApplicationConfiguration
static InputProcessingConfiguration = InputProcessingConfiguration
static ApplicationCodeConfiguration = ApplicationCodeConfiguration
static ZeppelinApplicationConfiguration = ZeppelinApplicationConfiguration
static MavenReference = MavenReference
static KinesisStreamsInput = KinesisStreamsInput
static CheckpointConfiguration = CheckpointConfiguration
static ZeppelinMonitoringConfiguration = ZeppelinMonitoringConfiguration
static S3ContentBaseLocation = S3ContentBaseLocation
static InputLambdaProcessor = InputLambdaProcessor
static RecordColumn = RecordColumn
static CSVMappingParameters = CSVMappingParameters
static RecordFormat = RecordFormat
static GlueDataCatalogConfiguration = GlueDataCatalogConfiguration
static JSONMappingParameters = JSONMappingParameters
static CodeContent = CodeContent
static ApplicationConfiguration = ApplicationConfiguration
static EnvironmentProperties = EnvironmentProperties
static CatalogConfiguration = CatalogConfiguration
constructor(properties: ApplicationProperties) {
super('AWS::KinesisAnalyticsV2::Application', properties)
}
} | the_stack |
import * as protos from '../protos/protos';
import * as assert from 'assert';
import * as sinon from 'sinon';
import {SinonStub} from 'sinon';
import {describe, it} from 'mocha';
import * as devicemanagerModule from '../src';
import {PassThrough} from 'stream';
import {protobuf} from 'google-gax';
function generateSampleMessage<T extends object>(instance: T) {
const filledObject = (
instance.constructor as typeof protobuf.Message
).toObject(instance as protobuf.Message<T>, {defaults: true});
return (instance.constructor as typeof protobuf.Message).fromObject(
filledObject
) as T;
}
function stubSimpleCall<ResponseType>(response?: ResponseType, error?: Error) {
return error
? sinon.stub().rejects(error)
: sinon.stub().resolves([response]);
}
function stubSimpleCallWithCallback<ResponseType>(
response?: ResponseType,
error?: Error
) {
return error
? sinon.stub().callsArgWith(2, error)
: sinon.stub().callsArgWith(2, null, response);
}
function stubPageStreamingCall<ResponseType>(
responses?: ResponseType[],
error?: Error
) {
const pagingStub = sinon.stub();
if (responses) {
for (let i = 0; i < responses.length; ++i) {
pagingStub.onCall(i).callsArgWith(2, null, responses[i]);
}
}
const transformStub = error
? sinon.stub().callsArgWith(2, error)
: pagingStub;
const mockStream = new PassThrough({
objectMode: true,
transform: transformStub,
});
// trigger as many responses as needed
if (responses) {
for (let i = 0; i < responses.length; ++i) {
setImmediate(() => {
mockStream.write({});
});
}
setImmediate(() => {
mockStream.end();
});
} else {
setImmediate(() => {
mockStream.write({});
});
setImmediate(() => {
mockStream.end();
});
}
return sinon.stub().returns(mockStream);
}
function stubAsyncIterationCall<ResponseType>(
responses?: ResponseType[],
error?: Error
) {
let counter = 0;
const asyncIterable = {
[Symbol.asyncIterator]() {
return {
async next() {
if (error) {
return Promise.reject(error);
}
if (counter >= responses!.length) {
return Promise.resolve({done: true, value: undefined});
}
return Promise.resolve({done: false, value: responses![counter++]});
},
};
},
};
return sinon.stub().returns(asyncIterable);
}
describe('v1.DeviceManagerClient', () => {
it('has servicePath', () => {
const servicePath = devicemanagerModule.v1.DeviceManagerClient.servicePath;
assert(servicePath);
});
it('has apiEndpoint', () => {
const apiEndpoint = devicemanagerModule.v1.DeviceManagerClient.apiEndpoint;
assert(apiEndpoint);
});
it('has port', () => {
const port = devicemanagerModule.v1.DeviceManagerClient.port;
assert(port);
assert(typeof port === 'number');
});
it('should create a client with no option', () => {
const client = new devicemanagerModule.v1.DeviceManagerClient();
assert(client);
});
it('should create a client with gRPC fallback', () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
fallback: true,
});
assert(client);
});
it('has initialize method and supports deferred initialization', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
assert.strictEqual(client.deviceManagerStub, undefined);
await client.initialize();
assert(client.deviceManagerStub);
});
it('has close method', () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.close();
});
it('has getProjectId method', async () => {
const fakeProjectId = 'fake-project-id';
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.auth.getProjectId = sinon.stub().resolves(fakeProjectId);
const result = await client.getProjectId();
assert.strictEqual(result, fakeProjectId);
assert((client.auth.getProjectId as SinonStub).calledWithExactly());
});
it('has getProjectId method with callback', async () => {
const fakeProjectId = 'fake-project-id';
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.auth.getProjectId = sinon
.stub()
.callsArgWith(0, null, fakeProjectId);
const promise = new Promise((resolve, reject) => {
client.getProjectId((err?: Error | null, projectId?: string | null) => {
if (err) {
reject(err);
} else {
resolve(projectId);
}
});
});
const result = await promise;
assert.strictEqual(result, fakeProjectId);
});
describe('createDeviceRegistry', () => {
it('invokes createDeviceRegistry without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.CreateDeviceRegistryRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.DeviceRegistry()
);
client.innerApiCalls.createDeviceRegistry =
stubSimpleCall(expectedResponse);
const [response] = await client.createDeviceRegistry(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.createDeviceRegistry as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes createDeviceRegistry without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.CreateDeviceRegistryRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.DeviceRegistry()
);
client.innerApiCalls.createDeviceRegistry =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.createDeviceRegistry(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.IDeviceRegistry | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.createDeviceRegistry as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes createDeviceRegistry with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.CreateDeviceRegistryRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.createDeviceRegistry = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.createDeviceRegistry(request), expectedError);
assert(
(client.innerApiCalls.createDeviceRegistry as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('getDeviceRegistry', () => {
it('invokes getDeviceRegistry without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.GetDeviceRegistryRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.DeviceRegistry()
);
client.innerApiCalls.getDeviceRegistry = stubSimpleCall(expectedResponse);
const [response] = await client.getDeviceRegistry(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getDeviceRegistry as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getDeviceRegistry without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.GetDeviceRegistryRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.DeviceRegistry()
);
client.innerApiCalls.getDeviceRegistry =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getDeviceRegistry(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.IDeviceRegistry | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getDeviceRegistry as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getDeviceRegistry with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.GetDeviceRegistryRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getDeviceRegistry = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.getDeviceRegistry(request), expectedError);
assert(
(client.innerApiCalls.getDeviceRegistry as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('updateDeviceRegistry', () => {
it('invokes updateDeviceRegistry without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.UpdateDeviceRegistryRequest()
);
request.deviceRegistry = {};
request.deviceRegistry.name = '';
const expectedHeaderRequestParams = 'device_registry.name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.DeviceRegistry()
);
client.innerApiCalls.updateDeviceRegistry =
stubSimpleCall(expectedResponse);
const [response] = await client.updateDeviceRegistry(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.updateDeviceRegistry as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes updateDeviceRegistry without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.UpdateDeviceRegistryRequest()
);
request.deviceRegistry = {};
request.deviceRegistry.name = '';
const expectedHeaderRequestParams = 'device_registry.name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.DeviceRegistry()
);
client.innerApiCalls.updateDeviceRegistry =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.updateDeviceRegistry(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.IDeviceRegistry | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.updateDeviceRegistry as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes updateDeviceRegistry with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.UpdateDeviceRegistryRequest()
);
request.deviceRegistry = {};
request.deviceRegistry.name = '';
const expectedHeaderRequestParams = 'device_registry.name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.updateDeviceRegistry = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.updateDeviceRegistry(request), expectedError);
assert(
(client.innerApiCalls.updateDeviceRegistry as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('deleteDeviceRegistry', () => {
it('invokes deleteDeviceRegistry without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.DeleteDeviceRegistryRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.deleteDeviceRegistry =
stubSimpleCall(expectedResponse);
const [response] = await client.deleteDeviceRegistry(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.deleteDeviceRegistry as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes deleteDeviceRegistry without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.DeleteDeviceRegistryRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.deleteDeviceRegistry =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.deleteDeviceRegistry(
request,
(
err?: Error | null,
result?: protos.google.protobuf.IEmpty | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.deleteDeviceRegistry as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes deleteDeviceRegistry with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.DeleteDeviceRegistryRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.deleteDeviceRegistry = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.deleteDeviceRegistry(request), expectedError);
assert(
(client.innerApiCalls.deleteDeviceRegistry as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('createDevice', () => {
it('invokes createDevice without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.CreateDeviceRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.Device()
);
client.innerApiCalls.createDevice = stubSimpleCall(expectedResponse);
const [response] = await client.createDevice(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.createDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes createDevice without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.CreateDeviceRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.Device()
);
client.innerApiCalls.createDevice =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.createDevice(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.IDevice | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.createDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes createDevice with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.CreateDeviceRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.createDevice = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.createDevice(request), expectedError);
assert(
(client.innerApiCalls.createDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('getDevice', () => {
it('invokes getDevice without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.GetDeviceRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.Device()
);
client.innerApiCalls.getDevice = stubSimpleCall(expectedResponse);
const [response] = await client.getDevice(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getDevice without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.GetDeviceRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.Device()
);
client.innerApiCalls.getDevice =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getDevice(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.IDevice | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getDevice with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.GetDeviceRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getDevice = stubSimpleCall(undefined, expectedError);
await assert.rejects(client.getDevice(request), expectedError);
assert(
(client.innerApiCalls.getDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('updateDevice', () => {
it('invokes updateDevice without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.UpdateDeviceRequest()
);
request.device = {};
request.device.name = '';
const expectedHeaderRequestParams = 'device.name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.Device()
);
client.innerApiCalls.updateDevice = stubSimpleCall(expectedResponse);
const [response] = await client.updateDevice(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.updateDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes updateDevice without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.UpdateDeviceRequest()
);
request.device = {};
request.device.name = '';
const expectedHeaderRequestParams = 'device.name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.Device()
);
client.innerApiCalls.updateDevice =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.updateDevice(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.IDevice | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.updateDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes updateDevice with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.UpdateDeviceRequest()
);
request.device = {};
request.device.name = '';
const expectedHeaderRequestParams = 'device.name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.updateDevice = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.updateDevice(request), expectedError);
assert(
(client.innerApiCalls.updateDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('deleteDevice', () => {
it('invokes deleteDevice without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.DeleteDeviceRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.deleteDevice = stubSimpleCall(expectedResponse);
const [response] = await client.deleteDevice(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.deleteDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes deleteDevice without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.DeleteDeviceRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.protobuf.Empty()
);
client.innerApiCalls.deleteDevice =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.deleteDevice(
request,
(
err?: Error | null,
result?: protos.google.protobuf.IEmpty | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.deleteDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes deleteDevice with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.DeleteDeviceRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.deleteDevice = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.deleteDevice(request), expectedError);
assert(
(client.innerApiCalls.deleteDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('modifyCloudToDeviceConfig', () => {
it('invokes modifyCloudToDeviceConfig without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ModifyCloudToDeviceConfigRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.DeviceConfig()
);
client.innerApiCalls.modifyCloudToDeviceConfig =
stubSimpleCall(expectedResponse);
const [response] = await client.modifyCloudToDeviceConfig(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.modifyCloudToDeviceConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes modifyCloudToDeviceConfig without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ModifyCloudToDeviceConfigRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.DeviceConfig()
);
client.innerApiCalls.modifyCloudToDeviceConfig =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.modifyCloudToDeviceConfig(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.IDeviceConfig | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.modifyCloudToDeviceConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes modifyCloudToDeviceConfig with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ModifyCloudToDeviceConfigRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.modifyCloudToDeviceConfig = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.modifyCloudToDeviceConfig(request),
expectedError
);
assert(
(client.innerApiCalls.modifyCloudToDeviceConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('listDeviceConfigVersions', () => {
it('invokes listDeviceConfigVersions without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceConfigVersionsRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceConfigVersionsResponse()
);
client.innerApiCalls.listDeviceConfigVersions =
stubSimpleCall(expectedResponse);
const [response] = await client.listDeviceConfigVersions(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listDeviceConfigVersions as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listDeviceConfigVersions without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceConfigVersionsRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceConfigVersionsResponse()
);
client.innerApiCalls.listDeviceConfigVersions =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.listDeviceConfigVersions(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.IListDeviceConfigVersionsResponse | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listDeviceConfigVersions as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes listDeviceConfigVersions with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceConfigVersionsRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.listDeviceConfigVersions = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.listDeviceConfigVersions(request),
expectedError
);
assert(
(client.innerApiCalls.listDeviceConfigVersions as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('listDeviceStates', () => {
it('invokes listDeviceStates without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceStatesRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceStatesResponse()
);
client.innerApiCalls.listDeviceStates = stubSimpleCall(expectedResponse);
const [response] = await client.listDeviceStates(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listDeviceStates as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listDeviceStates without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceStatesRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceStatesResponse()
);
client.innerApiCalls.listDeviceStates =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.listDeviceStates(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.IListDeviceStatesResponse | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listDeviceStates as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes listDeviceStates with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceStatesRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.listDeviceStates = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.listDeviceStates(request), expectedError);
assert(
(client.innerApiCalls.listDeviceStates as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setIamPolicy', () => {
it('invokes setIamPolicy without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.SetIamPolicyRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.iam.v1.Policy()
);
client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse);
const [response] = await client.setIamPolicy(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setIamPolicy without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.SetIamPolicyRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.iam.v1.Policy()
);
client.innerApiCalls.setIamPolicy =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setIamPolicy(
request,
(
err?: Error | null,
result?: protos.google.iam.v1.IPolicy | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setIamPolicy with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.SetIamPolicyRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setIamPolicy = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.setIamPolicy(request), expectedError);
assert(
(client.innerApiCalls.setIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('getIamPolicy', () => {
it('invokes getIamPolicy without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.GetIamPolicyRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.iam.v1.Policy()
);
client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse);
const [response] = await client.getIamPolicy(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getIamPolicy without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.GetIamPolicyRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.iam.v1.Policy()
);
client.innerApiCalls.getIamPolicy =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getIamPolicy(
request,
(
err?: Error | null,
result?: protos.google.iam.v1.IPolicy | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getIamPolicy with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.GetIamPolicyRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getIamPolicy = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.getIamPolicy(request), expectedError);
assert(
(client.innerApiCalls.getIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('testIamPermissions', () => {
it('invokes testIamPermissions without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.TestIamPermissionsRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.iam.v1.TestIamPermissionsResponse()
);
client.innerApiCalls.testIamPermissions =
stubSimpleCall(expectedResponse);
const [response] = await client.testIamPermissions(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.testIamPermissions as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes testIamPermissions without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.TestIamPermissionsRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.iam.v1.TestIamPermissionsResponse()
);
client.innerApiCalls.testIamPermissions =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.testIamPermissions(
request,
(
err?: Error | null,
result?: protos.google.iam.v1.ITestIamPermissionsResponse | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.testIamPermissions as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes testIamPermissions with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.iam.v1.TestIamPermissionsRequest()
);
request.resource = '';
const expectedHeaderRequestParams = 'resource=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.testIamPermissions = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.testIamPermissions(request), expectedError);
assert(
(client.innerApiCalls.testIamPermissions as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('sendCommandToDevice', () => {
it('invokes sendCommandToDevice without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.SendCommandToDeviceRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.SendCommandToDeviceResponse()
);
client.innerApiCalls.sendCommandToDevice =
stubSimpleCall(expectedResponse);
const [response] = await client.sendCommandToDevice(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.sendCommandToDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes sendCommandToDevice without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.SendCommandToDeviceRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.SendCommandToDeviceResponse()
);
client.innerApiCalls.sendCommandToDevice =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.sendCommandToDevice(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.ISendCommandToDeviceResponse | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.sendCommandToDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes sendCommandToDevice with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.SendCommandToDeviceRequest()
);
request.name = '';
const expectedHeaderRequestParams = 'name=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.sendCommandToDevice = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.sendCommandToDevice(request), expectedError);
assert(
(client.innerApiCalls.sendCommandToDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('bindDeviceToGateway', () => {
it('invokes bindDeviceToGateway without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.BindDeviceToGatewayRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.BindDeviceToGatewayResponse()
);
client.innerApiCalls.bindDeviceToGateway =
stubSimpleCall(expectedResponse);
const [response] = await client.bindDeviceToGateway(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.bindDeviceToGateway as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes bindDeviceToGateway without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.BindDeviceToGatewayRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.BindDeviceToGatewayResponse()
);
client.innerApiCalls.bindDeviceToGateway =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.bindDeviceToGateway(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.IBindDeviceToGatewayResponse | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.bindDeviceToGateway as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes bindDeviceToGateway with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.BindDeviceToGatewayRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.bindDeviceToGateway = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.bindDeviceToGateway(request), expectedError);
assert(
(client.innerApiCalls.bindDeviceToGateway as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('unbindDeviceFromGateway', () => {
it('invokes unbindDeviceFromGateway without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.UnbindDeviceFromGatewayRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.UnbindDeviceFromGatewayResponse()
);
client.innerApiCalls.unbindDeviceFromGateway =
stubSimpleCall(expectedResponse);
const [response] = await client.unbindDeviceFromGateway(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.unbindDeviceFromGateway as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes unbindDeviceFromGateway without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.UnbindDeviceFromGatewayRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.iot.v1.UnbindDeviceFromGatewayResponse()
);
client.innerApiCalls.unbindDeviceFromGateway =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.unbindDeviceFromGateway(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.IUnbindDeviceFromGatewayResponse | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.unbindDeviceFromGateway as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes unbindDeviceFromGateway with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.UnbindDeviceFromGatewayRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.unbindDeviceFromGateway = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.unbindDeviceFromGateway(request),
expectedError
);
assert(
(client.innerApiCalls.unbindDeviceFromGateway as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('listDeviceRegistries', () => {
it('invokes listDeviceRegistries without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceRegistriesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.iot.v1.DeviceRegistry()),
generateSampleMessage(new protos.google.cloud.iot.v1.DeviceRegistry()),
generateSampleMessage(new protos.google.cloud.iot.v1.DeviceRegistry()),
];
client.innerApiCalls.listDeviceRegistries =
stubSimpleCall(expectedResponse);
const [response] = await client.listDeviceRegistries(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listDeviceRegistries as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listDeviceRegistries without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceRegistriesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.iot.v1.DeviceRegistry()),
generateSampleMessage(new protos.google.cloud.iot.v1.DeviceRegistry()),
generateSampleMessage(new protos.google.cloud.iot.v1.DeviceRegistry()),
];
client.innerApiCalls.listDeviceRegistries =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.listDeviceRegistries(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.IDeviceRegistry[] | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listDeviceRegistries as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes listDeviceRegistries with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceRegistriesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.listDeviceRegistries = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.listDeviceRegistries(request), expectedError);
assert(
(client.innerApiCalls.listDeviceRegistries as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listDeviceRegistriesStream without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceRegistriesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.iot.v1.DeviceRegistry()),
generateSampleMessage(new protos.google.cloud.iot.v1.DeviceRegistry()),
generateSampleMessage(new protos.google.cloud.iot.v1.DeviceRegistry()),
];
client.descriptors.page.listDeviceRegistries.createStream =
stubPageStreamingCall(expectedResponse);
const stream = client.listDeviceRegistriesStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.cloud.iot.v1.DeviceRegistry[] = [];
stream.on(
'data',
(response: protos.google.cloud.iot.v1.DeviceRegistry) => {
responses.push(response);
}
);
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
const responses = await promise;
assert.deepStrictEqual(responses, expectedResponse);
assert(
(client.descriptors.page.listDeviceRegistries.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listDeviceRegistries, request)
);
assert.strictEqual(
(
client.descriptors.page.listDeviceRegistries.createStream as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('invokes listDeviceRegistriesStream with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceRegistriesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listDeviceRegistries.createStream =
stubPageStreamingCall(undefined, expectedError);
const stream = client.listDeviceRegistriesStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.cloud.iot.v1.DeviceRegistry[] = [];
stream.on(
'data',
(response: protos.google.cloud.iot.v1.DeviceRegistry) => {
responses.push(response);
}
);
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
await assert.rejects(promise, expectedError);
assert(
(client.descriptors.page.listDeviceRegistries.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listDeviceRegistries, request)
);
assert.strictEqual(
(
client.descriptors.page.listDeviceRegistries.createStream as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listDeviceRegistries without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceRegistriesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.iot.v1.DeviceRegistry()),
generateSampleMessage(new protos.google.cloud.iot.v1.DeviceRegistry()),
generateSampleMessage(new protos.google.cloud.iot.v1.DeviceRegistry()),
];
client.descriptors.page.listDeviceRegistries.asyncIterate =
stubAsyncIterationCall(expectedResponse);
const responses: protos.google.cloud.iot.v1.IDeviceRegistry[] = [];
const iterable = client.listDeviceRegistriesAsync(request);
for await (const resource of iterable) {
responses.push(resource!);
}
assert.deepStrictEqual(responses, expectedResponse);
assert.deepStrictEqual(
(
client.descriptors.page.listDeviceRegistries.asyncIterate as SinonStub
).getCall(0).args[1],
request
);
assert.strictEqual(
(
client.descriptors.page.listDeviceRegistries.asyncIterate as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listDeviceRegistries with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDeviceRegistriesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listDeviceRegistries.asyncIterate =
stubAsyncIterationCall(undefined, expectedError);
const iterable = client.listDeviceRegistriesAsync(request);
await assert.rejects(async () => {
const responses: protos.google.cloud.iot.v1.IDeviceRegistry[] = [];
for await (const resource of iterable) {
responses.push(resource!);
}
});
assert.deepStrictEqual(
(
client.descriptors.page.listDeviceRegistries.asyncIterate as SinonStub
).getCall(0).args[1],
request
);
assert.strictEqual(
(
client.descriptors.page.listDeviceRegistries.asyncIterate as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
});
describe('listDevices', () => {
it('invokes listDevices without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDevicesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.iot.v1.Device()),
generateSampleMessage(new protos.google.cloud.iot.v1.Device()),
generateSampleMessage(new protos.google.cloud.iot.v1.Device()),
];
client.innerApiCalls.listDevices = stubSimpleCall(expectedResponse);
const [response] = await client.listDevices(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listDevices as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listDevices without error using callback', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDevicesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.iot.v1.Device()),
generateSampleMessage(new protos.google.cloud.iot.v1.Device()),
generateSampleMessage(new protos.google.cloud.iot.v1.Device()),
];
client.innerApiCalls.listDevices =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.listDevices(
request,
(
err?: Error | null,
result?: protos.google.cloud.iot.v1.IDevice[] | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listDevices as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes listDevices with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDevicesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.listDevices = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.listDevices(request), expectedError);
assert(
(client.innerApiCalls.listDevices as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listDevicesStream without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDevicesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.iot.v1.Device()),
generateSampleMessage(new protos.google.cloud.iot.v1.Device()),
generateSampleMessage(new protos.google.cloud.iot.v1.Device()),
];
client.descriptors.page.listDevices.createStream =
stubPageStreamingCall(expectedResponse);
const stream = client.listDevicesStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.cloud.iot.v1.Device[] = [];
stream.on('data', (response: protos.google.cloud.iot.v1.Device) => {
responses.push(response);
});
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
const responses = await promise;
assert.deepStrictEqual(responses, expectedResponse);
assert(
(client.descriptors.page.listDevices.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listDevices, request)
);
assert.strictEqual(
(client.descriptors.page.listDevices.createStream as SinonStub).getCall(
0
).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('invokes listDevicesStream with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDevicesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listDevices.createStream = stubPageStreamingCall(
undefined,
expectedError
);
const stream = client.listDevicesStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.cloud.iot.v1.Device[] = [];
stream.on('data', (response: protos.google.cloud.iot.v1.Device) => {
responses.push(response);
});
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
await assert.rejects(promise, expectedError);
assert(
(client.descriptors.page.listDevices.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listDevices, request)
);
assert.strictEqual(
(client.descriptors.page.listDevices.createStream as SinonStub).getCall(
0
).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listDevices without error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDevicesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.iot.v1.Device()),
generateSampleMessage(new protos.google.cloud.iot.v1.Device()),
generateSampleMessage(new protos.google.cloud.iot.v1.Device()),
];
client.descriptors.page.listDevices.asyncIterate =
stubAsyncIterationCall(expectedResponse);
const responses: protos.google.cloud.iot.v1.IDevice[] = [];
const iterable = client.listDevicesAsync(request);
for await (const resource of iterable) {
responses.push(resource!);
}
assert.deepStrictEqual(responses, expectedResponse);
assert.deepStrictEqual(
(client.descriptors.page.listDevices.asyncIterate as SinonStub).getCall(
0
).args[1],
request
);
assert.strictEqual(
(client.descriptors.page.listDevices.asyncIterate as SinonStub).getCall(
0
).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listDevices with error', async () => {
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.iot.v1.ListDevicesRequest()
);
request.parent = '';
const expectedHeaderRequestParams = 'parent=';
const expectedError = new Error('expected');
client.descriptors.page.listDevices.asyncIterate = stubAsyncIterationCall(
undefined,
expectedError
);
const iterable = client.listDevicesAsync(request);
await assert.rejects(async () => {
const responses: protos.google.cloud.iot.v1.IDevice[] = [];
for await (const resource of iterable) {
responses.push(resource!);
}
});
assert.deepStrictEqual(
(client.descriptors.page.listDevices.asyncIterate as SinonStub).getCall(
0
).args[1],
request
);
assert.strictEqual(
(client.descriptors.page.listDevices.asyncIterate as SinonStub).getCall(
0
).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
});
describe('Path templates', () => {
describe('device', () => {
const fakePath = '/rendered/path/device';
const expectedParameters = {
project: 'projectValue',
location: 'locationValue',
registry: 'registryValue',
device: 'deviceValue',
};
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.devicePathTemplate.render = sinon
.stub()
.returns(fakePath);
client.pathTemplates.devicePathTemplate.match = sinon
.stub()
.returns(expectedParameters);
it('devicePath', () => {
const result = client.devicePath(
'projectValue',
'locationValue',
'registryValue',
'deviceValue'
);
assert.strictEqual(result, fakePath);
assert(
(client.pathTemplates.devicePathTemplate.render as SinonStub)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromDeviceName', () => {
const result = client.matchProjectFromDeviceName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(client.pathTemplates.devicePathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchLocationFromDeviceName', () => {
const result = client.matchLocationFromDeviceName(fakePath);
assert.strictEqual(result, 'locationValue');
assert(
(client.pathTemplates.devicePathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchRegistryFromDeviceName', () => {
const result = client.matchRegistryFromDeviceName(fakePath);
assert.strictEqual(result, 'registryValue');
assert(
(client.pathTemplates.devicePathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchDeviceFromDeviceName', () => {
const result = client.matchDeviceFromDeviceName(fakePath);
assert.strictEqual(result, 'deviceValue');
assert(
(client.pathTemplates.devicePathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
});
describe('location', () => {
const fakePath = '/rendered/path/location';
const expectedParameters = {
project: 'projectValue',
location: 'locationValue',
};
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.locationPathTemplate.render = sinon
.stub()
.returns(fakePath);
client.pathTemplates.locationPathTemplate.match = sinon
.stub()
.returns(expectedParameters);
it('locationPath', () => {
const result = client.locationPath('projectValue', 'locationValue');
assert.strictEqual(result, fakePath);
assert(
(client.pathTemplates.locationPathTemplate.render as SinonStub)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromLocationName', () => {
const result = client.matchProjectFromLocationName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(client.pathTemplates.locationPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchLocationFromLocationName', () => {
const result = client.matchLocationFromLocationName(fakePath);
assert.strictEqual(result, 'locationValue');
assert(
(client.pathTemplates.locationPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
});
describe('registry', () => {
const fakePath = '/rendered/path/registry';
const expectedParameters = {
project: 'projectValue',
location: 'locationValue',
registry: 'registryValue',
};
const client = new devicemanagerModule.v1.DeviceManagerClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
client.pathTemplates.registryPathTemplate.render = sinon
.stub()
.returns(fakePath);
client.pathTemplates.registryPathTemplate.match = sinon
.stub()
.returns(expectedParameters);
it('registryPath', () => {
const result = client.registryPath(
'projectValue',
'locationValue',
'registryValue'
);
assert.strictEqual(result, fakePath);
assert(
(client.pathTemplates.registryPathTemplate.render as SinonStub)
.getCall(-1)
.calledWith(expectedParameters)
);
});
it('matchProjectFromRegistryName', () => {
const result = client.matchProjectFromRegistryName(fakePath);
assert.strictEqual(result, 'projectValue');
assert(
(client.pathTemplates.registryPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchLocationFromRegistryName', () => {
const result = client.matchLocationFromRegistryName(fakePath);
assert.strictEqual(result, 'locationValue');
assert(
(client.pathTemplates.registryPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
it('matchRegistryFromRegistryName', () => {
const result = client.matchRegistryFromRegistryName(fakePath);
assert.strictEqual(result, 'registryValue');
assert(
(client.pathTemplates.registryPathTemplate.match as SinonStub)
.getCall(-1)
.calledWith(fakePath)
);
});
});
});
}); | the_stack |
import ImageLoader from '../image_loader';
import { XYSize, Point } from '../../../type-definitions/quagga.d';
import { InputStreamFactory, InputStream, EventHandlerList } from './input_stream.d';
const inputStreamFactory: InputStreamFactory = {
createVideoStream(video): InputStream {
let _config: { size: number; type: string } | null = null;
const _eventNames = ['canrecord', 'ended'];
const _eventHandlers: EventHandlerList = {};
let _calculatedWidth: number;
let _calculatedHeight: number;
const _topRight: Point = { x: 0, y: 0, type: 'Point' };
const _canvasSize: XYSize = { x: 0, y: 0, type: 'XYSize' };
function initSize(): void {
const width = video.videoWidth;
const height = video.videoHeight;
// eslint-disable-next-line no-nested-ternary
_calculatedWidth = _config?.size ? width / height > 1 ? _config.size : Math.floor((width / height) * _config.size) : width;
// eslint-disable-next-line no-nested-ternary
_calculatedHeight = _config?.size ? width / height > 1 ? Math.floor((height / width) * _config.size) : _config.size : height;
_canvasSize.x = _calculatedWidth;
_canvasSize.y = _calculatedHeight;
}
const inputStream: InputStream = {
getRealWidth() {
return video.videoWidth;
},
getRealHeight() {
return video.videoHeight;
},
getWidth() {
return _calculatedWidth;
},
getHeight() {
return _calculatedHeight;
},
setWidth(width) {
_calculatedWidth = width;
},
setHeight(height) {
_calculatedHeight = height;
},
setInputStream(config) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
_config = config;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
this.setAttribute('src', (typeof config.src !== 'undefined') ? config.src : '');
},
ended() {
return video.ended;
},
getConfig() {
return _config;
},
setAttribute(name, value) {
if (video) {
video.setAttribute(name, value);
}
},
pause() {
video.pause();
},
play() {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
video.play();
},
setCurrentTime(time) {
if (_config?.type !== 'LiveStream') {
this.setAttribute('currentTime', time.toString());
}
},
addEventListener(event, f, bool) {
if (_eventNames.indexOf(event) !== -1) {
if (!_eventHandlers[event]) {
_eventHandlers[event] = [];
}
_eventHandlers[event].push(f);
} else {
video.addEventListener(event, f, bool);
}
},
clearEventHandlers() {
_eventNames.forEach((eventName) => {
const handlers = _eventHandlers[eventName];
if (handlers && handlers.length > 0) {
handlers.forEach((handler) => {
video.removeEventListener(eventName, handler);
});
}
});
},
trigger(eventName, args) {
let j;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const handlers = _eventHandlers[eventName];
if (eventName === 'canrecord') {
initSize();
}
if (handlers && handlers.length > 0) {
for (j = 0; j < handlers.length; j++) {
handlers[j].apply(inputStream, args);
}
}
},
setTopRight(topRight) {
_topRight.x = topRight.x;
_topRight.y = topRight.y;
},
getTopRight() {
return _topRight;
},
setCanvasSize(size) {
_canvasSize.x = size.x;
_canvasSize.y = size.y;
},
getCanvasSize() {
return _canvasSize;
},
getFrame() {
return video;
},
};
return inputStream;
},
createLiveStream(video): InputStream {
if (video) {
video.setAttribute('autoplay', 'true');
}
const that = inputStreamFactory.createVideoStream(video);
that.ended = function ended(): false {
return false;
};
return that;
},
createImageStream(): InputStream {
let _config: { size: number; sequence: any } | null = null;
let width = 0;
let height = 0;
let frameIdx = 0;
let paused = true;
let loaded = false;
let imgArray: any[] | null = null;
let size = 0;
const offset = 1;
let baseUrl: string | null = null;
let ended = false;
let calculatedWidth: number;
let calculatedHeight: number;
const _eventNames = ['canrecord', 'ended'];
const _eventHandlers: EventHandlerList = {};
const _topRight: Point = { x: 0, y: 0, type: 'Point' };
const _canvasSize: XYSize = { x: 0, y: 0, type: 'XYSize' };
function loadImages(): void {
loaded = false;
ImageLoader.load(baseUrl, (imgs: Array<{ tags: any; img: HTMLImageElement}>) => {
imgArray = imgs;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (imgs[0].tags && imgs[0].tags.orientation) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
switch (imgs[0].tags.orientation) {
case 6:
case 8:
width = imgs[0].img.height;
height = imgs[0].img.width;
break;
default:
width = imgs[0].img.width;
height = imgs[0].img.height;
}
} else {
width = imgs[0].img.width;
height = imgs[0].img.height;
}
// eslint-disable-next-line no-nested-ternary
calculatedWidth = _config?.size ? width / height > 1 ? _config.size : Math.floor((width / height) * _config.size) : width;
// eslint-disable-next-line no-nested-ternary
calculatedHeight = _config?.size ? width / height > 1 ? Math.floor((height / width) * _config.size) : _config.size : height;
_canvasSize.x = calculatedWidth;
_canvasSize.y = calculatedHeight;
loaded = true;
frameIdx = 0;
setTimeout(() => {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
publishEvent('canrecord', []);
}, 0);
}, offset, size, _config?.sequence);
}
function publishEvent(eventName: string, args: Array<any>): void {
let j;
const handlers = _eventHandlers[eventName];
if (handlers && handlers.length > 0) {
for (j = 0; j < handlers.length; j++) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
handlers[j].apply(inputStream, args as any); // TODO: typescript complains that any[] is not valid for a second arg for apply?!
}
}
}
// TODO: any code shared with the first InputStream above should be shared not copied
// TODO: publishEvent needs access to inputStream, but inputStream needs access to publishEvent
// TODO: This is why it's a 'var', so it hoists back. This is ugly, and should be changed.
// eslint-disable-next-line no-var,vars-on-top
var inputStream: InputStream = {
trigger: publishEvent,
getWidth() {
return calculatedWidth;
},
getHeight() {
return calculatedHeight;
},
setWidth(newWidth) {
calculatedWidth = newWidth;
},
setHeight(newHeight) {
calculatedHeight = newHeight;
},
getRealWidth() {
return width;
},
getRealHeight() {
return height;
},
setInputStream(stream) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
_config = stream;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (stream.sequence === false) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
baseUrl = stream.src;
size = 1;
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
baseUrl = stream.src;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
size = stream.length;
}
loadImages();
},
ended() {
return ended;
},
setAttribute() {},
getConfig() {
return _config;
},
pause() {
paused = true;
},
play() {
paused = false;
},
setCurrentTime(time) {
frameIdx = time;
},
addEventListener(event, f) {
if (_eventNames.indexOf(event) !== -1) {
if (!_eventHandlers[event]) {
_eventHandlers[event] = [];
}
_eventHandlers[event].push(f);
}
},
clearEventHandlers() {
Object.keys(_eventHandlers).forEach((ind) => delete _eventHandlers[ind]);
},
setTopRight(topRight) {
_topRight.x = topRight.x;
_topRight.y = topRight.y;
},
getTopRight() {
return _topRight;
},
setCanvasSize(canvasSize) {
_canvasSize.x = canvasSize.x;
_canvasSize.y = canvasSize.y;
},
getCanvasSize() {
return _canvasSize;
},
getFrame() {
let frame;
if (!loaded) {
return null;
}
if (!paused) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
frame = imgArray?.[frameIdx];
if (frameIdx < (size - 1)) {
frameIdx++;
} else {
setTimeout(() => {
ended = true;
publishEvent('ended', []);
}, 0);
}
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return frame;
},
};
return inputStream;
},
};
export default inputStreamFactory; | the_stack |
import * as moment from 'moment';
import * as React from 'react';
import * as strings from 'MyTasksWebPartStrings';
import spservices from './../../../../services/spservices';
import styles from './MyTasks.module.scss';
import TaskCard from './../TaskCard/TaskCard';
import {
CommandButton,
Icon,
IContextualMenuProps,
IIconProps,
MessageBar,
MessageBarType,
SearchBox,
Spinner,
SpinnerSize,
Stack
} from 'office-ui-fabric-react';
import { escape } from '@microsoft/sp-lodash-subset';
import { IMyTasksProps } from './IMyTasksProps';
import { IMyTasksState } from './IMyTasksState';
import { ITask } from './../../../../services/ITask';
import { NewTask } from './../NewTask/NewTask';
const filterIcon: IIconProps = { iconName: 'Filter' };
const Data: any[] = require('./../../../../services/mockData.json');
/**
* Filters
*/
export enum filters {
'All Tasks',
'Not Started',
'Started',
'Completed'
}
/**
* My tasks
*/
export default class MyTasks extends React.Component<IMyTasksProps, IMyTasksState> {
private _Tasks: ITask[] = [];
private _spservices: spservices;
private menuProps: IContextualMenuProps = {
items: [
{
key: '0',
text: strings.alltasks,
iconProps: { iconName: 'TaskSolid' },
onClick: this.onClickFilterAllTasks.bind(this)
},
{
key: '1',
text: strings.notStarted,
iconProps: { iconName: 'StatusCircleRing' },
onClick: this.onClickFilterNotStartedTasks.bind(this)
},
{
key: '2',
text: strings.started,
iconProps: { iconName: 'CircleHalfFull' },
onClick: this.onClickFilterStartedTasks.bind(this)
},
{
key: '3',
text: strings.completed,
iconProps: { iconName: 'CompletedSolid' },
onClick: this.onClickFilterCompletedTasks.bind(this)
}
]
};
constructor(props: IMyTasksProps) {
super(props);
this._spservices = new spservices(this.props.context);
this.state = {
tasks: [],
isloading: true,
currentFilter: filters['All Tasks'],
currentFilterLabel: filters[0],
hasError: false,
errorMessage: undefined,
hasMoreTasks: false,
showDialog: false
};
}
/**
* Determines whether refresh on
* @param ev
*/
private _onRefresh = (ev?: any) => {
const currentFilter: filters = this.state.currentFilter;
switch (currentFilter) {
case filters['All Tasks']:
this.onClickFilterAllTasks(ev);
break;
case filters['Not Started']:
this.onClickFilterNotStartedTasks(ev);
break;
case filters.Started:
this.onClickFilterStartedTasks(ev);
break;
case filters.Completed:
this.onClickFilterCompletedTasks(ev);
break;
default:
break;
}
};
/**
* Determines whether click filter all tasks on
* @param ev
*/
private onClickFilterAllTasks(ev: React.MouseEvent<HTMLElement, MouseEvent>) {
this.setState({ isloading: true, currentFilter: filters['All Tasks'] });
this._loadTasks();
}
/**
* Determines whether click filter not started tasks on
* @param ev
*/
private async onClickFilterNotStartedTasks(ev: React.MouseEvent<HTMLElement, MouseEvent>) {
try {
this.setState({ isloading: true, currentFilter: filters['Not Started'] });
let filterTasks: ITask[] = await this._filterNotStartTasks();
filterTasks = await this._sortTasks(filterTasks);
this.setState({
tasks: filterTasks,
isloading: false,
hasError: false,
errorMessage: ''
});
} catch (error) {
this.setState({ hasError: true, errorMessage: error.message, isloading: false });
console.log('error filter Tasks', error);
}
}
/**
* Determines whether click filter started tasks on
* @param ev
*/
private async onClickFilterStartedTasks(ev: React.MouseEvent<HTMLElement, MouseEvent>) {
try {
this.setState({ isloading: true, currentFilter: filters.Started });
let filterTasks: ITask[] = await this._filterStartedTasks();
filterTasks = await this._sortTasks(filterTasks);
this.setState({
tasks: filterTasks,
isloading: false,
hasError: false,
errorMessage: ''
});
} catch (error) {
this.setState({ hasError: true, errorMessage: error.message, isloading: false });
console.log('error filter Tasks', error);
}
}
/**
* Determines whether click filter completed tasks on
* @param ev
*/
private async onClickFilterCompletedTasks(ev: React.MouseEvent<HTMLElement, MouseEvent>) {
try {
this.setState({ isloading: true, currentFilter: filters.Completed });
let filterTasks: ITask[] = await this._filterCompletedTasks();
filterTasks = await this._sortTasks(filterTasks);
this.setState({
tasks: filterTasks,
isloading: false,
hasError: false,
errorMessage: ''
});
} catch (error) {
console.log('error filter Tasks', error);
this.setState({ isloading: false, hasError: true, errorMessage: error.message });
}
}
private _sortTasks(tasks: ITask[]): Promise<ITask[]> {
return new Promise((resolve, reject) => {
const sortedTasks = tasks.sort((a, b) => {
if (a.orderHint < b.orderHint) return -1;
if (a.orderHint > b.orderHint) return 1;
return 0;
});
resolve(sortedTasks);
});
}
/**
* Filters not start tasks
* @returns not start tasks
*/
private _filterNotStartTasks(): Promise<ITask[]> {
return new Promise(async (resolve, reject) => {
this._Tasks = [];
try {
this._Tasks = await this._spservices.getTasks();
this._Tasks = this._Tasks.filter((task: ITask) => {
return task.percentComplete == 0;
});
resolve(this._Tasks);
} catch (error) {
reject(error);
}
});
}
private async _searchTasks(value: string): Promise<void> {
this.setState({ isloading: true, currentFilter: filters['All Tasks'] });
this._Tasks = [];
try {
this._Tasks = await this._spservices.getTasks();
this._Tasks = this._Tasks.filter((task: ITask) => {
let result: number = task.title.indexOf(`${value}`);
return result !== -1 ? true : false;
});
this.setState({ tasks: this._Tasks, isloading: false, currentFilter: filters['All Tasks'] });
} catch (error) {
this.setState({ isloading: false, hasError: true, errorMessage: error.message });
console.log('error filter Tasks', error);
}
}
/**
* Filters started tasks
* @returns started tasks
*/
private _filterStartedTasks(): Promise<ITask[]> {
return new Promise(async (resolve, reject) => {
this._Tasks = [];
try {
this._Tasks = await this._spservices.getTasks();
this._Tasks = this._Tasks.filter((task: ITask) => {
return task.percentComplete == 50;
});
resolve(this._Tasks);
} catch (error) {
reject(error);
}
});
}
/**
* Filters completed tasks
* @returns completed tasks
*/
private _filterCompletedTasks(): Promise<ITask[]> {
return new Promise(async (resolve, reject) => {
this._Tasks = [];
try {
this._Tasks = await this._spservices.getTasks();
this._Tasks = this._Tasks.filter((task: ITask) => {
return task.percentComplete == 100;
});
resolve(this._Tasks);
} catch (error) {
reject(error);
}
});
}
public componentDidUpdate(prevProps: IMyTasksProps, prevState: IMyTasksState): void {}
public async _loadTasks() {
this._Tasks = [];
try {
this.setState({ tasks: this._Tasks, isloading: true });
this._Tasks = await this._spservices.getTasks();
this._Tasks = await this._sortTasks(this._Tasks);
this.setState({
tasks: this._Tasks,
isloading: false
});
} catch (error) {
this.setState({ hasError: true, errorMessage: error.message, isloading: false });
}
}
public async componentDidMount() {
await this._loadTasks();
}
/**
* Determines whether dismiss dialog on
*/
private _onDismissDialog = (refresh: boolean): void => {
if (refresh) {
this.setState({ showDialog: false });
this._onRefresh();
} else {
this.setState({ showDialog: false });
}
};
/**
* Renders my tasks
* @returns render
*/
public render(): React.ReactElement<IMyTasksProps> {
const renderTasks: JSX.Element[] = [];
for (const task of this.state.tasks) {
renderTasks.push(
<TaskCard
task={task}
spservice={this._spservices}
refreshList={refresh => {
if (refresh) {
this._onRefresh();
}
}}
/>
);
}
return (
<div className={styles.myTasks}>
{this.state.isloading ? (
<Spinner size={SpinnerSize.medium}></Spinner>
) : (
<>
{this.state.hasError ? ( // has error
<MessageBar messageBarType={MessageBarType.error}>{this.state.errorMessage}</MessageBar>
) : (
<>
<div className={styles.commandButtonsWrapper}>
<CommandButton
iconProps={{ iconName: 'add' }}
text={strings.AddLabel}
style={{ flexGrow: 8, paddingRight: 10 }}
disabled={false}
onClick={(ev: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement>) => {
this.setState({ showDialog: true });
}}
/>
<SearchBox placeholder={strings.SearchLabel} underlined={true} onSearch={this._searchTasks.bind(this)} />
<CommandButton
iconProps={{ iconName: 'refresh' }}
text={strings.RefreshLabel}
onClick={this._onRefresh}
disabled={false}
/>
<CommandButton
iconProps={filterIcon}
text={filters[this.state.currentFilter]}
menuProps={this.menuProps}
disabled={false}
checked={true}
/>
</div>
{renderTasks.length === 0 ? ( // has tasks ?
<>
<div className={styles.noTasksIcon}>
<Icon iconName='Taskboard' style={{ fontSize: 55 }} />
</div>
<div className={styles.noTaskLabel}>
<span style={{ fontSize: 22 }}>{strings.NoTaskFoundLabel}</span>
</div>
</>
) : (
<>
<Stack wrap horizontal horizontalAlign='start'>
{renderTasks}
</Stack>
</>
)}
{this.state.showDialog && (
<NewTask spservice={this._spservices} displayDialog={this.state.showDialog} onDismiss={this._onDismissDialog} />
)}
</>
)}
</>
)}
</div>
);
}
} | the_stack |
import { Injectable } from '@angular/core';
import { global } from './index';
const timeoutData = { code: -2 };
@Injectable()
export class ApiService {
// 登出
public loginOut(success?: Function) {
return new Promise((resolve) => {
global.JIM.loginOut();
if (success && success instanceof Function) {
success();
}
resolve();
});
}
// 更新会话extra字段
public updateConversation(conversationObj, success?: Function) {
return new Promise((resolve) => {
global.JIM.updateConversation(conversationObj);
if (success && success instanceof Function) {
success();
}
resolve();
});
}
// 重置会话徽标未读数
public resetUnreadCount(conversationObj, success?: Function) {
return new Promise((resolve) => {
global.JIM.resetUnreadCount(conversationObj);
if (success && success instanceof Function) {
success();
}
resolve();
});
}
// JIM初始化
public init(initObj: object, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.init(initObj), success, error, timeout);
}
// 登录
public login(loginObj: object, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.login(loginObj), success, error, timeout);
}
// 注册
public register(registerObj: object, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.register(registerObj), success, error, timeout);
}
// 获取静态资源路径
public getResource(urlObj: object, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.getResource(urlObj), success, error, timeout);
}
// 获取用户资料
public getUserInfo(userObj: object, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.getUserInfo(userObj), success, error, timeout);
}
// 获取好友列表
public getFriendList(success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.getFriendList(), success, error, timeout);
}
// 获取会话列表
public getConversation(success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.getConversation(), success, error, timeout);
}
// 获取群屏蔽列表
public groupShieldList(success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.groupShieldList(), success, error, timeout);
}
// 获取免打扰列表
public getNoDisturb(success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.getNoDisturb(), success, error, timeout);
}
// 获取群组信息
public getGroupInfo(groupObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.getGroupInfo(groupObj), success, error, timeout);
}
// 获取群成员
public getGroupMembers(groupObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.getGroupMembers(groupObj), success, error, timeout);
}
// 更新群组信息
public updateGroupInfo(groupObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.updateGroupInfo(groupObj), success, error, timeout);
}
// 删除群屏蔽
public delGroupShield(groupObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.delGroupShield(groupObj), success, error, timeout);
}
// 添加群屏蔽
public addGroupShield(groupObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.addGroupShield(groupObj), success, error, timeout);
}
// 删除群免打扰
public delGroupNoDisturb(groupObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.delGroupNoDisturb(groupObj), success, error, timeout);
}
// 添加群免打扰
public addGroupNoDisturb(groupObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.addGroupNoDisturb(groupObj), success, error, timeout);
}
// 消息撤回
public msgRetract(msgObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.msgRetract(msgObj), success, error, timeout);
}
// 添加好友
public addFriend(friendObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.addFriend(friendObj), success, error, timeout);
}
// 删除单聊黑名单
public delSingleBlacks(blackObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.delSingleBlacks(blackObj), success, error, timeout);
}
// 删除单聊免打扰
public delSingleNoDisturb
(disturbObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.delSingleNoDisturb(disturbObj), success, error, timeout);
}
// 修改好友备注名
public updateFriendMemo(friendObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.updateFriendMemo(friendObj), success, error, timeout);
}
// 上报单聊已读回执
public addSingleReceiptReport
(msgObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.addSingleReceiptReport(msgObj), success, error, timeout);
}
// 上报群聊已读回执
public addGroupReceiptReport(msgObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.addGroupReceiptReport(msgObj), success, error, timeout);
}
// 添加群成员禁言
public addGroupMemSilence(memberObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.addGroupMemSilence(memberObj), success, error, timeout);
}
// 删除群成员禁言
public delGroupMemSilence(memberObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.delGroupMemSilence(memberObj), success, error, timeout);
}
// 获取群列表
public getGroups(success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.getGroups(), success, error, timeout);
}
// 拒绝好友请求
public declineFriend(friendObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.declineFriend(friendObj), success, error, timeout);
}
// 同意好友请求
public acceptFriend(friendObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.acceptFriend(friendObj), success, error, timeout);
}
// 同意或者拒绝入群请求
public addGroupMemberResp(memberObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.addGroupMemberResp(memberObj), success, error, timeout);
}
// 更新个人资料
public updateSelfInfo(selfInfoObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.updateSelfInfo(selfInfoObj), success, error, timeout);
}
// 创建群组
public createGroup(groupObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.createGroup(groupObj), success, error, timeout);
}
// 添加群成员
public addGroupMembers(memberObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.addGroupMembers(memberObj), success, error, timeout);
}
// 修改密码
public updateSelfPwd(passwordObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.updateSelfPwd(passwordObj), success, error, timeout);
}
// 获取黑名单
public getBlacks(success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.getBlacks(), success, error, timeout);
}
// 添加单聊黑名单
public addSingleBlacks(blackObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.addSingleBlacks(blackObj), success, error, timeout);
}
// 退出群组
public exitGroup(groupObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.exitGroup(groupObj), success, error, timeout);
}
// 删除群成员
public delGroupMembers(memberObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.delGroupMembers(memberObj), success, error, timeout);
}
// 添加单聊免打扰
public addSingleNoDisturb(singleObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.addSingleNoDisturb(singleObj), success, error, timeout);
}
// 删除好友
public delFriend(friendObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.delFriend(friendObj), success, error, timeout);
}
// 获取聊天室资料
public getChatroomInfo(roomObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.getChatroomInfo(roomObj), success, error, timeout);
}
// 加入群组
public joinGroup(groupObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.joinGroup(groupObj), success, error, timeout);
}
// 更新个人头像
public updateSelfAvatar(selfObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.updateSelfAvatar(selfObj), success, error, timeout);
}
// 获取本人所在聊天室列表
public getSelfChatrooms(success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.getSelfChatrooms(), success, error, timeout);
}
// 获取appkey下的聊天室
public getAppkeyChatrooms(roomObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.getAppkeyChatrooms(roomObj), success, error, timeout);
}
// 进入聊天室
public enterChatroom(roomObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.enterChatroom(roomObj), success, error, timeout);
}
// 退出聊天室
public exitChatroom(roomObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.exitChatroom(roomObj), success, error, timeout);
}
// 发送透传消息
public transSingleMsg(msgObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.transSingleMsg(msgObj), success, error, timeout);
}
// 查看未读列表
public msgUnreadList(msgObj, success?: Function, error?: Function, timeout?: Function) {
return this.callback(global.JIM.msgUnreadList(msgObj), success, error, timeout);
}
// 发送聊天室文本消息
public sendChatroomMsg(msgObj, success?: Function, error?: Function, timeout?: Function) {
return this.msgCallback(global.JIM.sendChatroomMsg(msgObj), success, error, timeout);
}
// 发送聊天室文件消息
public sendChatroomFile(fileObj, success?: Function, error?: Function, timeout?: Function) {
return this.msgCallback(global.JIM.sendChatroomFile(fileObj), success, error, timeout);
}
// 发送聊天室图片
public sendChatroomPic(picObj, success?: Function, error?: Function, timeout?: Function) {
return this.msgCallback(global.JIM.sendChatroomPic(picObj), success, error, timeout);
}
// 发送或者转发单聊文本
public sendSingleMsg(singleMsg, success?: Function, error?: Function, timeout?: Function) {
return this.msgCallback(global.JIM.sendSingleMsg(singleMsg), success, error, timeout);
}
// 发送或者转发群聊文本
public sendGroupMsg(groupleMsg, success?: Function, error?: Function, timeout?: Function) {
return this.msgCallback(global.JIM.sendGroupMsg(groupleMsg), success, error, timeout);
}
// 发送或者转发单聊图片
public sendSinglePic(singlePic, success?: Function, error?: Function, timeout?: Function) {
return this.msgCallback(global.JIM.sendSinglePic(singlePic), success, error, timeout);
}
// 发送或者转发群聊图片
public sendGroupPic(groupPic, success?: Function, error?: Function, timeout?: Function) {
return this.msgCallback(global.JIM.sendGroupPic(groupPic), success, error, timeout);
}
// 发送或者转发单聊文件
public sendSingleFile(singleFile, success?: Function, error?: Function, timeout?: Function) {
return this.msgCallback(global.JIM.sendSingleFile(singleFile), success, error, timeout);
}
// 发送或者转发群聊文件
public sendGroupFile(groupFile, success?: Function, error?: Function, timeout?: Function) {
return this.msgCallback(global.JIM.sendGroupFile(groupFile), success, error, timeout);
}
// 发送或者转发单聊位置
public sendSingleLocation
(singleLocation, success?: Function, error?: Function, timeout?: Function) {
return this.msgCallback(global.JIM.sendSingleLocation(singleLocation), success, error, timeout);
}
// 发送或者转发群聊位置
public sendGroupLocation
(groupLocation, success?: Function, error?: Function, timeout?: Function) {
return this.msgCallback(global.JIM.sendGroupLocation(groupLocation), success, error, timeout);
}
// 回调函数
private callback(obj, ...args): Promise<any> {
return new Promise((resolve) => {
if (obj && obj.onSuccess) {
obj.onSuccess((successData) => {
if (successData.code) {
delete successData.code;
}
if (args[0] && args[0] instanceof Function) {
args[0](successData);
}
resolve(successData);
}).onFail((errorData) => {
if (args[1] && args[1] instanceof Function) {
args[1](errorData);
}
resolve(errorData);
}).onTimeout(() => {
if (args[2] && args[2] instanceof Function) {
args[2]();
}
resolve(timeoutData);
});
}
});
}
// 发送消息回调函数
private msgCallback(obj, ...args): Promise<any> {
return new Promise((resolve) => {
if (obj && obj.onSuccess) {
obj.onSuccess((successData, msgs) => {
if (successData.key) {
msgs.key = successData.key;
}
msgs.unread_count = successData.unread_count || 0;
if (args[0] && args[0] instanceof Function) {
args[0](msgs);
}
resolve(msgs);
}).onFail((errorData) => {
if (args[1] && args[1] instanceof Function) {
args[1](errorData);
}
resolve(errorData);
}).onTimeout(() => {
if (args[2] && args[2] instanceof Function) {
args[2]();
}
resolve(timeoutData);
});
}
});
}
} | the_stack |
import { GeoPackageConnection } from './geoPackageConnection'
import { UserTable } from '../user/userTable'
import { UserCustomTableReader } from '../user/custom/userCustomTableReader'
import { CoreSQLUtils } from './coreSQLUtils'
import { StringUtils } from './stringUtils'
import { UserCustomTable } from '../user/custom/userCustomTable'
import { TableMapping } from './tableMapping'
import { UserColumn } from '../user/userColumn'
import { Constraint } from './table/constraint'
import { RawConstraint } from './table/rawConstraint'
import { ConstraintParser } from './table/constraintParser'
import { SQLiteMaster } from './master/sqliteMaster'
import { SQLiteMasterColumn } from './master/sqliteMasterColumn'
import { SQLiteMasterType } from './master/sqliteMasterType'
import { SQLiteMasterQuery } from './master/sqliteMasterQuery'
import { RTreeIndexDao } from '../extension/rtree/rtreeIndexDao'
/**
* Builds and performs alter table statements
*/
export class AlterTable {
/**
* Create the ALTER TABLE SQL command prefix
* @param table table name
* @return alter table SQL prefix
*/
static alterTableSQL (table: string) {
return 'ALTER TABLE ' + StringUtils.quoteWrap(table)
}
/**
* Rename a table
* @param db connection
* @param tableName table name
* @param newTableName new table name
*/
static renameTable (db: GeoPackageConnection, tableName: string, newTableName: string) {
const sql = AlterTable.renameTableSQL(tableName, newTableName)
db.run(sql)
}
/**
* Create the rename table SQL
* @param tableName table name
* @param newTableName new table name
* @return rename table SQL
*/
static renameTableSQL (tableName: string, newTableName: string) {
return AlterTable.alterTableSQL(tableName) + ' RENAME TO ' + StringUtils.quoteWrap(newTableName)
}
/**
* Rename a column
* @param db connection
* @param tableName table name
* @param columnName column name
* @param newColumnName new column name
*/
static renameColumn (db: GeoPackageConnection, tableName: string, columnName: string, newColumnName: string) {
const sql = AlterTable.renameColumnSQL(tableName, columnName, newColumnName)
db.run(sql)
}
/**
* Create the rename column SQL
* @param tableName table name
* @param columnName column name
* @param newColumnName new column name
* @return rename table SQL
*/
static renameColumnSQL (tableName: string, columnName: string, newColumnName: string) {
return AlterTable.alterTableSQL(tableName) + ' RENAME COLUMN ' + StringUtils.quoteWrap(columnName) + ' TO ' + StringUtils.quoteWrap(newColumnName)
}
/**
* Add a column
* @param db connection
* @param tableName table name
* @param columnName column name
* @param columnDef column definition
*/
static addColumn (db: GeoPackageConnection, tableName: string, columnName: string, columnDef: string) {
const sql = AlterTable.addColumnSQL(tableName, columnName, columnDef)
db.run(sql)
}
/**
* Create the add column SQL
* @param tableName table name
* @param columnName column name
* @param columnDef column definition
* @return add column SQL
*/
static addColumnSQL (tableName: string, columnName: string, columnDef: string) {
return AlterTable.alterTableSQL(tableName) + ' ADD COLUMN ' + StringUtils.quoteWrap(columnName) + ' ' + columnDef
}
/**
* Drop a column
* @param db connection
* @param table table
* @param columnName column name
*/
static dropColumnForUserTable (db: GeoPackageConnection, table: UserTable<UserColumn>, columnName: string) {
AlterTable.dropColumnsForUserTable(db, table, [columnName])
}
/**
* Drop columns
*
* @param db connection
* @param table table
* @param columnNames column names
*/
static dropColumnsForUserTable (db: GeoPackageConnection, table: UserTable<UserColumn>, columnNames: Array<string>) {
const newTable: UserTable<UserColumn> = table.copy()
columnNames.forEach(columnName => {
newTable.dropColumnWithName(columnName)
})
// Build the table mapping
const tableMapping = new TableMapping(newTable.getTableName(), newTable.getTableName(), newTable.getUserColumns().getColumns())
columnNames.forEach(columnName => {
tableMapping.addDroppedColumn(columnName)
})
AlterTable.alterTableWithTableMapping(db, newTable, tableMapping)
columnNames.forEach(columnName => {
table.dropColumnWithName(columnName)
})
}
/**
* Drop a column
* @param db connection
* @param tableName table name
* @param columnName column name
*/
static dropColumn(db: GeoPackageConnection, tableName: string, columnName: string) {
AlterTable.dropColumns(db, tableName, [columnName])
}
/**
* Drop columns
*
* @param db connection
* @param tableName table name
* @param columnNames column names
*/
static dropColumns (db: GeoPackageConnection, tableName: string, columnNames: Array<string>) {
const userTable: UserTable<UserColumn> = new UserCustomTableReader(tableName).readTable(db)
AlterTable.dropColumnsForUserTable(db, userTable, columnNames)
}
/**
* Alter a column
* @param db connection
* @param table table
* @param column column
* @param user column type
*/
static alterColumnForTable(db: GeoPackageConnection, table: UserTable<UserColumn>, column: any) {
AlterTable.alterColumnsForTable(db, table, [column])
}
/**
* Alter columns
* @param db connection
* @param table table
* @param columns columns
*/
static alterColumnsForTable(db: GeoPackageConnection, table: UserTable<UserColumn>, columns: UserColumn[]) {
const newTable: UserTable<UserColumn> = table.copy()
columns.forEach(column => {
newTable.alterColumn(column)
})
AlterTable.alterTable(db, newTable)
columns.forEach(column => {
table.alterColumn(column)
})
}
/**
* Alter a column
* @param db connection
* @param tableName table name
* @param column column
*/
static alterColumn(db: GeoPackageConnection, tableName: string, column: UserColumn) {
AlterTable.alterColumns(db, tableName, [column])
}
/**
* Alter columns
* @param db connection
* @param tableName table name
* @param columns columns
*/
static alterColumns(db: GeoPackageConnection, tableName: string, columns: UserColumn[]) {
const userTable: UserCustomTable = new UserCustomTableReader(tableName).readTable(db)
AlterTable.alterColumnsForTable(db, userTable, columns)
}
/**
* Copy the table
* @param db connection
* @param table table
* @param newTableName new table name
* @param transferContent transfer row content to the new table
*/
static copyTable(db: GeoPackageConnection, table: UserTable<UserColumn>, newTableName: string, transferContent: boolean = true) {
// Build the table mapping
const tableMapping = new TableMapping(table.getTableName(), newTableName, table.getUserColumns().getColumns())
tableMapping.transferContent = transferContent
AlterTable.alterTableWithTableMapping(db, table, tableMapping)
}
/**
* Copy the table
* @param db connection
* @param tableName table name
* @param newTableName new table name
* @param transferContent transfer row content to the new table
*/
static copyTableWithName(db: GeoPackageConnection, tableName: string, newTableName: string, transferContent: boolean = true) {
const userTable: UserCustomTable = new UserCustomTableReader(tableName).readTable(db)
AlterTable.copyTable(db, userTable, newTableName, transferContent)
}
/**
* Alter a table with a new table schema assuming a default table mapping.
* This removes views on the table, creates a new table, transfers the old
* table data to the new, drops the old table, and renames the new table to
* the old. Indexes, triggers, and views that reference deleted columns are
* not recreated. An attempt is made to recreate the others including any
* modifications for renamed columns.
*
* Making Other Kinds Of Table Schema Changes:
* https://www.sqlite.org/lang_altertable.html
*
* @param db connection
* @param newTable new table schema
*/
static alterTable(db: GeoPackageConnection, newTable: UserTable<UserColumn>) {
// Build the table mapping
const tableMapping = new TableMapping(newTable.getTableName(), newTable.getTableName(), newTable.getUserColumns().getColumns())
AlterTable.alterTableWithTableMapping(db, newTable, tableMapping)
}
/**
* Alter a table with a new table schema and table mapping.
*
* Altering a table: Removes views on the table, creates a new table,
* transfers the old table data to the new, drops the old table, and renames
* the new table to the old. Indexes, triggers, and views that reference
* deleted columns are not recreated. An attempt is made to recreate the
* others including any modifications for renamed columns.
*
* Creating a new table: Creates a new table and transfers the table data to
* the new. Triggers are not created on the new table. Indexes and views
* that reference deleted columns are not recreated. An attempt is made to
* create the others on the new table.
*
* Making Other Kinds Of Table Schema Changes:
* https://www.sqlite.org/lang_altertable.html
*
* @param db connection
* @param newTable new table schema
* @param tableMapping table mapping
*/
static alterTableWithTableMapping(db: GeoPackageConnection, newTable: UserTable<UserColumn>, tableMapping: TableMapping) {
// Update column constraints
newTable.getUserColumns().getColumns().forEach((column: UserColumn) => {
const columnConstraints = column.clearConstraints()
columnConstraints.forEach((columnConstraint: Constraint) => {
const updatedSql = CoreSQLUtils.modifySQL(null, columnConstraint.name, columnConstraint.buildSql(), tableMapping)
if (updatedSql !== null && updatedSql !== undefined) {
column.addConstraint(new RawConstraint(columnConstraint.type, ConstraintParser.getName(updatedSql), updatedSql))
}
})
})
// Update table constraints
const tableConstraints = newTable.clearConstraints()
tableConstraints.forEach((tableConstraint: Constraint) => {
const updatedSql = CoreSQLUtils.modifySQL(null, tableConstraint.name, tableConstraint.buildSql(), tableMapping)
if (updatedSql !== null && updatedSql !== undefined) {
newTable.addConstraint(new RawConstraint(tableConstraint.type, tableConstraint.name, updatedSql))
}
})
// Build the create table sql
const sql = CoreSQLUtils.createTableSQL(newTable)
AlterTable.alterTableWithSQLAndTableMapping(db, sql, tableMapping)
}
/**
* Alter a table with a new table SQL creation statement and table mapping.
*
* Altering a table: Removes views on the table, creates a new table,
* transfers the old table data to the new, drops the old table, and renames
* the new table to the old. Indexes, triggers, and views that reference
* deleted columns are not recreated. An attempt is made to recreate the
* others including any modifications for renamed columns.
*
* Creating a new table: Creates a new table and transfers the table data to
* the new. Triggers are not created on the new table. Indexes and views
* that reference deleted columns are not recreated. An attempt is made to
* create the others on the new table.
*
* Making Other Kinds Of Table Schema Changes:
* https://www.sqlite.org/lang_altertable.html
*
* @param db
* connection
* @param sql
* new table SQL
* @param tableMapping
* table mapping
*/
static alterTableWithSQLAndTableMapping(db: GeoPackageConnection, sql: string, tableMapping: TableMapping) {
let tableName = tableMapping.fromTable
// Determine if a new table copy vs an alter table
let newTable = tableMapping.isNewTable()
// 1. Disable foreign key constraints
let enableForeignKeys = CoreSQLUtils.setForeignKeys(db, false)
// 2. Start a transaction
let successful = true
db.transaction(() => {
try {
// 9a. Query for views
let views = SQLiteMaster.queryViewsOnTable(db, [SQLiteMasterColumn.NAME, SQLiteMasterColumn.SQL], tableName)
// Remove the views if not a new table
if (!newTable) {
for (let i = 0; i < views.count(); i++) {
let viewName = views.getName(i)
try {
CoreSQLUtils.dropView(db, viewName)
} catch (error) {
console.warn('Failed to drop view: ' + viewName + ', table: ' + tableName, error)
}
}
}
// 3. Query indexes and triggers
let indexesAndTriggers = SQLiteMaster.query(db,
[SQLiteMasterColumn.NAME, SQLiteMasterColumn.TYPE, SQLiteMasterColumn.SQL],
[SQLiteMasterType.INDEX, SQLiteMasterType.TRIGGER],
SQLiteMasterQuery.createForColumnValue(SQLiteMasterColumn.TBL_NAME, tableName))
// Get the temporary or new table name
let transferTable
if (newTable) {
transferTable = tableMapping.toTable
} else {
transferTable = CoreSQLUtils.tempTableName(db, 'new', tableName)
tableMapping.toTable = transferTable
}
// 4. Create the new table
sql = sql.replace(tableName, transferTable)
db.run(sql)
// If transferring content
if (tableMapping.isTransferContent()) {
// 5. Transfer content to new table
CoreSQLUtils.transferTableContentForTableMapping(db, tableMapping)
}
// If altering a table
if (!newTable) {
// 6. Drop the old table
CoreSQLUtils.dropTable(db, tableName)
// 7. Rename the new table
AlterTable.renameTable(db, transferTable, tableName)
tableMapping.toTable = tableName
}
// 8. Create the indexes and triggers
for (let i = 0; i < indexesAndTriggers.count(); i++) {
let create = !newTable
if (!create) {
// Don't create rtree triggers for new tables
create = indexesAndTriggers.getType(i) != SQLiteMasterType.TRIGGER || !indexesAndTriggers.getName(i).startsWith(RTreeIndexDao.PREFIX)
}
if (create) {
let tableSql = indexesAndTriggers.getSql(i)
if (tableSql != null) {
tableSql = CoreSQLUtils.modifySQL(db,
indexesAndTriggers.getName(i), tableSql,
tableMapping)
if (tableSql != null) {
try {
db.run(tableSql)
} catch (e) {
console.warn('Failed to recreate '
+ indexesAndTriggers.getType(i)
+ ' after table alteration. table: '
+ tableMapping.toTable + ', sql: '
+ tableSql, e)
}
}
}
}
}
// 9b. Recreate views
for (let i = 0; i < views.count(); i++) {
let viewSql = views.getSql(i)
if (viewSql !== null && viewSql !== undefined) {
viewSql = CoreSQLUtils.modifySQL(db, views.getName(i), viewSql, tableMapping)
if (viewSql !== null && viewSql !== undefined) {
try {
db.run(viewSql)
} catch (e) {
console.warn(
'Failed to recreate view: '
+ views.getName(i) + ', table: '
+ tableMapping.toTable
+ ', sql: ' + viewSql,
e)
}
}
}
}
// 10. Foreign key check
if (enableForeignKeys) {
AlterTable.foreignKeyCheck(db)
}
} catch (e) {
successful = false
}
})
// 12. Re-enable foreign key constraints
if (enableForeignKeys) {
CoreSQLUtils.setForeignKeys(db, true)
}
}
/**
* Perform a foreign key check for violations
* @param db connection
*/
static foreignKeyCheck (db: GeoPackageConnection) {
const violations = CoreSQLUtils.foreignKeyCheck(db)
if (violations.length > 0) {
let violationsMessage = []
for (let i = 0; i < violations.length; i++) {
if (i > 0) {
violationsMessage = violationsMessage.concat(' ')
}
violationsMessage = violationsMessage.concat(i + 1).concat(': ')
let violation = violations[i]
for (let j = 0; j < violation.length; j++) {
if (j > 0) {
violationsMessage = violationsMessage.concat(', ')
}
violationsMessage = violationsMessage.concat(violation.get(j))
}
}
throw new Error('Foreign Key Check Violations: ' + violationsMessage)
}
}
} | the_stack |
import assert from 'assert';
import { r } from '../src';
import config from './config';
describe('math and logic', () => {
before(async () => {
await r.connectPool(config);
});
after(async () => {
await r.getPoolMaster().drain();
});
it('`add` should work', async () => {
let result = await r
.expr(1)
.add(1)
.run();
assert.equal(result, 2);
result = await r
.expr(1)
.add(1)
.add(1)
.run();
assert.equal(result, 3);
result = await r
.expr(1)
.add(1, 1)
.run();
assert.equal(result, 3);
result = await r.add(1, 1, 1).run();
assert.equal(result, 3);
});
it('`add` should throw if no argument has been passed', async () => {
try {
await r
.expr(1)
.add()
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`add` takes at least 1 argument, 0 provided after:\nr.expr(1)\n'
);
}
});
it('`add` should throw if no argument has been passed -- r.add', async () => {
try {
// @ts-ignore
await r.add().run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`r.add` takes at least 2 arguments, 0 provided.'
);
}
});
it('`add` should throw if just one argument has been passed -- r.add', async () => {
try {
await r.add(1).run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`r.add` takes at least 2 arguments, 1 provided.'
);
}
});
it('`sub` should work', async () => {
let result = await r
.expr(1)
.sub(1)
.run();
assert.equal(result, 0);
result = await r.sub(5, 3, 1).run();
assert.equal(result, 1);
});
it('`sub` should throw if no argument has been passed', async () => {
try {
await r
.expr(1)
.sub()
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`sub` takes at least 1 argument, 0 provided after:\nr.expr(1)\n'
);
}
});
it('`sub` should throw if no argument has been passed -- r.sub', async () => {
try {
// @ts-ignore;
await r.sub().run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`r.sub` takes at least 2 arguments, 0 provided.'
);
}
});
it('`sub` should throw if just one argument has been passed -- r.sub', async () => {
try {
await r.sub(1).run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`r.sub` takes at least 2 arguments, 1 provided.'
);
}
});
it('`mul` should work', async () => {
let result = await r
.expr(2)
.mul(3)
.run();
assert.equal(result, 6);
result = await r.mul(2, 3, 4).run();
assert.equal(result, 24);
});
it('`mul` should throw if no argument has been passed', async () => {
try {
await r
.expr(1)
.mul()
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`mul` takes at least 1 argument, 0 provided after:\nr.expr(1)\n'
);
}
});
it('`mul` should throw if no argument has been passed -- r.mul', async () => {
try {
// @ts-ignore
await r.mul().run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`r.mul` takes at least 2 arguments, 0 provided.'
);
}
});
it('`mul` should throw if just one argument has been passed -- r.mul', async () => {
try {
await r.mul(1).run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`r.mul` takes at least 2 arguments, 1 provided.'
);
}
});
it('`div` should work', async () => {
let result = await r
.expr(24)
.div(2)
.run();
assert.equal(result, 12);
result = await r.div(20, 2, 5, 1).run();
assert.equal(result, 2);
});
it('`div` should throw if no argument has been passed', async () => {
try {
await r
.expr(1)
.div()
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`div` takes at least 1 argument, 0 provided after:\nr.expr(1)\n'
);
}
});
it('`div` should throw if no argument has been passed -- r.div', async () => {
try {
// @ts-ignore
await r.div().run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`r.div` takes at least 2 arguments, 0 provided.'
);
}
});
it('`div` should throw if just one argument has been passed -- r.div', async () => {
try {
await r.div(1).run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`r.div` takes at least 2 arguments, 1 provided.'
);
}
});
it('`mod` should work', async () => {
let result = await r
.expr(24)
.mod(7)
.run();
assert.equal(result, 3);
result = await r.mod(24, 7).run();
assert.equal(result, 3);
});
it('`mod` should throw if no argument has been passed', async () => {
try {
await r
.expr(1)
.mod()
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`mod` takes 1 argument, 0 provided after:\nr.expr(1)\n'
);
}
});
it('`mod` should throw if more than two arguments -- r.mod', async () => {
try {
await r.mod(24, 7, 2).run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.mod` takes 2 arguments, 3 provided.');
}
});
it('`and` should work', async () => {
let result = await r
.expr(true)
.and(false)
.run();
assert.equal(result, false);
result = await r
.expr(true)
.and(true)
.run();
assert.equal(result, true);
result = await r.and(true, true, true).run();
assert.equal(result, true);
result = await r.and(true, true, true, false).run();
assert.equal(result, false);
result = await r.and(r.args([true, true, true])).run();
assert.equal(result, true);
});
// it('`and` should work if no argument has been passed -- r.and', async () => {
// const result = await r.and().run();
// assert.equal(result, true);
// });
it('`or` should work', async () => {
let result = await r
.expr(true)
.or(false)
.run();
assert.equal(result, true);
result = await r
.expr(false)
.or(false)
.run();
assert.equal(result, false);
result = await r.or(true, true, true).run();
assert.equal(result, true);
result = await r.or(r.args([false, false, true])).run();
assert.equal(result, true);
result = await r.or(false, false, false, false).run();
assert.equal(result, false);
});
// it('`or` should work if no argument has been passed -- r.or', async () => {
// const result = await r.or().run();
// assert.equal(result, false);
// });
it('`eq` should work', async () => {
let result = await r
.expr(1)
.eq(1)
.run();
assert.equal(result, true);
result = await r
.expr(1)
.eq(2)
.run();
assert.equal(result, false);
result = await r.eq(1, 1, 1, 1).run();
assert.equal(result, true);
result = await r.eq(1, 1, 2, 1).run();
assert.equal(result, false);
});
it('`eq` should throw if no argument has been passed', async () => {
try {
await r
.expr(1)
.eq()
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`eq` takes at least 1 argument, 0 provided after:\nr.expr(1)\n'
);
}
});
it('`eq` should throw if no argument has been passed -- r.eq', async () => {
try {
// @ts-ignore
await r.eq().run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.eq` takes at least 2 arguments, 0 provided.');
}
});
it('`eq` should throw if just one argument has been passed -- r.eq', async () => {
try {
await r.eq(1).run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.eq` takes at least 2 arguments, 1 provided.');
}
});
it('`ne` should work', async () => {
let result = await r
.expr(1)
.ne(1)
.run();
assert.equal(result, false);
result = await r
.expr(1)
.ne(2)
.run();
assert.equal(result, true);
result = await r.ne(1, 1, 1, 1).run();
assert.equal(result, false);
result = await r.ne(1, 1, 2, 1).run();
assert.equal(result, true);
});
it('`ne` should throw if no argument has been passed', async () => {
try {
await r
.expr(1)
.ne()
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`ne` takes at least 1 argument, 0 provided after:\nr.expr(1)\n'
);
}
});
it('`ne` should throw if no argument has been passed -- r.ne', async () => {
try {
// @ts-ignore
await r.ne().run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.ne` takes at least 2 arguments, 0 provided.');
}
});
it('`ne` should throw if just one argument has been passed -- r.ne', async () => {
try {
await r.ne(1).run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.ne` takes at least 2 arguments, 1 provided.');
}
});
it('`gt` should work', async () => {
let result = await r
.expr(1)
.gt(2)
.run();
assert.equal(result, false);
result = await r
.expr(2)
.gt(2)
.run();
assert.equal(result, false);
result = await r
.expr(3)
.gt(2)
.run();
assert.equal(result, true);
result = await r.gt(10, 9, 7, 2).run();
assert.equal(result, true);
result = await r.gt(10, 9, 9, 1).run();
assert.equal(result, false);
});
it('`gt` should throw if no argument has been passed', async () => {
try {
await r
.expr(1)
.gt()
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`gt` takes at least 1 argument, 0 provided after:\nr.expr(1)\n'
);
}
});
it('`gt` should throw if no argument has been passed -- r.gt', async () => {
try {
// @ts-ignore
await r.gt().run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.gt` takes at least 2 arguments, 0 provided.');
}
});
it('`gt` should throw if just one argument has been passed -- r.gt', async () => {
try {
await r.gt(1).run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.gt` takes at least 2 arguments, 1 provided.');
}
});
it('`ge` should work', async () => {
let result = await r
.expr(1)
.ge(2)
.run();
assert.equal(result, false);
result = await r
.expr(2)
.ge(2)
.run();
assert.equal(result, true);
result = await r
.expr(3)
.ge(2)
.run();
assert.equal(result, true);
result = await r.ge(10, 9, 7, 2).run();
assert.equal(result, true);
result = await r.ge(10, 9, 9, 1).run();
assert.equal(result, true);
result = await r.ge(10, 9, 10, 1).run();
assert.equal(result, false);
});
it('`ge` should throw if no argument has been passed', async () => {
try {
await r
.expr(1)
.ge()
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`ge` takes at least 1 argument, 0 provided after:\nr.expr(1)\n'
);
}
});
it('`ge` should throw if no argument has been passed -- r.ge', async () => {
try {
// @ts-ignore
await r.ge().run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.ge` takes at least 2 arguments, 0 provided.');
}
});
it('`ge` should throw if just one argument has been passed -- r.ge', async () => {
try {
await r.ge(1).run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.ge` takes at least 2 arguments, 1 provided.');
}
});
it('`lt` should work', async () => {
let result = await r
.expr(1)
.lt(2)
.run();
assert.equal(result, true);
result = await r
.expr(2)
.lt(2)
.run();
assert.equal(result, false);
result = await r
.expr(3)
.lt(2)
.run();
assert.equal(result, false);
result = await r.lt(0, 2, 4, 20).run();
assert.equal(result, true);
result = await r.lt(0, 2, 2, 4).run();
assert.equal(result, false);
result = await r.lt(0, 2, 1, 20).run();
assert.equal(result, false);
});
it('`lt` should throw if no argument has been passed', async () => {
try {
await r
.expr(1)
.lt()
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`lt` takes at least 1 argument, 0 provided after:\nr.expr(1)\n'
);
}
});
it('`lt` should throw if no argument has been passed -- r.lt', async () => {
try {
// @ts-ignore
await r.lt().run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.lt` takes at least 2 arguments, 0 provided.');
}
});
it('`lt` should throw if just one argument has been passed -- r.lt', async () => {
try {
await r.lt(1).run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.lt` takes at least 2 arguments, 1 provided.');
}
});
it('`le` should work', async () => {
let result = await r
.expr(1)
.le(2)
.run();
assert.equal(result, true);
result = await r
.expr(2)
.le(2)
.run();
assert.equal(result, true);
result = await r
.expr(3)
.le(2)
.run();
assert.equal(result, false);
result = await r.le(0, 2, 4, 20).run();
assert.equal(result, true);
result = await r.le(0, 2, 2, 4).run();
assert.equal(result, true);
result = await r.le(0, 2, 1, 20).run();
assert.equal(result, false);
});
it('`le` should throw if no argument has been passed', async () => {
try {
await r
.expr(1)
.le()
.run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'`le` takes at least 1 argument, 0 provided after:\nr.expr(1)\n'
);
}
});
it('`le` should throw if no argument has been passed -- r.le', async () => {
try {
// @ts-ignore
await r.le().run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.le` takes at least 2 arguments, 0 provided.');
}
});
it('`le` should throw if just one argument has been passed -- r.le', async () => {
try {
await r.le(1).run();
assert.fail('should throw');
} catch (e) {
assert.equal(e.message, '`r.le` takes at least 2 arguments, 1 provided.');
}
});
it('`not` should work', async () => {
let result = await r
.expr(true)
.not()
.run();
assert.equal(result, false);
result = await r
.expr(false)
.not()
.run();
assert.equal(result, true);
});
it('`random` should work', async () => {
let result = await r.random().run();
assert(result > 0 && result < 1);
result = await r.random(10).run();
assert(result >= 0 && result < 10);
assert.equal(Math.floor(result), result);
result = await r.random(5, 10).run();
assert(result >= 5 && result < 10);
assert.equal(Math.floor(result), result);
result = await r.random(5, 10, { float: true }).run();
assert(result >= 5 && result < 10);
assert.notEqual(Math.floor(result), result); // that's "almost" safe
result = await r.random(5, { float: true }).run();
assert(result < 5 && result > 0);
assert.notEqual(Math.floor(result), result); // that's "almost" safe
});
it('`r.floor` should work', async () => {
let result = await r.floor(1.2).run();
assert.equal(result, 1);
result = await r
.expr(1.2)
.floor()
.run();
assert.equal(result, 1);
result = await r.floor(1.8).run();
assert.equal(result, 1);
result = await r
.expr(1.8)
.floor()
.run();
assert.equal(result, 1);
});
it('`r.ceil` should work', async () => {
let result = await r.ceil(1.2).run();
assert.equal(result, 2);
result = await r
.expr(1.2)
.ceil()
.run();
assert.equal(result, 2);
result = await r.ceil(1.8).run();
assert.equal(result, 2);
result = await r
.expr(1.8)
.ceil()
.run();
assert.equal(result, 2);
});
it('`r.round` should work', async () => {
let result = await r.round(1.8).run();
assert.equal(result, 2);
result = await r
.expr(1.8)
.round()
.run();
assert.equal(result, 2);
result = await r.round(1.2).run();
assert.equal(result, 1);
result = await r
.expr(1.2)
.round()
.run();
assert.equal(result, 1);
});
}); | the_stack |
import React from 'react';
import PropTypes from 'prop-types';
import warning from 'warning';
import classNames from 'classnames';
import LoaderDots from '../LoaderDots/index';
import { InputRowContext } from '../InputRow/index';
import getAnchorProps from './get-anchor-props';
import getButtonProps from './get-button-props';
import styles from './themed.module.scss';
enum loaderDotsTheme {
primary = 'inverse',
secondary = 'brand',
tertiary = 'muted',
}
const withIcon = (
children: React.ReactNode,
{ icon, iconRight }: { icon?: React.ReactNode; iconRight?: React.ReactNode },
): React.ReactNode => {
if (!icon && !iconRight) {
return children;
}
return (
<span className={styles.flexCenter}>
<span
className={classNames({
[styles.iconContainer]: true,
[styles.iconContainerHasRightChildren]: children,
})}
>
{icon}
</span>
{children}
<span
className={classNames({
[styles.iconContainer]: true,
[styles.iconContainerHasLeftChildren]: children,
})}
>
{iconRight}
</span>
</span>
);
};
const withLoader = (
children: React.ReactNode,
{
isLoading,
theme = 'primary',
}: { isLoading?: boolean; theme?: 'primary' | 'secondary' | 'tertiary' },
): React.ReactNode => {
if (!isLoading) {
return children;
}
return (
<span className={styles.loaderContainer}>
<span className={styles.absoluteCenter}>
<LoaderDots theme={loaderDotsTheme[theme]} size="small" />
</span>
<span className={styles.hidden}>{children}</span>
</span>
);
};
const withFlexWrapper = (
children: React.ReactNode,
{ size }: { size?: 'small' | 'large' },
): React.ReactNode => (
<span
className={classNames({
[styles.flexWrapper]: true,
[styles.flexWrapperSizeSmall]: size === 'small',
[styles.flexWrapperSizeLarge]: size === 'large',
})}
>
{children}
</span>
);
const Themed = React.forwardRef<HTMLButtonElement | HTMLAnchorElement, PropTypes>(
(
{
children,
isDisabled = false,
isLoading = false,
icon,
iconRight,
type = 'button',
to,
shouldOpenInNewTab = false,
target,
onClick,
onMouseEnter,
onMouseOver,
onFocus,
onMouseLeave,
onBlur,
accessibilityLabel,
size = 'large',
theme = 'primary',
width = 'auto',
dataTestId,
dataTest,
}: PropTypes,
ref,
): JSX.Element => {
warning(
children || accessibilityLabel || ((icon || iconRight) && children),
'The prop `accessibilityLabel` must be provided to the button or link when `icon` or `iconRight` is provided but `children` is not. This helps users on screen readers navigate our content.',
);
return (
<InputRowContext.Consumer>
{({ isWithinInputRow, isFirstInputRowChild, isLastInputRowChild }): JSX.Element => {
const isAnchor = !!to;
const anchorProps = getAnchorProps({
isDisabled,
shouldOpenInNewTab,
to,
onClick,
target,
});
const buttonProps = getButtonProps({
onClick,
type,
onMouseEnter,
onMouseOver,
onFocus,
onMouseLeave,
onBlur,
});
const className = classNames({
[styles.themedButton]: true,
[styles.themedButtonRoundedBordersLeft]:
isFirstInputRowChild || !isWithinInputRow,
[styles.themedButtonRoundedBordersRight]:
isLastInputRowChild || !isWithinInputRow,
[styles.themedButtonHasNoRightBorder]:
isWithinInputRow && !isLastInputRowChild,
[styles.themedButtonThemePrimary]: theme === 'primary',
[styles.themedButtonThemeTertiary]: theme === 'tertiary',
[styles.themedButtonThemeSecondary]: theme === 'secondary',
[styles.themedButtonThemeCaution]: theme === 'caution',
[styles.themedButtonThemeSolid]: theme === 'solid',
[styles.themedButtonThemePopoverPrimary]: theme === 'popover-primary',
[styles.themedButtonThemePopoverSecondary]: theme === 'popover-secondary',
[styles.themedButtonWidthAuto]: width === 'auto' && !isWithinInputRow,
[styles.themedButtonWidthFull]: width === 'full' || isWithinInputRow,
[styles.themedButtonWidthFullBelowSmall]:
width === 'full-below-small' && !isWithinInputRow,
});
const commonProps = {
disabled: isLoading || isDisabled,
className,
'aria-label': accessibilityLabel,
'data-testid': dataTestId,
'data-test': dataTest,
};
// There are more themes here than are valid for use with `LoaderDots`, so restrict the type
// by overwriting any invalid themes as `undefined`.
const restrictedTheme =
theme === 'primary' || theme === 'secondary' || theme === 'tertiary'
? theme
: undefined;
const newChildren = withFlexWrapper(
withLoader(withIcon(children, { icon, iconRight }), {
isLoading,
theme: restrictedTheme,
}),
{ size },
);
if (isAnchor) {
return (
<a
{...commonProps}
{...anchorProps}
ref={ref as React.Ref<HTMLAnchorElement>}
>
{newChildren}
</a>
);
}
return (
// Disable this rule, even though `buttonProps.type` can never be undefined,
// because the rule itself is broken and shows a false positive.
// https://github.com/yannickcr/eslint-plugin-react/issues/1555
// eslint-disable-next-line react/button-has-type
<button
{...commonProps}
{...buttonProps}
ref={ref as React.Ref<HTMLButtonElement>}
>
{newChildren}
</button>
);
}}
</InputRowContext.Consumer>
);
},
);
interface PropTypes {
/**
* Contents displayed within the button.
*/
children?: React.ReactNode;
/**
* Boolean determining whether the button is disabled. When `true` it will appear visually
* "greyed out" and not respond to interaction.
*/
isDisabled?: boolean;
/**
* Boolean determining whether the button is in a loading state. When `true` the text will
* we replaced with a loading animation and interaction will be disabled.
*/
isLoading?: boolean;
/**
* Icon from [Thumbprint Icons](/icons/) to render left within the button.
*/
icon?: React.ReactNode;
/**
* Icon from [Thumbprint Icons](/icons/) to render right within the button.
*/
iconRight?: React.ReactNode;
/**
* Button's on type `submit` will submit a form when used within a `form`
* element.
*/
type?: 'button' | 'submit';
/**
* Page to navigate to when the anchor is clicked.
*/
to?: string;
/**
* @deprecated
* Opens the URL in a new tab when clicked.
* This is deprecated. Use `target="_blank"` instead.
*/
shouldOpenInNewTab?: boolean;
/**
* The anchor `target` attribute. Set this to `_blank` to open in a new tab, or to an arbitrary
* string to open the link in an `<iframe>` with the same `name`.
*/
target?: string;
/**
* Function that will run when the button is clicked on.
*/
onClick?: (event: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement, MouseEvent>) => void;
/**
* Function that runs when the user hovers on the button.
*/
onMouseEnter?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
/**
* Function that runs when the user hovers on the button. Unlike `onMouseEnter`, `onMouseOver`
* fires each time a child element receives focus.
*/
onMouseOver?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
/**
* Function that runs when the user hovers away from the button.
*/
onMouseLeave?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
/**
* Function that runs when the button receives focus.
*/
onFocus?: (event: React.FocusEvent<HTMLButtonElement>) => void;
/**
* Function that runs when the button loses focus.
*/
onBlur?: (event: React.FocusEvent<HTMLButtonElement>) => void;
/**
* Description of the button’s content. It is required if the button has an icon and no
* descriptive text.
*/
accessibilityLabel?: string;
/**
* Controls the button's background, text, and border color.
*/
theme?:
| 'primary'
| 'secondary'
| 'tertiary'
| 'caution'
| 'solid'
| 'popover-primary'
| 'popover-secondary';
/**
* Changes the button's `line-height`, `padding`, `border-radius`, and `font-size`.
*/
size?: 'small' | 'large';
/**
* `Button` components are as wide as the content that is passed in. The `full` option will
* expand the width to `100%` on all screens. `full-below-small` will expand the width to 100%
* on devices smaller than [our `small` breakpoint](/tokens/#section-breakpoint).
*/
width?: 'auto' | 'full' | 'full-below-small';
/**
* A selector hook into the React component for use in automated testing environments.
*/
dataTestId?: string;
/**
* A selector hook into the React component for use in automated testing environments.
* @deprecated Deprecated in favor of the `dataTestId` prop
*/
dataTest?: string;
}
export default Themed; | the_stack |
import { createCanvas, loadImage, resizeImage } from "./tools";
import { Translator } from "../i18n";
export interface TopGraphicOptions {
champion?: riot.Champion;
title: string;
players: {
championAvatar?: string;
place: number;
username: string;
avatar: string;
score: number;
level: number;
}[];
}
const SPLASH_OFFSETS: { [key: string]: number } = {
Blitzcrank: 30,
Anivia: 80,
Kassadin: 40,
Hecarim: -40,
Velkoz: 100,
Zac: 230,
Soraka: -40,
Jayce: 30,
Alistar: 120,
Leona: -60,
Rammus: 100,
Lissandra: -40,
Darius: -45,
Trundle: 30,
TahmKench: 100,
Kaisa: -40,
Katarina: 110,
Aatrox: 30,
Gnar: 220,
Lucian: 100,
Ezreal: 30,
Khazix: 90,
Draven: 30,
Heimerdinger: 140,
Yasuo: 50,
MissFortune: 40,
Kindred: 70,
Fiddlesticks: 50,
Garen: 60,
Shen: -60,
Annie: 60,
Quinn: 40,
Ziggs: 150,
DrMundo: 40,
Kennen: 50,
Rumble: 15,
Malphite: 200,
Illaoi: -85,
Sona: -30,
Zed: -30,
Rengar: 70,
Urgot: -80,
Maokai: 110,
Olaf: 60,
Braum: -30,
Lulu: 90,
Sejuani: -30,
Amumu: 50,
Ornn: 80,
Tristana: 30,
Yorick: -60,
Sion: -20,
Nunu: 320,
Rakan: -40,
KogMaw: 250,
Xayah: 40,
Volibear: -70,
Corki: 30,
Veigar: 40,
Ivern: 20,
Skarner: 130,
Teemo: 40,
Akali: -30,
Orianna: -50,
Nocturne: 140,
Irelia: -70,
Diana: 70,
Cassiopeia: 50,
Twitch: 100,
Galio: -70,
RekSai: 260,
Udyr: 180,
Warwick: 240,
Kayn: 170,
Karthus: -60,
Ryze: 80,
Taric: -80,
MasterYi: 60,
Pyke: 70,
Talon: 60,
Camille: -30,
Graves: -90,
Janna: 30,
Fiora: -70,
Caitlyn: -20,
Sivir: 60,
Chogath: 70,
Xerath: -80,
Varus: -70,
Swain: -80,
Gangplank: 30,
};
/**
* The following function is generated from an instance of [html2canvas](https://github.com/niklasvh/html2canvas) on
* a fake canvas object to retrieve the operations needed to render the specified image statically.
*/
export async function generateChampionTopGraphic(t: Translator, options: TopGraphicOptions): Promise<Buffer> {
const splash = await t.staticData.getChampionSplash(options.champion!);
const icon = await t.staticData.getChampionIcon(options.champion!);
// Step 1: Load all images.
await Promise.all([
// Title and header images.
loadImage(splash),
loadImage(icon),
// Player avatars
...options.players.map(x => loadImage(x.avatar)),
// All the level icons we need.
...[...new Set(options.players.map(x => x.level))].map(x => loadImage(`./assets/level${x}.png`))
]);
// Figure out the width our numbers need to be.
const placeWidth = Math.max(...options.players.map(x => x.place)).toString().length * 8;
// Step 2: Render canvas. All the code that follows was automatically generated.
const canvas = createCanvas(399, 299);
const ctx = canvas.getContext("2d");
ctx.textBaseline = "bottom";
ctx.fillStyle = "rgb(255,255,255)";
ctx.fillRect(0, 0, 399, 299);
ctx.globalAlpha = 1;
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(399, 0);
ctx.lineTo(399, 50);
ctx.lineTo(0, 50);
ctx.closePath();
ctx.clip();
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(399, 0);
ctx.lineTo(399, 50);
ctx.lineTo(0, 50);
ctx.closePath();
ctx.fillStyle = ctx.createPattern(resizeImage(await loadImage(splash), {
"width": 399,
"height": 235.45925925925926,
yOffset: SPLASH_OFFSETS[options.champion!.id] || 0
}), "repeat");
ctx.translate(0, -503);
ctx.fill();
ctx.translate(0, 503);
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.fillStyle = "rgb(47,49,54)";
ctx.fill();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.save();
ctx.beginPath();
ctx.moveTo(5, 69);
ctx.bezierCurveTo(5, 62.92486775186127, 9.924867751861271, 58, 16, 58);
ctx.lineTo(16, 58);
ctx.bezierCurveTo(22.07513224813873, 58, 27, 62.92486775186127, 27, 69);
ctx.lineTo(27, 69);
ctx.bezierCurveTo(27, 75.07513224813873, 22.07513224813873, 80, 16, 80);
ctx.lineTo(16, 80);
ctx.bezierCurveTo(9.924867751861271, 80, 5, 75.07513224813873, 5, 69);
ctx.closePath();
ctx.clip();
ctx.drawImage(await loadImage(icon), 0, 0, 120, 120, 5, 58, 22, 22);
ctx.restore();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.font = "bold 13px \"Noto Sans KR\", \"Noto Sans Small\", sans-serif";
ctx.fillStyle = "#ffffff";
ctx.fillText(options.title, 32, 78);
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.font = "11px \"Noto Sans KR\", \"Noto Sans\", sans-serif";
ctx.fillStyle = "#898991";
ctx.fillText(t.command_top_graphic_name, 5, 102.5);
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.font = "11px \"Noto Sans KR\", \"Noto Sans\", sans-serif";
ctx.fillStyle = "#898991";
ctx.fillText(t.command_top_graphic_score, 294, 102.5);
ctx.restore();
for (let i = 0; i < options.players.length; i++) {
const player = options.players[i];
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.font = "13px \"Noto Sans KR\", \"Noto Sans Small\", sans-serif";
ctx.fillStyle = "rgba(255, 255, 255, 0.6)";
ctx.fillText(player.place.toString(), 5, 127 + 24 * i);
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.save();
ctx.beginPath();
ctx.arc(19 + placeWidth, 118 + 24 * i, 8, 0, Math.PI * 2, true);
ctx.closePath();
ctx.clip();
ctx.drawImage(await loadImage(player.avatar), 0, 0, 16, 16, 11 + placeWidth, 110 + 24 * i, 16, 16);
ctx.restore();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.beginPath();
ctx.moveTo(41, 106 + 24 * i);
ctx.lineTo(261, 106 + 24 * i);
ctx.lineTo(261, 130 + 24 * i);
ctx.lineTo(41, 130 + 24 * i);
ctx.closePath();
ctx.clip();
ctx.font = "13px \"Noto Sans KR\", \"Noto Sans\", sans-serif";
ctx.fillStyle = "#ffffff";
ctx.fillText(player.username, 33 + placeWidth, 127 + 24 * i);
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.save();
ctx.beginPath();
ctx.moveTo(294, 110 + 24 * i);
ctx.lineTo(310, 110 + 24 * i);
ctx.lineTo(310, 126 + 24 * i);
ctx.lineTo(294, 126 + 24 * i);
ctx.closePath();
ctx.clip();
ctx.drawImage(await loadImage(`./assets/level${player.level}.png`), 0, 0, 105, 103, 294, 110 + 24 * i, 16, 16);
ctx.restore();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50 + 24 * i);
ctx.lineTo(399, 50 + 24 * i);
ctx.lineTo(399, 300 + 24 * i);
ctx.lineTo(0, 300 + 24 * i);
ctx.closePath();
ctx.clip();
ctx.font = "bold 13px \"Noto Sans KR\", \"Noto Sans Small\", sans-serif";
ctx.fillStyle = "#ffffff";
ctx.fillText(t.number(player.score), 314, 127 + 24 * i);
ctx.restore();
}
return canvas.toBuffer("image/jpeg", { quality: 1 });
}
/**
* The following function is generated from an instance of [html2canvas](https://github.com/niklasvh/html2canvas) on
* a fake canvas object to retrieve the operations needed to render the specified image statically.
*/
export async function generateGlobalTopGraphic(t: Translator, options: TopGraphicOptions): Promise<Buffer> {
// Step 1: Load all images.
await Promise.all([
// Title and header images.
loadImage("https://i.imgur.com/XVKpmRV.png"),
// Player avatars
...options.players.map(x => loadImage(x.avatar)),
// Champion images
...options.players.map(x => loadImage(x.championAvatar!)),
// All the level icons we need.
...[...new Set(options.players.map(x => x.level))].map(x => loadImage(`./assets/level${x}.png`))
]);
// Figure out the width our numbers need to be.
const placeWidth = Math.max(...options.players.map(x => x.place)).toString().length * 8;
// Step 2: Render canvas. All the code that follows was automatically generated.
const canvas = createCanvas(399, 299);
const ctx = canvas.getContext("2d");
ctx.textBaseline = "bottom";
ctx.fillStyle = "rgb(255,255,255)";
ctx.fillRect(0, 0, 399, 299);
ctx.globalAlpha = 1;
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(399, 0);
ctx.lineTo(399, 50);
ctx.lineTo(0, 50);
ctx.closePath();
ctx.clip();
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(399, 0);
ctx.lineTo(399, 50);
ctx.lineTo(0, 50);
ctx.closePath();
ctx.fillStyle = ctx.createPattern(resizeImage(await loadImage("https://i.imgur.com/XVKpmRV.png"), {
"width": 399,
"height": 235.45925925925926
}), "repeat");
ctx.translate(0, -503);
ctx.fill();
ctx.translate(0, 503);
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.fillStyle = "rgb(47,49,54)";
ctx.fill();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.font = "bold 13px \"Noto Sans KR\", \"Noto Sans Small\", sans-serif";
ctx.fillStyle = "#ffffff";
ctx.fillText(options.title, 5, 78);
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.font = "11px \"Noto Sans KR\", \"Noto Sans\", sans-serif";
ctx.fillStyle = "#898991";
ctx.fillText(t.command_top_graphic_name, 5, 102.5);
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.font = "11px \"Noto Sans KR\", \"Noto Sans\", sans-serif";
ctx.fillStyle = "#898991";
ctx.fillText(t.command_top_graphic_score, 273, 102.5);
ctx.restore();
for (let i = 0; i < options.players.length; i++) {
const player = options.players[i];
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.font = "13px \"Noto Sans KR\", \"Noto Sans Small\", sans-serif";
ctx.fillStyle = "rgba(255, 255, 255, 0.6)";
ctx.fillText(player.place.toString(), 5, 127 + 24 * i);
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.save();
ctx.beginPath();
ctx.arc(19 + placeWidth, 118 + 24 * i, 8, 0, Math.PI * 2, true);
ctx.closePath();
ctx.clip();
ctx.drawImage(await loadImage(player.avatar), 0, 0, 16, 16, 11 + placeWidth, 110 + 24 * i, 16, 16);
ctx.restore();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.beginPath();
ctx.moveTo(41, 106 + 24 * i);
ctx.lineTo(261, 106 + 24 * i);
ctx.lineTo(261, 130 + 24 * i);
ctx.lineTo(41, 130 + 24 * i);
ctx.closePath();
ctx.clip();
ctx.font = "13px \"Noto Sans KR\", \"Noto Sans\", sans-serif";
ctx.fillStyle = "#ffffff";
ctx.fillText(player.username, 33 + placeWidth, 127 + 24 * i);
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(399, 50);
ctx.lineTo(399, 300);
ctx.lineTo(0, 300);
ctx.closePath();
ctx.clip();
ctx.save();
ctx.beginPath();
ctx.arc(281, 118 + 24 * i, 8, 0, Math.PI * 2, true);
ctx.closePath();
ctx.clip();
ctx.drawImage(await loadImage(player.championAvatar!), 0, 0, 120, 120, 273, 110 + 24 * i, 16, 16);
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(294, 110 + 24 * i);
ctx.lineTo(310, 110 + 24 * i);
ctx.lineTo(310, 126 + 24 * i);
ctx.lineTo(294, 126 + 24 * i);
ctx.closePath();
ctx.clip();
ctx.drawImage(await loadImage(`./assets/level${player.level}.png`), 0, 0, 105, 103, 294, 110 + 24 * i, 16, 16);
ctx.restore();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 50 + 24 * i);
ctx.lineTo(399, 50 + 24 * i);
ctx.lineTo(399, 300 + 24 * i);
ctx.lineTo(0, 300 + 24 * i);
ctx.closePath();
ctx.clip();
ctx.font = "bold 13px \"Noto Sans KR\", \"Noto Sans Small\", sans-serif";
ctx.fillStyle = "#ffffff";
ctx.fillText(t.number(player.score), 314, 127 + 24 * i);
ctx.restore();
}
return canvas.toBuffer("image/jpeg", { quality: 1 });
} | the_stack |
import * as React from 'react';
import * as CopyToClipboard from 'react-copy-to-clipboard';
import * as CSSModules from 'react-css-modules';
import * as TetherComponent from 'react-tether';
import {InlineData} from 'vega-lite/build/src/data';
import {isDiscrete, isFieldDef} from 'vega-lite/build/src/fielddef';
import {SortField, SortOrder} from 'vega-lite/build/src/sort';
import {TopLevelFacetedUnitSpec} from 'vega-lite/build/src/spec';
import {BOOKMARK_MODIFY_NOTE, BookmarkAction} from '../../actions/bookmark';
import {LogAction} from '../../actions/log';
import {ActionHandler} from '../../actions/redux-action';
import {ResultAction} from '../../actions/result';
import {ShelfAction, SPEC_LOAD} from '../../actions/shelf';
import {SHELF_PREVIEW_DISABLE, SHELF_PREVIEW_SPEC, ShelfPreviewAction} from '../../actions/shelf-preview';
import {PLOT_HOVER_MIN_DURATION} from '../../constants';
import {Bookmark} from '../../models/bookmark';
import {PlotFieldInfo, ResultPlot} from '../../models/result';
import {ShelfFilter, toTransforms} from '../../models/shelf/filter';
import {Field} from '../field/index';
import {Logger} from '../util/util.logger';
import {VegaLite} from '../vega-lite/index';
import {BookmarkButton} from './bookmarkbutton';
import * as styles from './plot.scss';
export interface PlotProps extends ActionHandler<
ShelfAction | BookmarkAction | ShelfPreviewAction | ResultAction | LogAction
> {
data: InlineData;
filters: ShelfFilter[];
fieldInfos?: PlotFieldInfo[];
isPlotListItem?: boolean;
showBookmarkButton?: boolean;
showSpecifyButton?: boolean;
onSort?: (channel: 'x' | 'y', sort: SortField<string> | SortOrder) => void;
spec: TopLevelFacetedUnitSpec;
bookmark?: Bookmark;
// specified when it's in the modal
// so we can close the modal when the specify button is clicked.
closeModal?: () => void;
}
export interface PlotState {
hovered: boolean;
preview: boolean;
copiedPopupIsOpened: boolean;
}
export class PlotBase extends React.PureComponent<PlotProps, PlotState> {
private hoverTimeoutId: number;
private previewTimeoutId: number;
private vegaLiteWrapper: HTMLElement;
private plotLogger: Logger;
constructor(props: PlotProps) {
super(props);
this.state = {
hovered: false,
preview: false,
copiedPopupIsOpened: false
};
// Bind - https://facebook.github.io/react/docs/handling-events.html
this.handleTextChange = this.handleTextChange.bind(this);
this.onMouseEnter = this.onMouseEnter.bind(this);
this.onMouseLeave = this.onMouseLeave.bind(this);
this.onPreviewMouseEnter = this.onPreviewMouseEnter.bind(this);
this.onPreviewMouseLeave = this.onPreviewMouseLeave.bind(this);
this.onSpecify = this.onSpecify.bind(this);
this.onSort = this.onSort.bind(this);
this.plotLogger = new Logger(props.handleAction);
}
public componentDidUpdate(prevProps: PlotProps, prevState: PlotState) {
// We have to check this here since we do not know if it is vertically overflown
// during render time.
if (!this.isVerticallyOverFlown(this.vegaLiteWrapper) && this.state.hovered) {
// add a padding similar to .plot
this.vegaLiteWrapper.style.paddingRight = '11px';
} else {
// reset state otherwise, so we clean up what we add in the case above.
delete this.vegaLiteWrapper.style.paddingRight;
}
}
public render() {
const {isPlotListItem, onSort, showBookmarkButton, showSpecifyButton, spec, data} = this.props;
let notesDiv;
const specKey = JSON.stringify(spec);
if (this.props.bookmark.dict[specKey]) {
notesDiv = (
<textarea
styleName='note'
placeholder={'notes'}
value={this.props.bookmark.dict[specKey].note}
onChange={this.handleTextChange}
/>
);
}
return (
<div styleName={isPlotListItem ? 'plot-list-item-group' : 'plot-group'}>
<div styleName="plot-info">
<div styleName="command-toolbox">
{onSort && this.renderSortButton('x')}
{onSort && this.renderSortButton('y')}
{showBookmarkButton && this.renderBookmarkButton()}
{showSpecifyButton && this.renderSpecifyButton()}
<span styleName='command'>
<TetherComponent
attachment='bottom left'
offset='0px 30px'
>
{this.renderCopySpecButton()}
{this.state.copiedPopupIsOpened && <span styleName='copied'>copied</span>}
</TetherComponent>
</span>
</div>
<span
onMouseEnter={this.onPreviewMouseEnter}
onMouseLeave={this.onPreviewMouseLeave}
>
{this.renderFields()}
</span>
</div>
<div
ref={this.vegaLiteWrapperRefHandler}
styleName={this.state.hovered ? 'plot-scroll' : 'plot'}
className="persist-scroll"
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
>
<VegaLite spec={spec} logger={this.plotLogger} data={data}/>
</div>
{notesDiv}
</div>
);
}
public componentWillUnmount() {
this.clearHoverTimeout();
}
private renderFields() {
const {fieldInfos} = this.props;
if (fieldInfos) {
return fieldInfos.map(fieldInfo => {
const {fieldDef, isEnumeratedWildcardField} = fieldInfo;
return (
<div styleName="plot-field-info" key={JSON.stringify(fieldDef)}>
<Field
fieldDef={fieldDef}
caretShow={false}
draggable={false}
isEnumeratedWildcardField={isEnumeratedWildcardField}
isPill={false}
/>
</div>
);
});
}
return undefined;
}
private clearHoverTimeout() {
if (this.hoverTimeoutId) {
clearTimeout(this.hoverTimeoutId);
this.hoverTimeoutId = undefined;
}
}
private clearPreviewTimeout() {
if (this.previewTimeoutId) {
clearTimeout(this.previewTimeoutId);
this.previewTimeoutId = undefined;
}
}
private onMouseEnter() {
this.hoverTimeoutId = window.setTimeout(
() => {
// TODO log action
this.setState({hovered: true});
this.hoverTimeoutId = undefined;
},
PLOT_HOVER_MIN_DURATION
);
}
private onMouseLeave() {
this.clearHoverTimeout();
if (this.state.hovered) {
this.setState({hovered: false});
}
}
private onSort(channel: 'x' | 'y') {
// TODO: really take `sort` as input instead of toggling like this
const {spec, onSort} = this.props;
const channelDef = spec.encoding[channel];
if (isFieldDef(channelDef)) {
const sort = channelDef.sort === 'descending' ? undefined : 'descending';
onSort(channel, sort);
}
}
private onSpecify() {
if (this.props.closeModal) {
this.props.closeModal();
}
this.onPreviewMouseLeave();
const {handleAction, spec} = this.props;
handleAction({
type: SPEC_LOAD,
payload: {spec, keepWildcardMark: true}
});
}
private onPreviewMouseEnter() {
this.previewTimeoutId = window.setTimeout(
() => {
const {handleAction, spec} = this.props;
this.setState({preview: true});
handleAction({
type: SHELF_PREVIEW_SPEC,
payload: {spec}
});
this.previewTimeoutId = undefined;
},
PLOT_HOVER_MIN_DURATION
);
}
private onPreviewMouseLeave() {
this.clearPreviewTimeout();
if (this.state.preview) {
this.setState({preview: false});
const {handleAction} = this.props;
handleAction({type: SHELF_PREVIEW_DISABLE});
}
}
private renderSortButton(channel: 'x' | 'y') {
const {spec} = this.props;
const channelDef = spec.encoding[channel];
if (isFieldDef(channelDef) && isDiscrete(channelDef)) {
return <i
title='Sort'
className="fa fa-sort-alpha-asc"
styleName={channel === 'x' ? 'sort-x-command' : 'command'}
onClick={this.onSort.bind(this, channel)}
/>;
}
return undefined;
}
private renderSpecifyButton() {
return <i
title='Specify'
className="fa fa-server"
styleName="specify-command"
onClick={this.onSpecify}
onMouseEnter={this.onPreviewMouseEnter}
onMouseLeave={this.onPreviewMouseLeave}
/>;
}
private renderBookmarkButton() {
const plot: ResultPlot = {
fieldInfos: this.props.fieldInfos,
spec: this.specWithFilter
};
return (
<BookmarkButton
bookmark={this.props.bookmark}
plot={plot}
handleAction={this.props.handleAction}
/>
);
}
private handleTextChange(event: any) {
const {handleAction} = this.props;
handleAction({
type: BOOKMARK_MODIFY_NOTE,
payload: {
note: event.target.value,
spec: this.props.spec
}
});
}
private get specWithFilter() {
const {spec, filters} = this.props;
const transform = (spec.transform || []).concat(toTransforms(filters));
return {
...spec,
...(transform.length > 0 ? {transform} : {})
};
}
private renderCopySpecButton() {
// TODO: spec would only contain NamedData, but not the actual data.
// Need to augment spec.data
// TODO instead of pre-generating a text for the copy button, which
// takes a lot of memory for each plot
// Can only generate the text only when the button is clicked?
return (
<CopyToClipboard
onCopy={this.copied.bind(this)}
text={JSON.stringify(this.specWithFilter, null, 2)}>
<i title='Copy' className='fa fa-clipboard' />
</CopyToClipboard>
);
}
private copied() {
this.setState({
copiedPopupIsOpened: true
});
window.setTimeout(() => {
this.setState({
copiedPopupIsOpened: false
});
}, 1000);
}
private isVerticallyOverFlown(element: HTMLElement) {
return element.scrollHeight > element.clientHeight;
}
private vegaLiteWrapperRefHandler = (ref: any) => {
this.vegaLiteWrapper = ref;
}
}
export const Plot = CSSModules(PlotBase, styles); | the_stack |
import Ajv from 'ajv';
import {
File,
Location,
MutationScoreThresholds,
StrykerOptions,
strykerCoreSchema,
WarningOptions,
Mutant,
MutantTestCoverage,
MutantResult,
MutantCoverage,
schema,
MutantStatus,
} from '@stryker-mutator/api/core';
import { Logger } from '@stryker-mutator/api/logging';
import { Reporter, SourceFile } from '@stryker-mutator/api/report';
import { calculateMutationTestMetrics, Metrics, MetricsResult, MutationTestMetricsResult } from 'mutation-testing-metrics';
import sinon from 'sinon';
import { Injector } from 'typed-inject';
import { PluginResolver } from '@stryker-mutator/api/plugin';
import {
MutantRunOptions,
DryRunOptions,
DryRunStatus,
TestRunner,
SuccessTestResult,
FailedTestResult,
SkippedTestResult,
CompleteDryRunResult,
ErrorDryRunResult,
TimeoutDryRunResult,
KilledMutantRunResult,
SurvivedMutantRunResult,
MutantRunStatus,
TimeoutMutantRunResult,
ErrorMutantRunResult,
TestStatus,
TestResult,
} from '@stryker-mutator/api/test-runner';
import { Checker, CheckResult, CheckStatus, FailedCheckResult } from '@stryker-mutator/api/check';
const ajv = new Ajv({ useDefaults: true, strict: false });
/**
* This validator will fill in the defaults of stryker options as registered in the schema.
*/
function strykerOptionsValidator(overrides: Partial<StrykerOptions>): asserts overrides is StrykerOptions {
const ajvValidator = ajv.compile(strykerCoreSchema);
if (!ajvValidator(overrides)) {
throw new Error('Unknown stryker options ' + ajv.errorsText(ajvValidator.errors));
}
}
/**
* A 1x1 png base64 encoded
*/
export const PNG_BASE64_ENCODED =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAAMSURBVBhXY/j//z8ABf4C/qc1gYQAAAAASUVORK5CYII=';
/**
* Use this factory method to create deep test data
* @param defaults
*/
function factoryMethod<T>(defaultsFactory: () => T) {
return (overrides?: Partial<T>): T => Object.assign({}, defaultsFactory(), overrides);
}
export const location = factoryMethod<Location>(() => ({ start: { line: 0, column: 0 }, end: { line: 0, column: 0 } }));
export function pluginResolver(): sinon.SinonStubbedInstance<PluginResolver> {
return {
resolve: sinon.stub<any>(),
resolveAll: sinon.stub<any>(),
resolveValidationSchemaContributions: sinon.stub(),
};
}
export const warningOptions = factoryMethod<WarningOptions>(() => ({
unknownOptions: true,
preprocessorErrors: true,
unserializableOptions: true,
}));
export const killedMutantResult = (overrides?: Partial<Omit<MutantResult, 'status'>>): MutantResult =>
mutantResult({ ...overrides, status: MutantStatus.Killed, killedBy: ['45'], testsCompleted: 2 });
export const timeoutMutantResult = (overrides?: Partial<Omit<MutantResult, 'status'>>): MutantResult =>
mutantResult({ ...overrides, status: MutantStatus.Timeout, statusReason: 'expected error' });
export const runtimeErrorMutantResult = (overrides?: Partial<Omit<MutantResult, 'status'>>): MutantResult =>
mutantResult({ ...overrides, status: MutantStatus.RuntimeError, statusReason: 'expected error' });
export const ignoredMutantResult = (overrides?: Partial<Omit<MutantResult, 'status'>>): MutantResult =>
mutantResult({ ...overrides, status: MutantStatus.Ignored, statusReason: 'Ignored by "fooMutator" in excludedMutations' });
export const noCoverageMutantResult = (overrides?: Partial<Omit<MutantResult, 'status'>>): MutantResult =>
mutantResult({ ...overrides, status: MutantStatus.NoCoverage });
export const mutantResult = factoryMethod<MutantResult>(() => ({
id: '256',
location: location(),
mutatorName: '',
range: [0, 0],
replacement: '',
fileName: 'file.js',
status: MutantStatus.Survived,
coveredBy: ['1', '2'],
testsCompleted: 2,
static: false,
}));
export const mutationTestReportSchemaMutantResult = factoryMethod<schema.MutantResult>(() => ({
id: '256',
location: location(),
mutatedLines: '',
mutatorName: '',
originalLines: '',
range: [0, 0],
replacement: '',
sourceFilePath: '',
status: MutantStatus.Killed,
testsRan: [''],
}));
export const mutationTestReportSchemaFileResult = factoryMethod<schema.FileResult>(() => ({
language: 'javascript',
mutants: [mutationTestReportSchemaMutantResult()],
source: 'export function add (a, b) { return a + b; }',
}));
export const mutationTestReportSchemaTestFile = factoryMethod<schema.TestFile>(() => ({
tests: [],
source: '',
}));
export const mutationTestReportSchemaTestDefinition = factoryMethod<schema.TestDefinition>(() => ({
id: '4',
name: 'foo should be bar',
}));
export const mutationTestReportSchemaMutationTestResult = factoryMethod<schema.MutationTestResult>(() => ({
files: {
'fileA.js': mutationTestReportSchemaFileResult(),
},
schemaVersion: '1',
thresholds: {
high: 81,
low: 19,
},
}));
export const mutationTestMetricsResult = factoryMethod<MutationTestMetricsResult>(() =>
calculateMutationTestMetrics(mutationTestReportSchemaMutationTestResult())
);
export const mutant = factoryMethod<Mutant>(() => ({
id: '42',
fileName: 'file',
mutatorName: 'foobarMutator',
location: location(),
replacement: 'replacement',
}));
export const metrics = factoryMethod<Metrics>(() => ({
compileErrors: 0,
killed: 0,
mutationScore: 0,
mutationScoreBasedOnCoveredCode: 0,
noCoverage: 0,
runtimeErrors: 0,
survived: 0,
timeout: 0,
ignored: 0,
totalCovered: 0,
totalDetected: 0,
totalInvalid: 0,
totalMutants: 0,
totalUndetected: 0,
totalValid: 0,
}));
export const metricsResult = factoryMethod<MetricsResult>(() => ({
childResults: [],
metrics: metrics({}),
name: '',
}));
export function logger(): sinon.SinonStubbedInstance<Logger> {
return {
debug: sinon.stub(),
error: sinon.stub(),
fatal: sinon.stub(),
info: sinon.stub(),
isDebugEnabled: sinon.stub(),
isErrorEnabled: sinon.stub(),
isFatalEnabled: sinon.stub(),
isInfoEnabled: sinon.stub(),
isTraceEnabled: sinon.stub(),
isWarnEnabled: sinon.stub(),
trace: sinon.stub(),
warn: sinon.stub(),
};
}
export function testRunner(): sinon.SinonStubbedInstance<Required<TestRunner>> {
return {
init: sinon.stub(),
dryRun: sinon.stub(),
mutantRun: sinon.stub(),
dispose: sinon.stub(),
};
}
export function checker(): sinon.SinonStubbedInstance<Checker> {
return {
check: sinon.stub(),
init: sinon.stub(),
};
}
export const checkResult = factoryMethod<CheckResult>(() => ({
status: CheckStatus.Passed,
}));
export const failedCheckResult = factoryMethod<FailedCheckResult>(() => ({
status: CheckStatus.CompileError,
reason: 'Cannot call "foo" of undefined',
}));
export const testResult = factoryMethod<TestResult>(() => ({
id: 'spec1',
name: 'name',
status: TestStatus.Success,
timeSpentMs: 10,
}));
export const successTestResult = factoryMethod<SuccessTestResult>(() => ({
id: 'spec1',
name: 'foo should be bar',
status: TestStatus.Success,
timeSpentMs: 32,
}));
export const failedTestResult = factoryMethod<FailedTestResult>(() => ({
id: 'spec2',
name: 'foo should be bar',
status: TestStatus.Failed,
timeSpentMs: 32,
failureMessage: 'foo was baz',
}));
export const skippedTestResult = factoryMethod<SkippedTestResult>(() => ({
id: 'spec31',
status: TestStatus.Skipped,
timeSpentMs: 0,
name: 'qux should be quux',
}));
export const mutantRunOptions = factoryMethod<MutantRunOptions>(() => ({
activeMutant: mutant(),
timeout: 2000,
sandboxFileName: '.stryker-tmp/sandbox123/file',
disableBail: false,
}));
export const dryRunOptions = factoryMethod<DryRunOptions>(() => ({
coverageAnalysis: 'off',
timeout: 2000,
disableBail: false,
}));
export const completeDryRunResult = factoryMethod<CompleteDryRunResult>(() => ({
status: DryRunStatus.Complete,
tests: [],
}));
export const mutantCoverage = factoryMethod<MutantCoverage>(() => ({
perTest: {},
static: {},
}));
export const errorDryRunResult = factoryMethod<ErrorDryRunResult>(() => ({
status: DryRunStatus.Error,
errorMessage: 'example error',
}));
export const timeoutDryRunResult = factoryMethod<TimeoutDryRunResult>(() => ({
status: DryRunStatus.Timeout,
}));
export const killedMutantRunResult = factoryMethod<KilledMutantRunResult>(() => ({
status: MutantRunStatus.Killed,
killedBy: ['spec1'],
failureMessage: 'foo should be bar',
nrOfTests: 1,
}));
export const survivedMutantRunResult = factoryMethod<SurvivedMutantRunResult>(() => ({
status: MutantRunStatus.Survived,
nrOfTests: 2,
}));
export const timeoutMutantRunResult = factoryMethod<TimeoutMutantRunResult>(() => ({
status: MutantRunStatus.Timeout,
}));
export const errorMutantRunResult = factoryMethod<ErrorMutantRunResult>(() => ({
status: MutantRunStatus.Error,
errorMessage: 'Cannot find foo of undefined',
}));
export const mutationScoreThresholds = factoryMethod<MutationScoreThresholds>(() => ({
break: null,
high: 80,
low: 60,
}));
export const strykerOptions = factoryMethod<StrykerOptions>(() => {
const options: Partial<StrykerOptions> = {};
strykerOptionsValidator(options);
return options;
});
export const strykerWithPluginOptions = <T>(pluginOptions: T): StrykerOptions & T => {
return { ...strykerOptions(), ...pluginOptions };
};
export const ALL_REPORTER_EVENTS: Array<keyof Reporter> = [
'onSourceFileRead',
'onAllSourceFilesRead',
'onAllMutantsMatchedWithTests',
'onMutantTested',
'onAllMutantsTested',
'onMutationTestReportReady',
'wrapUp',
];
export function reporter(name = 'fooReporter'): sinon.SinonStubbedInstance<Required<Reporter>> {
const reporters = { name } as any;
ALL_REPORTER_EVENTS.forEach((event) => (reporters[event] = sinon.stub()));
return reporters;
}
export const mutantTestCoverage = factoryMethod<MutantTestCoverage>(() => ({
coveredBy: undefined,
fileName: '',
id: '1',
mutatorName: '',
static: false,
replacement: '',
location: location(),
estimatedNetTime: 42,
}));
export function injector(): sinon.SinonStubbedInstance<Injector> {
const injectorMock: sinon.SinonStubbedInstance<Injector> = {
dispose: sinon.stub(),
injectClass: sinon.stub<any>(),
injectFunction: sinon.stub<any>(),
provideClass: sinon.stub<any>(),
provideFactory: sinon.stub<any>(),
provideValue: sinon.stub<any>(),
resolve: sinon.stub(),
};
injectorMock.provideClass.returnsThis();
injectorMock.provideFactory.returnsThis();
injectorMock.provideValue.returnsThis();
return injectorMock;
}
export function file(): File {
return new File('', '');
}
export const sourceFile = factoryMethod<SourceFile>(() => ({
content: 'foo.bar()',
path: 'foo.js',
}));
export function fileNotFoundError(): NodeJS.ErrnoException {
return createErrnoException('ENOENT');
}
export function fileAlreadyExistsError(): NodeJS.ErrnoException {
return createErrnoException('EEXIST');
}
export function createIsDirError(): NodeJS.ErrnoException {
return createErrnoException('EISDIR');
}
function createErrnoException(errorCode: string) {
const fileNotFoundErrorInstance: NodeJS.ErrnoException = new Error('');
fileNotFoundErrorInstance.code = errorCode;
return fileNotFoundErrorInstance;
} | the_stack |
import {
keys,
makeAutoObservable,
observable,
ObservableMap,
runInAction,
toJS,
values,
} from 'mobx';
import * as POOL from 'types/generated/trader_pb';
import Big from 'big.js';
import debounce from 'lodash/debounce';
import { hex } from 'util/strings';
import { Store } from 'store';
import { Lease, Order } from 'store/models';
import { OrderType, Tier } from 'store/models/order';
export default class OrderStore {
private _store: Store;
/** the collection of orders */
orders: ObservableMap<string, Order> = observable.map();
/** the collection of leases */
leases: ObservableMap<string, Lease> = observable.map();
/** that amount earned from sold leases */
earnedSats = Big(0);
/** the amount paid from purchased leases */
paidSats = Big(0);
constructor(store: Store) {
makeAutoObservable(this, {}, { deep: false, autoBind: true });
this._store = store;
}
/** all orders sorted by created date descending */
get sortedOrders() {
const { field, descending } = this._store.settingsStore.orderSort;
const orders = values(this.orders)
.slice()
.sort((a, b) => Order.compare(a, b, field));
return descending ? orders.reverse() : orders;
}
/** the number of pending orders for the active account */
get pendingOrdersCount() {
return this.sortedOrders.filter(o => o.isPending).length;
}
/** the leases grouped by orderNonce */
get leasesByNonce() {
const leases: Record<string, Lease[]> = {};
values(this.leases)
.slice()
.forEach(lease => {
if (!leases[lease.orderNonce]) {
// create a new array with the lease
leases[lease.orderNonce] = [lease];
} else {
// append the lease to the existing array
leases[lease.orderNonce] = [...leases[lease.orderNonce], lease];
}
});
return leases;
}
/**
* queries the POOL api to fetch the list of orders and stores them
* in the state
*/
async fetchOrders() {
this._store.log.info('fetching orders');
try {
const { asksList, bidsList } = await this._store.api.pool.listOrders();
runInAction(() => {
const serverIds: string[] = [];
asksList.forEach(({ details, leaseDurationBlocks }) => {
const poolOrder = details as POOL.Order.AsObject;
// update existing orders or create new ones in state. using this
// approach instead of overwriting the array will cause fewer state
// mutations, resulting in better react rendering performance
const nonce = hex(poolOrder.orderNonce);
const order = this.orders.get(nonce) || new Order(this._store);
order.update(poolOrder, OrderType.Ask, leaseDurationBlocks);
this.orders.set(nonce, order);
serverIds.push(nonce);
});
bidsList.forEach(({ details, leaseDurationBlocks, minNodeTier }) => {
const poolOrder = details as POOL.Order.AsObject;
// update existing orders or create new ones in state. using this
// approach instead of overwriting the array will cause fewer state
// mutations, resulting in better react rendering performance
const nonce = hex(poolOrder.orderNonce);
const order = this.orders.get(nonce) || new Order(this._store);
order.update(poolOrder, OrderType.Bid, leaseDurationBlocks, minNodeTier);
this.orders.set(nonce, order);
serverIds.push(nonce);
});
// remove any orders in state that are not in the API response
const localIds = Object.keys(this.orders);
localIds
.filter(id => !serverIds.includes(id))
.forEach(id => this.orders.delete(id));
this._store.log.info('updated orderStore.orders', toJS(this.orders));
});
// fetch leases whenever orders are fetched
await this.fetchLeases();
} catch (error) {
this._store.appView.handleError(error, 'Unable to fetch orders');
}
}
/** fetch orders at most once every 2 seconds when using this func */
fetchOrdersThrottled = debounce(this.fetchOrders, 2000);
/**
* queries the POOL api to fetch the list of leases and stores them
* in the state
*/
async fetchLeases() {
this._store.log.info('fetching leases');
try {
const {
leasesList,
totalAmtEarnedSat,
totalAmtPaidSat,
} = await this._store.api.pool.listLeases();
runInAction(() => {
this.earnedSats = Big(totalAmtEarnedSat);
this.paidSats = Big(totalAmtPaidSat);
leasesList.forEach(poolLease => {
// update existing leases or create new ones in state. using this
// approach instead of overwriting the array will cause fewer state
// mutations, resulting in better react rendering performance
const channelPoint = Lease.channelPointToString(poolLease.channelPoint);
const existing = this.leases.get(channelPoint);
if (existing) {
existing.update(poolLease);
} else {
this.leases.set(channelPoint, new Lease(poolLease));
}
});
// remove any leases in state that are not in the API response
const serverIds = leasesList.map(a => Lease.channelPointToString(a.channelPoint));
const localIds = keys(this.leases).map(key => String(key));
localIds
.filter(id => !serverIds.includes(id))
.forEach(id => this.leases.delete(id));
this._store.log.info('updated orderStore.leases', toJS(this.leases));
});
} catch (error) {
this._store.appView.handleError(error, 'Unable to fetch leases');
}
}
/** fetch leases at most once every 2 seconds when using this func */
fetchLeasesThrottled = debounce(this.fetchLeases, 2000);
/**
* Requests a fee quote for an order
* @param amount the amount of the order
* @param rateFixed the per block fixed rate
* @param duration the number of blocks to keep the channel open for
* @param minUnitsMatch the minimum number of units required to match this order
* @param maxBatchFeeRate the maximum batch fee rate to allowed as sats per vByte
*/
async quoteOrder(
amount: Big,
rateFixed: number,
duration: number,
minUnitsMatch: number,
maxBatchFeeRate: number,
): Promise<POOL.QuoteOrderResponse.AsObject> {
try {
this._store.log.info(`quoting an order for ${amount}sats`, {
rateFixed,
duration,
minUnitsMatch,
maxBatchFeeRate,
});
const res = await this._store.api.pool.quoteOrder(
amount,
rateFixed,
duration,
minUnitsMatch,
maxBatchFeeRate,
);
return res;
} catch (error) {
this._store.appView.handleError(error, 'Unable to estimate order fees');
return {
ratePerBlock: rateFixed,
ratePercent: 0,
totalExecutionFeeSat: '0',
totalPremiumSat: '0',
worstCaseChainFeeSat: '0',
};
}
}
/**
* Submits an order to the market
* @param type the type of order (bid or ask)
* @param amount the amount of the order
* @param rateFixed the per block fixed rate
* @param duration the number of blocks to keep the channel open for
* @param minUnitsMatch the minimum number of units required to match this order
* @param maxBatchFeeRate the maximum batch fee rate to allowed as sats per vByte
* @param minNodeTier the minimum node tier (only for Bid orders)
*/
async submitOrder(
type: OrderType,
amount: Big,
rateFixed: number,
duration: number,
minUnitsMatch: number,
maxBatchFeeRate: number,
minNodeTier?: Tier,
) {
try {
const traderKey = this._store.accountStore.activeAccount.traderKey;
this._store.log.info(`submitting ${type} order for ${amount}sats`, {
rateFixed,
duration,
minUnitsMatch,
maxBatchFeeRate,
minNodeTier,
});
const { acceptedOrderNonce, invalidOrder } = await this._store.api.pool.submitOrder(
traderKey,
type,
amount,
rateFixed,
duration,
minUnitsMatch,
maxBatchFeeRate,
minNodeTier,
);
// fetch all orders to update the store's state
await this.fetchOrders();
// also update account balances in the store
await this._store.accountStore.fetchAccounts();
if (invalidOrder) {
this._store.log.error('invalid order', invalidOrder);
throw new Error(invalidOrder.failString);
}
return hex(acceptedOrderNonce);
} catch (error) {
this._store.appView.handleError(error, 'Unable to submit the order');
}
}
/**
* Cancels a pending order
* @param nonce the order's nonce value
*/
async cancelOrder(nonce: string) {
try {
const traderKey = this._store.accountStore.activeAccount.traderKey;
this._store.log.info(`cancelling order with nonce ${nonce} for ${traderKey}`);
await this._store.api.pool.cancelOrder(nonce);
// fetch all orders to update the store's state
await this.fetchOrders();
// also update account balances in the store
await this._store.accountStore.fetchAccounts();
} catch (error) {
this._store.appView.handleError(error, 'Unable to cancel the order');
}
}
/**
* Cancels all open orders for the active account
*/
async cancelAllOrders() {
const traderKey = this._store.accountStore.activeAccount.traderKey;
this._store.log.info(`cancelling all pending orders for ${traderKey}`);
const orders = this.sortedOrders.filter(o => o.isPending);
for (const order of orders) {
this._store.log.info(`cancelling order with nonce ${order.nonce} for ${traderKey}`);
await this._store.api.pool.cancelOrder(order.nonce);
}
// fetch all orders to update the store's state
await this.fetchOrders();
// also update account balances in the store
await this._store.accountStore.fetchAccounts();
}
/** exports the list of leases to CSV file */
exportLeases() {
this._store.log.info('exporting Leases to a CSV file');
const leases = values(this.leases).slice();
this._store.csv.export('leases', Lease.csvColumns, toJS(leases));
}
} | the_stack |
import { throwError as observableThrowError, Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpErrorResponse } from '@angular/common/http';
import { ScanMetadata } from '../model/ScanMetadata';
import { MarkerSlice } from '../model/MarkerSlice';
import { API_URL } from '../utils/ApiUrl';
import { environment } from '../../environments/environment';
import { ScanSelection } from '../model/selections/ScanSelection';
import { SliceSelection } from '../model/selections/SliceSelection';
import { MedTaggerWebSocket } from './websocket.service';
import { concat, delay, map, mergeAll, retryWhen, take } from 'rxjs/operators';
import { of } from 'rxjs/internal/observable/of';
import { from } from 'rxjs/internal/observable/from';
import { defer } from 'rxjs/internal/observable/defer';
import { isUndefined } from 'util';
import { PredefinedBrushLabelElement } from '../model/PredefinedBrushLabelElement';
interface ScanResponse {
scan_id: string;
status: string;
number_of_slices: number;
width: number;
height: number;
predefined_label_id: string;
}
interface NewScanResponse {
scan_id: string;
}
@Injectable()
export class ScanService {
websocket: MedTaggerWebSocket;
delay = 5000;
retries = 5;
constructor(private http: HttpClient, private socket: MedTaggerWebSocket) {
this.websocket = socket;
}
sendSelection(scanId: string, taskKey: string, selection: ScanSelection<SliceSelection>, labelingTime: number,
comment: string): Promise<Response> {
console.log('ScanService | send3dSelection | sending 3D selection:',
selection, `for scanId: ${scanId}`, `with labeling time: ${labelingTime}`);
const payload = selection.toJSON();
payload['labeling_time'] = labelingTime;
payload['comment'] = comment;
const form = new FormData();
form.append('label', JSON.stringify(payload));
const additionalData = selection.getAdditionalData();
for (const key of Object.keys(additionalData)) {
const value = additionalData[key];
form.append(key, value, key);
}
return new Promise((resolve, reject) => {
this.http.post(environment.API_URL + API_URL.SCANS + `/${scanId}/${taskKey}/label`, form).toPromise()
.then((response: Response) => {
console.log('ScanService | send3dSelection | response: ', response);
resolve(response);
}).catch((error: Response) => {
console.log('ScanService | send3dSelection | error: ', error);
reject(error);
});
});
}
public sendPredefinedLabel(scanId: string, taskKey: string, label: Object, additionalData: Object): Promise<Response> {
const form = new FormData();
form.append('label', JSON.stringify(label));
for (const key of Object.keys(additionalData)) {
const value = additionalData[key];
form.append(key, value, key);
}
return new Promise((resolve, reject) => {
this.http.post(environment.API_URL + API_URL.SCANS + `/${scanId}/${taskKey}/label?is_predefined=true`, form).toPromise()
.then((response: Response) => {
console.log('ScanService | sendPredefinedLabel | response: ', response);
resolve(response);
}).catch((error: Response) => {
console.log('ScanService | sendPredefinedLabel | error: ', error);
reject(error);
});
});
}
public getRandomScan(taskKey: string): Promise<ScanMetadata> {
if (isUndefined(taskKey)) {
return Promise.reject('ScanService | getRandomScan | error: Task key is undefined!');
}
return new Promise((resolve, reject) => {
let params = new HttpParams();
params = params.set('task', taskKey);
this.http.get<ScanResponse>(environment.API_URL + API_URL.SCANS + '/random', {params: params})
.subscribe(
(response: ScanResponse) => {
console.log('ScanService | getRandomScan | response: ', response);
resolve(new ScanMetadata(response.scan_id, response.status, response.number_of_slices,
response.width, response.height, response.predefined_label_id));
},
(error: Error) => {
console.log('ScanService | getRandomScan | error: ', error);
reject(error);
},
() => {
console.log('ScanService | getRandomScan | done');
});
});
}
getScanForScanId(scanId: string): Promise<ScanMetadata> {
return new Promise((resolve, reject) => {
this.http.get<ScanResponse>(environment.API_URL + API_URL.SCANS + '/' + scanId).toPromise().then(
(response: ScanResponse) => {
console.log('ScanService | getScanForScanId | response: ', response);
resolve(new ScanMetadata(response.scan_id, response.status, response.number_of_slices,
response.width, response.height, undefined));
},
(error: Error) => {
console.log('ScanService | getScanForScanId | error: ', error);
reject(error);
}
);
});
}
slicesObservable(): Observable<MarkerSlice> {
return this.websocket.fromEvent<any>('slice').pipe(
map((slice: { scan_id: string, index: number, last_in_batch: number, image: ArrayBuffer }) => {
return new MarkerSlice(slice.scan_id, slice.index, slice.last_in_batch, slice.image);
})
);
}
predefinedBrushLabelElementsObservable(): Observable<PredefinedBrushLabelElement> {
return this.websocket.fromEvent<any>('brush_labels').pipe(
map((label: { scan_id: string, tag_key: string, index: number, image: ArrayBuffer }) => {
return new PredefinedBrushLabelElement(label.scan_id, label.tag_key, label.index, label.image);
})
);
}
requestSlices(scanId: string, taskKey: string, begin: number, count: number, reversed: boolean = false): void {
console.log('ScanService | requestSlices | (begin, count, reversed):', begin, count, reversed);
const request = {
scan_id: scanId,
task_key: taskKey,
begin: begin,
count: count,
reversed: reversed,
};
// Send request immediately
this.websocket.emit('request_slices', request);
// And request it again in case of WebSocket failure
this.websocket.on('reconnect', () => {
this.websocket.emit('request_slices', request);
});
}
createNewScan(dataset: string, numberOfSlices: number): Promise<string> {
return new Promise((resolve, reject) => {
const payload = {
dataset: dataset,
number_of_slices: numberOfSlices,
};
let retryAttempt = 0;
this.http.post<NewScanResponse>(environment.API_URL + API_URL.SCANS, payload)
.pipe(
retryWhen((error: Observable<HttpErrorResponse>) => {
return error.pipe(
map((scanRequestError: HttpErrorResponse) => {
console.warn('Retrying request for creating new Scan (attempt: ' + (++retryAttempt) + ').');
return of(scanRequestError.status);
}),
delay(this.delay), // Let's give it a try after 5 seconds
take(this.retries), // Let's give it 5 retries (each after 5 seconds)
concat(observableThrowError({error: 'Cannot create new Scan.'}))
);
})
).toPromise().then(
(response: NewScanResponse) => {
resolve(response.scan_id);
},
(error: HttpErrorResponse) => {
reject(error);
}
);
});
}
uploadSlices(scanId: string, files: File[]): Observable<any> {
const CONCURRENT_API_CALLS = 5;
return from(files).pipe(
map((file: File) => {
console.log('Uploading file...', file.name);
let retryAttempt = 0;
const form = new FormData();
form.append('image', file, file.name);
return defer(
() => this.http.post(environment.API_URL + API_URL.SCANS + '/' + scanId + '/slices', form)
.pipe(
retryWhen((error: Observable<HttpErrorResponse>) => {
return error.pipe(
map((uploadRequestError: HttpErrorResponse) => {
console.warn('Retrying request for uploading a single Slice ('
+ file.name + ', attempt: ' + (++retryAttempt) + ').');
return of(uploadRequestError.status);
}),
delay(this.delay), // Let's give it a try after 5 seconds
take(this.retries), // Let's give it 5 retries (each after 5 seconds)
concat(observableThrowError({error: 'Cannot upload Slice ' + file.name}))
);
})
)
);
}),
mergeAll(CONCURRENT_API_CALLS)
);
}
skipScan(scanId: string): Promise<Response> {
return new Promise((resolve, reject) => {
this.http.post(environment.API_URL + API_URL.SCANS + `/${scanId}/skip`, {}).toPromise().then((response: Response) => {
console.log('ScanService | skipScan | response: ', response);
resolve(response);
}).catch((error: Response) => {
console.log('ScanService | skipScan | error: ', error);
reject(error);
});
});
}
} | the_stack |
import { sleep } from "@atomist/automation-client/lib/internal/util/poll";
import { guid } from "@atomist/automation-client/lib/internal/util/string";
import { GitCommandGitProject } from "@atomist/automation-client/lib/project/git/GitCommandGitProject";
import { GitProject } from "@atomist/automation-client/lib/project/git/GitProject";
import * as k8s from "@kubernetes/client-node";
import * as fs from "fs-extra";
import * as stringify from "json-stringify-safe";
import * as _ from "lodash";
import * as os from "os";
import * as path from "path";
import * as request from "request";
import { Writable } from "stream";
import { Merge } from "ts-essentials";
import { minimalClone } from "../../api-helper/goal/minimalClone";
import { goalData, sdmGoalTimeout } from "../../api-helper/goal/sdmGoal";
import { RepoContext } from "../../api/context/SdmContext";
import { ExecuteGoalResult } from "../../api/goal/ExecuteGoalResult";
import { ExecuteGoal, GoalProjectListenerEvent, GoalProjectListenerRegistration } from "../../api/goal/GoalInvocation";
import { GoalWithFulfillment, ImplementationRegistration } from "../../api/goal/GoalWithFulfillment";
import { SdmGoalEvent } from "../../api/goal/SdmGoalEvent";
import { GoalScheduler } from "../../api/goal/support/GoalScheduler";
import { ServiceRegistrationGoalDataKey } from "../../api/registration/ServiceRegistration";
import { CacheEntry, CacheOutputGoalDataKey, cachePut, cacheRestore } from "../../core/goal/cache/goalCaching";
import {
Container,
ContainerInput,
ContainerOutput,
ContainerProjectHome,
ContainerRegistration,
ContainerRegistrationGoalDataKey,
ContainerScheduler,
GoalContainer,
GoalContainerVolume,
} from "../../core/goal/container/container";
import { prepareSecrets } from "../../core/goal/container/provider";
import { containerEnvVars, prepareInputAndOutput, processResult } from "../../core/goal/container/util";
import { toArray } from "../../core/util/misc/array";
import { ProgressLog } from "../../spi/log/ProgressLog";
import { SdmGoalState } from "../../typings/types";
import { loadKubeConfig } from "./kubernetes/config";
import { k8sJobEnv, KubernetesGoalScheduler, readNamespace } from "./scheduler/KubernetesGoalScheduler";
import { K8sServiceRegistrationType, K8sServiceSpec } from "./scheduler/service";
import { k8sErrMsg } from "./support/error";
// tslint:disable:max-file-line-count
/** Merge of base and Kubernetes goal container interfaces. */
export type K8sGoalContainer = Merge<GoalContainer, k8s.V1Container> & Pick<GoalContainer, "name" | "image">;
/** Merge of base and Kubernetes goal container volume interfaces. */
export type K8sGoalContainerVolume = Merge<k8s.V1Volume, GoalContainerVolume>;
/**
* Function signature for callback that can modify and return the
* [[ContainerRegistration]] object.
*/
export type K8sContainerSpecCallback = (
r: K8sContainerRegistration,
p: GitProject,
g: Container,
e: SdmGoalEvent,
ctx: RepoContext,
) => Promise<Omit<K8sContainerRegistration, "callback">>;
/**
* Additional options for Kubernetes implementation of container goals.
*/
export interface K8sContainerRegistration extends ContainerRegistration {
/**
* Replace generic containers in [[ContainerRegistration]] with
* Kubernetes containers.
*
* Containers to run for this goal. The goal result is based on
* the exit status of the first element of the `containers` array.
* The other containers are considered "sidecar" containers
* provided functionality that the main container needs to
* function. If not set, the working directory of the first
* container is set to [[ContainerProjectHome]], which contains
* the project upon which the goal should operate. If
* `workingDir` is set, it is not changed. If `workingDir` is set
* to the empty string, the `workingDir` property is deleted from
* the main container spec, meaning the container default working
* directory will be used.
*/
containers: K8sGoalContainer[];
/**
* Replace generic callback in [[ContainerRegistration]] with
* Kubernetes-specific callback.
*/
callback?: K8sContainerSpecCallback;
/**
* Init containers to run for this goal. Any containers provided
* here will run after the one inserted by the SDM to manage the
* cloned repository.
*/
initContainers?: k8s.V1Container[];
/**
* Replace generic volumes in [[ContainerRegistration]] with
* Kubernetes volumes available to mount in containers.
*/
volumes?: K8sGoalContainerVolume[];
}
/**
* Container scheduler to use when running in Kubernetes.
*/
export const k8sContainerScheduler: ContainerScheduler = (goal, registration: K8sContainerRegistration) => {
goal.addFulfillment({
goalExecutor: executeK8sJob(),
...(registration as ImplementationRegistration),
});
goal.addFulfillmentCallback({
goal,
callback: k8sFulfillmentCallback(goal, registration),
});
};
/**
* Container scheduler to use when running in Google Cloud Functions.
*/
export const k8sSkillContainerScheduler: ContainerScheduler = (goal, registration: K8sContainerRegistration) => {
goal.addFulfillment({
goalExecutor: executeK8sJob(),
...(registration as ImplementationRegistration),
});
};
/**
* Add Kubernetes job scheduling information to SDM goal event data
* for use by the [[KubernetesGoalScheduler]].
*/
export function k8sFulfillmentCallback(
goal: Container,
registration: K8sContainerRegistration,
): (sge: SdmGoalEvent, rc: RepoContext) => Promise<SdmGoalEvent> {
// tslint:disable-next-line:cyclomatic-complexity
return async (goalEvent, repoContext) => {
let spec: K8sContainerRegistration = _.cloneDeep(registration);
if (registration.callback) {
spec = await repoContext.configuration.sdm.projectLoader.doWithProject(
{
...repoContext,
readOnly: true,
cloneOptions: minimalClone(goalEvent.push, { detachHead: true }),
},
async p => {
return {
...spec,
...((await registration.callback(_.cloneDeep(registration), p, goal, goalEvent, repoContext)) ||
{}),
};
},
);
}
if (!spec.containers || spec.containers.length < 1) {
throw new Error("No containers defined in K8sGoalContainerSpec");
}
// Preserve the container registration in the goal data before it gets munged with internals
let data = goalData(goalEvent);
let newData: any = {};
delete spec.callback;
_.set<any>(newData, ContainerRegistrationGoalDataKey, spec);
goalEvent.data = JSON.stringify(_.merge(data, newData));
if (spec.containers[0].workingDir === "") {
delete spec.containers[0].workingDir;
} else if (!spec.containers[0].workingDir) {
spec.containers[0].workingDir = ContainerProjectHome;
}
const goalSchedulers: GoalScheduler[] = toArray(repoContext.configuration.sdm.goalScheduler) || [];
const k8sScheduler = goalSchedulers.find(
gs => gs instanceof KubernetesGoalScheduler,
) as KubernetesGoalScheduler;
if (!k8sScheduler) {
throw new Error("Failed to find KubernetesGoalScheduler in goal schedulers");
}
if (!k8sScheduler.podSpec) {
throw new Error("KubernetesGoalScheduler has no podSpec defined");
}
const containerEnvs = await containerEnvVars(goalEvent, repoContext);
const projectVolume = `project-${guid().split("-")[0]}`;
const inputVolume = `input-${guid().split("-")[0]}`;
const outputVolume = `output-${guid().split("-")[0]}`;
const ioVolumes = [
{
name: projectVolume,
emptyDir: {},
},
{
name: inputVolume,
emptyDir: {},
},
{
name: outputVolume,
emptyDir: {},
},
];
const ioVolumeMounts = [
{
mountPath: ContainerProjectHome,
name: projectVolume,
},
{
mountPath: ContainerInput,
name: inputVolume,
},
{
mountPath: ContainerOutput,
name: outputVolume,
},
];
const copyContainer = _.cloneDeep(k8sScheduler.podSpec.containers[0]);
delete copyContainer.lifecycle;
delete copyContainer.livenessProbe;
delete copyContainer.readinessProbe;
copyContainer.name = `container-goal-init-${guid().split("-")[0]}`;
copyContainer.env = [
...(copyContainer.env || []),
...k8sJobEnv(k8sScheduler.podSpec, goalEvent, repoContext.context as any),
...containerEnvs,
{
name: "ATOMIST_ISOLATED_GOAL_INIT",
value: "true",
},
{
name: "ATOMIST_CONFIG",
value: JSON.stringify({
cluster: {
enabled: false,
},
ws: {
enabled: false,
},
}),
},
];
spec.initContainers = spec.initContainers || [];
const parameters = JSON.parse((goalEvent as any).parameters || "{}");
const secrets = await prepareSecrets(
_.merge({}, registration.containers[0], parameters["@atomist/sdm/secrets"] || {}),
repoContext,
);
delete spec.containers[0].secrets;
[...spec.containers, ...spec.initContainers].forEach(c => {
c.env = [...(secrets.env || []), ...containerEnvs, ...(c.env || [])];
});
if (!!secrets?.files) {
for (const file of secrets.files) {
const fileName = path.basename(file.mountPath);
const dirname = path.dirname(file.mountPath);
let secretName = `secret-${guid().split("-")[0]}`;
const vm = (copyContainer.volumeMounts || []).find(m => m.mountPath === dirname);
if (!!vm) {
secretName = vm.name;
} else {
copyContainer.volumeMounts = [
...(copyContainer.volumeMounts || []),
{
mountPath: dirname,
name: secretName,
},
];
spec.volumes = [
...(spec.volumes || []),
{
name: secretName,
emptyDir: {},
} as any,
];
}
[...spec.containers, ...spec.initContainers].forEach((c: k8s.V1Container) => {
c.volumeMounts = [
...(c.volumeMounts || []),
{
mountPath: file.mountPath,
name: secretName,
subPath: fileName,
},
];
});
}
}
spec.initContainers = [copyContainer, ...spec.initContainers];
const serviceSpec: { type: string; spec: K8sServiceSpec } = {
type: K8sServiceRegistrationType.K8sService,
spec: {
container: spec.containers,
initContainer: spec.initContainers,
volume: [...ioVolumes, ...(spec.volumes || [])],
volumeMount: ioVolumeMounts,
},
};
// Store k8s service registration in goal data
data = goalData(goalEvent);
newData = {};
_.set<any>(newData, `${ServiceRegistrationGoalDataKey}.${registration.name}`, serviceSpec);
goalEvent.data = JSON.stringify(_.merge(data, newData));
return goalEvent;
};
}
/**
* Get container registration from goal event data, use
* [[k8sFulfillmentcallback]] to get a goal event schedulable by a
* [[KubernetesGoalScheduler]], then schedule the goal using that
* scheduler.
*/
export const scheduleK8sJob: ExecuteGoal = async gi => {
const { goalEvent } = gi;
const { uniqueName } = goalEvent;
const data = goalData(goalEvent);
const containerReg: K8sContainerRegistration = data["@atomist/sdm/container"];
if (!containerReg) {
throw new Error(`Goal ${uniqueName} event data has no container spec: ${goalEvent.data}`);
}
const goalSchedulers: GoalScheduler[] = toArray(gi.configuration.sdm.goalScheduler) || [];
const k8sScheduler = goalSchedulers.find(gs => gs instanceof KubernetesGoalScheduler) as KubernetesGoalScheduler;
if (!k8sScheduler) {
throw new Error(`Failed to find KubernetesGoalScheduler in goal schedulers: ${stringify(goalSchedulers)}`);
}
// the k8sFulfillmentCallback may already have been called, so wipe it out
delete data[ServiceRegistrationGoalDataKey];
goalEvent.data = JSON.stringify(data);
try {
const schedulableGoalEvent = await k8sFulfillmentCallback(gi.goal as Container, containerReg)(goalEvent, gi);
const scheduleResult = await k8sScheduler.schedule({ ...gi, goalEvent: schedulableGoalEvent });
if (scheduleResult.code) {
return {
...scheduleResult,
message: `Failed to schedule container goal ${uniqueName}: ${scheduleResult.message}`,
};
}
schedulableGoalEvent.state = SdmGoalState.in_process;
return schedulableGoalEvent;
} catch (e) {
const message = `Failed to schedule container goal ${uniqueName} as Kubernetes job: ${e.message}`;
gi.progressLog.write(message);
return { code: 1, message };
}
};
/** Container information useful the various functions. */
interface K8sContainer {
/** Kubernetes configuration to use when creating API clients */
config: k8s.KubeConfig;
/** Name of container in pod */
name: string;
/** Pod name */
pod: string;
/** Pod namespace */
ns: string;
/** Log */
log: ProgressLog;
}
/**
* Wait for first container to exit and stream its logs to the
* progress log.
*/
export function executeK8sJob(): ExecuteGoal {
// tslint:disable-next-line:cyclomatic-complexity
return async gi => {
const { goalEvent, progressLog, configuration, id, credentials } = gi;
const projectDir = process.env.ATOMIST_PROJECT_DIR || ContainerProjectHome;
const inputDir = process.env.ATOMIST_INPUT_DIR || ContainerInput;
const outputDir = process.env.ATOMIST_OUTPUT_DIR || ContainerOutput;
const data = goalData(goalEvent);
if (!data[ContainerRegistrationGoalDataKey]) {
throw new Error("Failed to read k8s ContainerRegistration from goal data");
}
if (!data[ContainerRegistrationGoalDataKey]) {
throw new Error(
`Goal ${gi.goal.uniqueName} has no Kubernetes container registration: ${gi.goalEvent.data}`,
);
}
const registration: K8sContainerRegistration = data[ContainerRegistrationGoalDataKey];
if (process.env.ATOMIST_ISOLATED_GOAL_INIT === "true") {
return configuration.sdm.projectLoader.doWithProject(
{
...gi,
readOnly: false,
cloneDir: projectDir,
cloneOptions: minimalClone(goalEvent.push, { detachHead: true }),
},
async () => {
try {
await prepareInputAndOutput(inputDir, outputDir, gi);
} catch (e) {
const message = `Failed to prepare input and output for goal ${goalEvent.name}: ${e.message}`;
progressLog.write(message);
return { code: 1, message };
}
const secrets = await prepareSecrets(
_.merge({}, registration.containers[0], (gi.parameters || {})["@atomist/sdm/secrets"] || {}),
gi,
);
if (!!secrets?.files) {
for (const file of secrets.files) {
await fs.writeFile(file.mountPath, file.value);
}
}
goalEvent.state = SdmGoalState.in_process;
return goalEvent;
},
);
}
let containerName: string = _.get(registration, "containers[0].name");
if (!containerName) {
const msg = `Failed to get main container name from goal registration: ${stringify(registration)}`;
progressLog.write(msg);
let svcSpec: K8sServiceSpec;
try {
svcSpec = _.get(data, `${ServiceRegistrationGoalDataKey}.${registration.name}.spec`);
} catch (e) {
const message = `Failed to parse Kubernetes spec from goal data '${goalEvent.data}': ${e.message}`;
progressLog.write(message);
return { code: 1, message };
}
containerName = _.get(svcSpec, "container[1].name");
if (!containerName) {
const message = `Failed to get main container name from either goal registration or data: '${goalEvent.data}'`;
progressLog.write(message);
return { code: 1, message };
}
}
const ns = await readNamespace();
const podName = os.hostname();
let kc: k8s.KubeConfig;
try {
kc = loadKubeConfig();
} catch (e) {
const message = `Failed to load Kubernetes configuration: ${e.message}`;
progressLog.write(message);
return { code: 1, message };
}
const container: K8sContainer = {
config: kc,
name: containerName,
pod: podName,
ns,
log: progressLog,
};
try {
await containerStarted(container);
} catch (e) {
const message = `Failed to determine if container started: ${e.message}`;
progressLog.write(message);
return { code: 1, message };
}
const status = { code: 0, message: `Container '${containerName}' completed successfully` };
try {
const timeout = sdmGoalTimeout(configuration);
const podStatus = await containerWatch(container, timeout);
progressLog.write(`Container '${containerName}' exited: ${stringify(podStatus)}`);
} catch (e) {
const message = `Container '${containerName}' failed: ${e.message}`;
progressLog.write(message);
status.code++;
status.message = message;
}
const outputFile = path.join(outputDir, "result.json");
let outputResult: ExecuteGoalResult;
if (status.code === 0 && (await fs.pathExists(outputFile))) {
try {
outputResult = await processResult(await fs.readJson(outputFile), gi);
} catch (e) {
const message = `Failed to read output from container: ${e.message}`;
progressLog.write(message);
status.code++;
status.message += ` but f${message.slice(1)}`;
}
}
const cacheEntriesToPut: CacheEntry[] = [
...(registration.output || []),
...((gi.parameters || {})[CacheOutputGoalDataKey] || []),
];
if (cacheEntriesToPut.length > 0) {
try {
const project = GitCommandGitProject.fromBaseDir(id, projectDir, credentials, async () => {});
const cp = cachePut({
entries: cacheEntriesToPut.map(e => {
// Prevent the type on the entry to get passed along when goal actually failed
if (status.code !== 0) {
return {
classifier: e.classifier,
pattern: e.pattern,
};
} else {
return e;
}
}),
});
await cp.listener(project, gi, GoalProjectListenerEvent.after);
} catch (e) {
const message = `Failed to put cache output from container: ${e.message}`;
progressLog.write(message);
status.code++;
status.message += ` but f${message.slice(1)}`;
}
}
return outputResult || status;
};
}
/**
* If running as isolated goal, use [[executeK8sJob]] to execute the
* goal. Otherwise, schedule the goal execution as a Kubernetes job
* using [[scheduleK8sJob]].
*/
const containerExecutor: ExecuteGoal = gi =>
process.env.ATOMIST_ISOLATED_GOAL ? executeK8sJob()(gi) : scheduleK8sJob(gi);
/**
* Restore cache input entries before fulfilling goal.
*/
const containerFulfillerCacheRestore: GoalProjectListenerRegistration = {
name: "cache restore",
events: [GoalProjectListenerEvent.before],
listener: async (project, gi) => {
const data = goalData(gi.goalEvent);
if (!data[ContainerRegistrationGoalDataKey]) {
throw new Error(
`Goal ${gi.goal.uniqueName} has no Kubernetes container registration: ${gi.goalEvent.data}`,
);
}
const registration: K8sContainerRegistration = data[ContainerRegistrationGoalDataKey];
if (registration.input && registration.input.length > 0) {
try {
const cp = cacheRestore({ entries: registration.input });
return cp.listener(project, gi, GoalProjectListenerEvent.before);
} catch (e) {
const message = `Failed to restore cache input to container for goal ${gi.goal.uniqueName}: ${e.message}`;
gi.progressLog.write(message);
return { code: 1, message };
}
} else {
return { code: 0, message: "No container input cache entries to restore" };
}
},
};
/** Deterministic name for Kubernetes container goal fulfiller. */
export const K8sContainerFulfillerName = "Kubernetes Container Goal Fulfiller";
/**
* Goal that fulfills requested container goals by scheduling them as
* Kubernetes jobs.
*/
export function k8sContainerFulfiller(): GoalWithFulfillment {
return new GoalWithFulfillment({
displayName: K8sContainerFulfillerName,
uniqueName: K8sContainerFulfillerName,
})
.with({
goalExecutor: containerExecutor,
name: `${K8sContainerFulfillerName} Executor`,
})
.withProjectListener(containerFulfillerCacheRestore);
}
/**
* Wait for container in pod to start, return when it does.
*
* @param container Information about container to check
* @param attempts Maximum number of attempts, waiting 500 ms between
*/
async function containerStarted(container: K8sContainer, attempts: number = 240): Promise<void> {
let core: k8s.CoreV1Api;
try {
core = container.config.makeApiClient(k8s.CoreV1Api);
} catch (e) {
e.message = `Failed to create Kubernetes core API client: ${e.message}`;
container.log.write(e.message);
throw e;
}
const sleepTime = 500; // ms
for (let i = 0; i < attempts; i++) {
await sleep(sleepTime);
let pod: k8s.V1Pod;
try {
pod = (await core.readNamespacedPod(container.pod, container.ns)).body;
} catch (e) {
container.log.write(`Reading pod ${container.ns}/${container.pod} failed: ${k8sErrMsg(e)}`);
continue;
}
const containerStatus = pod.status?.containerStatuses?.find(c => c.name === container.name);
if (containerStatus && (!!containerStatus.state?.running?.startedAt || !!containerStatus.state?.terminated)) {
const message = `Container '${container.name}' started`;
container.log.write(message);
return;
}
}
const errMsg = `Container '${container.name}' failed to start within ${attempts * sleepTime} ms`;
container.log.write(errMsg);
throw new Error(errMsg);
}
/** Items used to in watching main container and its logs. */
interface ContainerDetritus {
logStream?: Writable;
logRequest?: request.Request;
watcher?: any;
timeout?: NodeJS.Timeout;
}
/**
* Watch pod until container `container.name` exits and its log stream
* is done being written to. Resolve promise with status if container
* `container.name` exits with status 0. If container exits with
* non-zero status, reject promise and includ pod status in the
* `podStatus` property of the error. If any other error occurs,
* e.g., a watch or log error or timeout exceeded, reject immediately
* upon receipt of error.
*
* @param container Information about container to watch
* @param timeout Milliseconds to allow container to run
* @return Status of pod after container terminates
*/
function containerWatch(container: K8sContainer, timeout: number): Promise<k8s.V1PodStatus> {
return new Promise(async (resolve, reject) => {
const clean: ContainerDetritus = {};
const k8sLog = new k8s.Log(container.config);
clean.logStream = new Writable({
write: (chunk, encoding, callback) => {
container.log.write(chunk.toString());
callback();
},
});
let logDone = false;
let podStatus: k8s.V1PodStatus | undefined;
let podError: Error | undefined;
const doneCallback = (e: any) => {
logDone = true;
if (e) {
e.message = `Container logging error: ${k8sErrMsg(e)}`;
container.log.write(e.message);
containerCleanup(clean);
reject(e);
}
if (podStatus) {
containerCleanup(clean);
resolve(podStatus);
} else if (podError) {
containerCleanup(clean);
reject(podError);
}
};
const logOptions: k8s.LogOptions = { follow: true };
clean.logRequest = await k8sLog.log(
container.ns,
container.pod,
container.name,
clean.logStream,
doneCallback,
logOptions,
);
let watch: k8s.Watch;
try {
watch = new k8s.Watch(container.config);
} catch (e) {
e.message = `Failed to create Kubernetes watch client: ${e.message}`;
container.log.write(e.message);
containerCleanup(clean);
reject(e);
}
clean.timeout = setTimeout(() => {
containerCleanup(clean);
reject(new Error(`Goal timeout '${timeout}' exceeded`));
}, timeout);
const watchPath = `/api/v1/watch/namespaces/${container.ns}/pods/${container.pod}`;
clean.watcher = await watch.watch(
watchPath,
{},
async (phase, obj) => {
const pod = obj as k8s.V1Pod;
if (pod?.status?.containerStatuses) {
const containerStatus = pod.status.containerStatuses.find(c => c.name === container.name);
if (containerStatus?.state?.terminated) {
const exitCode: number = containerStatus.state.terminated.exitCode;
if (exitCode === 0) {
podStatus = pod.status;
const msg = `Container '${container.name}' exited with status 0`;
container.log.write(msg);
if (logDone) {
containerCleanup(clean);
resolve(podStatus);
}
} else {
const msg = `Container '${container.name}' exited with status ${exitCode}`;
container.log.write(msg);
podError = new Error(msg);
(podError as any).podStatus = pod.status;
if (logDone) {
containerCleanup(clean);
reject(podError);
}
}
return;
}
}
container.log.write(`Container '${container.name}' phase: ${phase}`);
},
() => containerCleanup(clean),
err => {
err.message = `Container watcher failed: ${err.message}`;
container.log.write(err.message);
containerCleanup(clean);
reject(err);
},
);
});
}
/** Clean up resources used to watch running container. */
function containerCleanup(c: ContainerDetritus): void {
if (c.timeout) {
clearTimeout(c.timeout);
}
if (c.logRequest?.abort) {
c.logRequest.abort();
}
if (c.logStream?.end) {
c.logStream.end();
}
if (c.watcher?.abort) {
c.watcher.abort();
}
} | the_stack |
import * as fse from 'fs-extra';
import test from 'ava';
import {
rmdir, DirItem, OSWALK, osWalk,
} from '../src/io';
import { join, dirname } from '../src/path';
import { Commit } from '../src/commit';
import { Index } from '../src/index';
import { Reference } from '../src/reference';
import { COMMIT_ORDER, Repository } from '../src/repository';
import { createRandomFile, getRandomPath } from './helper';
import { TreeEntry } from '../src/treedir';
async function repoTest(t, commondirInside: boolean) {
const repoPath = getRandomPath();
let repo: Repository;
let index: Index;
let foopath1: string;
let foopath2: string;
if (commondirInside) {
await Repository.initExt(repoPath);
} else {
const commondir = getRandomPath();
await Repository.initExt(repoPath, { commondir: `${commondir}.external-snow` });
}
let howManyCharsAreEqualInHash = 0;
const firstCommitMessage = 'Add Foo';
const secondCommitMessage = 'Delete Foo';
await Repository.open(repoPath)
.then(async (repoResult: Repository) => {
repo = repoResult;
index = repo.ensureMainIndex();
foopath1 = join(repo.workdir(), 'foo');
const file1 = await createRandomFile(foopath1, 2048);
index.addFiles([file1.filepath]);
// index uses an internal set. So this is an additional check
// to ensure addFiles doesn't add the file actually twice
index.addFiles([file1.filepath]);
foopath2 = join(repo.workdir(), 'subdir', 'bar');
fse.ensureDirSync(dirname(foopath2));
const file2 = await createRandomFile(foopath2, 2048);
index.addFiles([file2.filepath]);
if (file1.filehash.substr(0, 4) === file2.filehash.substr(0, 4)) {
howManyCharsAreEqualInHash = 4;
} else if (file1.filehash.substr(0, 2) === file2.filehash.substr(0, 2)) {
howManyCharsAreEqualInHash = 2;
} else {
howManyCharsAreEqualInHash = 0;
}
return index.writeFiles();
}).then(() => repo.createCommit(repo.getFirstIndex(), firstCommitMessage))
.then((commit: Commit) => {
t.is(commit.message, firstCommitMessage, 'commit message');
t.true(Boolean(commit.parent), "Commit has a parent 'Created Project'");
t.is(commit.root.children.length, 2, 'one file in root dir, one subdir');
const filenames = Array.from(commit.root.getAllTreeFiles({ entireHierarchy: true, includeDirs: true }).keys());
t.true(filenames.includes('foo'));
t.true(filenames.includes('subdir'));
t.true(filenames.includes('subdir/bar'));
return osWalk(repo.workdir(), OSWALK.DIRS | OSWALK.FILES | OSWALK.HIDDEN | OSWALK.BROWSE_REPOS);
})
.then(async (dirItems: DirItem[]) => {
if (commondirInside) {
// Two random files can generate hashes where the first 2 or 4 digits are equal.
// Depending on the situation, we expect either 22, 23 or 24 items since we might have fewer
// directories in the object database
// eslint-disable-next-line default-case
switch (howManyCharsAreEqualInHash) {
case 4: // if 4-digits of hash are equal, we have 2 directories less
t.is(dirItems.length, 22, 'expect 22 items');
break;
case 2: // if 2-digits of hash are equal, we have 1 directory less
t.is(dirItems.length, 23, 'expect 23 items');
break;
case 0: // by default we expect 24 items
t.is(dirItems.length, 24, 'expect 24 items');
break;
}
} else {
t.is(dirItems.length, 4, 'expect 3 items (foo + subdir + subdir/bar + .snow)');
}
t.true(fse.pathExistsSync(join(repo.commondir(), 'HEAD')), 'HEAD reference');
t.true(fse.pathExistsSync(join(repo.commondir(), 'config')), 'repo must contain a config file');
t.true(fse.pathExistsSync(join(repo.commondir(), 'hooks')), 'repo must contain a hooks directory');
t.true(fse.pathExistsSync(join(repo.commondir(), 'objects')), 'repo must contain an objects directory');
t.true(fse.pathExistsSync(join(repo.commondir(), 'refs')), 'repo must have a refs directory');
t.true(fse.pathExistsSync(join(repo.commondir(), 'refs', 'Main')), 'Main reference');
t.true(fse.pathExistsSync(join(repo.commondir(), 'versions')), 'repo must have a version directory');
/* and a few more
.snow
.snow/config
.snow/HEAD
.snow/hooks
.snow/objects
.snow/objects/8e1760c0354228ce59e0c7b4356a933778823f40d8de89f56046cfa44e4667c1
.snow/objects/tmp
.snow/refs
.snow/refs/Main
.snow/versions
.snow/versions/20c3bc6257fd094295c8c86abb921c20985843a7af4b5bee8f9ab978a8bb70ab
.snow/versions/e598bbca7aa9d50f174e977cbc707292a7324082b45a9d078f45e892f670c9db
*/
// Reference checks
const head: Reference = repo.getHead();
t.is(head.getName(), 'Main', 'Default branch must be Main');
t.false(head.isDetached(), 'Default branch must not be detached');
// Commit checks
const commit: Commit = repo.getCommitByHead();
t.is(repo.getAllCommits(COMMIT_ORDER.UNDEFINED).length, 2);
t.is(commit.message, firstCommitMessage);
return osWalk(join(repo.commondir(), 'versions'), OSWALK.DIRS | OSWALK.FILES | OSWALK.HIDDEN);
})
.then((dirItems: DirItem[]) => {
t.is(dirItems.length, 2, 'expect 2 versions (Create Project + Version where foo got added)');
return fse.unlink(foopath1);
})
.then(() => {
index = repo.ensureMainIndex();
index.deleteFiles([foopath1]);
return index.writeFiles();
})
.then(() => repo.createCommit(repo.getFirstIndex(), secondCommitMessage))
.then((commit: Commit) => {
t.is(commit.message, secondCommitMessage, 'commit message');
t.true(Boolean(commit.parent), "Commit has a parent 'Created Project'");
t.is(commit.root.children.length, 1, 'no file anymore in root dir');
return osWalk(join(repo.commondir(), 'versions'), OSWALK.DIRS | OSWALK.FILES | OSWALK.HIDDEN);
})
.then((dirItems: DirItem[]) => {
t.is(dirItems.length, 3, 'expect 3 versions (Create Project + Version where foo got added and where foo got deleted)');
return osWalk(repo.workdir(), OSWALK.DIRS | OSWALK.FILES | OSWALK.HIDDEN);
})
.then((dirItems: DirItem[]) => {
t.is(dirItems.length, 2, 'expect 2 items (subdir and subdir/bar)'); // foo got deleted
t.true(fse.pathExistsSync(join(repo.commondir(), 'HEAD')), 'HEAD reference');
t.true(fse.pathExistsSync(join(repo.commondir(), 'config')), 'repo must contain a config file');
t.true(fse.pathExistsSync(join(repo.commondir(), 'hooks')), 'repo must contain a hooks directory');
t.true(fse.pathExistsSync(join(repo.commondir(), 'objects')), 'repo must contain an objects directory');
t.true(fse.pathExistsSync(join(repo.commondir(), 'refs')), 'repo must have a refs directory');
t.true(fse.pathExistsSync(join(repo.commondir(), 'refs', 'Main')), 'Main reference');
t.true(fse.pathExistsSync(join(repo.commondir(), 'versions')), 'repo must have a version directory');
/*
.snow/hooks
.snow
.snow/config
.snow/HEAD
.snow/objects
.snow/objects/c89df5c29949cb021e75efb768dcd5413f57da0bf69a644824b86c066b964ca5
.snow/objects/tmp
.snow/refs
.snow/refs/Main
.snow/versions
.snow/versions/3b884181f8919e113e69f82e0d3e0f0d610b5087e5bc1e202f380d83029694ee
.snow/versions/812da2a9e3116f6134d84d1743b655f1452ef8b2bcd42f6b747b555b8c059dc5
.snow/versions/c5f79ed5edfd5dcb27d4bfd61d115f4b242f8b647393c4dd441dec7c48673d53
*/
})
.then(() => rmdir(repo.workdir()))
.then(() => {
if (!commondirInside) {
return rmdir(repo.commondir());
}
});
}
test('repo open-commondir-outside', async (t) => {
/* This test creates a repo, and creates 2 commits.
1st commit: Add file 'foo'
2nd commit: Delete file 'foo'
*/
await repoTest(t, false);
});
test('repo open-commondir-inside', async (t) => {
/* This test creates a repo, and creates 2 commits.
1st commit: Add file 'foo'
2nd commit: Delete file 'foo'
*/
await repoTest(t, true);
});
test('custom-commit-data', async (t) => {
/*
Add a file and attach user-data to the commit
*/
const repoPath = getRandomPath();
let repo: Repository;
await Repository.initExt(repoPath).then((repoResult: Repository) => {
repo = repoResult;
return fse.writeFile(join(repo.workdir(), 'foo.txt'), 'Hello World!');
}).then(() => {
const index = repo.ensureMainIndex();
index.addFiles(['foo.txt']);
return index.writeFiles();
}).then(() => {
const index = repo.getFirstIndex();
return repo.createCommit(index, 'This is a commit with custom-data', {}, [], { hello: 'world', foo: 'bar', bas: 3 });
})
.then((commit: Commit) => {
t.log('User Data of commit', commit.userData);
t.is(commit.userData.hello, 'world');
t.is(commit.userData.foo, 'bar');
t.is(commit.userData.bas, 3);
});
await Repository.open(repoPath).then((repo: Repository) => {
const lastCommit = repo.getAllCommits(COMMIT_ORDER.NEWEST_FIRST)[0];
t.is(lastCommit.userData.hello, 'world');
t.is(lastCommit.userData.foo, 'bar');
t.is(lastCommit.userData.bas, 3);
});
});
test('commit hash subdirectory test', async (t) => {
/*
createCommit contains a hash to ensure that all items commited have a hash, even in subdirectories.
This test ensures no exception is thrown.
*/
const repoPath = getRandomPath();
let repo: Repository;
await Repository.initExt(repoPath).then((repoResult: Repository) => {
repo = repoResult;
return fse.ensureFile(join(repo.workdir(), 'a', 'b', 'c', 'd', 'e', 'foo.txt'));
}).then(() => {
const index = repo.ensureMainIndex();
index.addFiles(['a/b/c/d/e/foo.txt']);
return index.writeFiles();
}).then(() => {
const index = repo.getFirstIndex();
return repo.createCommit(index, 'This is a commit with several subdirectories');
})
.then((commit: Commit) => {
// The hash is already verified inside `createCommit`, but we check here again, just in case `createCommit` gets some changes in the future
const items: Map<string, TreeEntry> = commit.root.getAllTreeFiles({ entireHierarchy: true, includeDirs: true });
items.forEach((item: TreeEntry) => {
t.true(!!item.hash);
});
t.pass();
});
});
function makeCommit(repo: Repository, message: string): Promise<Commit> {
return fse.writeFile(join(repo.workdir(), 'foo.txt'), message)
.then(() => {
const index = repo.ensureMainIndex();
index.addFiles(['foo.txt']);
return index.writeFiles();
}).then(() => {
const index = repo.getFirstIndex();
return repo.createCommit(index, message);
});
}
test('HEAD~n', async (t) => {
const repoPath = getRandomPath();
const repo = await Repository.initExt(repoPath);
const commit1: Commit = await makeCommit(repo, '1st-commit');
const commit2: Commit = await makeCommit(repo, '2nd-commit');
const commit3: Commit = await makeCommit(repo, '3rd-commit');
const commit4: Commit = await makeCommit(repo, '4th-commit');
const commit5: Commit = await makeCommit(repo, '5th-commit');
let res: Commit;
t.log('Test HEAD~0');
res = repo.findCommitByHash('HEAD~0');
t.is(res.hash, commit5.hash);
t.log('Test HEAD~1');
res = repo.findCommitByHash('HEAD~1');
t.is(res.hash, commit4.hash);
t.log('Test Main~1');
res = repo.findCommitByHash('Main~1');
t.is(res.hash, commit4.hash);
t.log('Test HEAD~2');
res = repo.findCommitByHash('HEAD~2');
t.is(res.hash, commit3.hash);
t.log('Test HEAD~3');
res = repo.findCommitByHash('HEAD~3');
t.is(res.hash, commit2.hash);
t.log('Test HEAD~4');
res = repo.findCommitByHash('HEAD~4');
t.is(res.hash, commit1.hash);
t.log('Test HEAD~1~2');
res = repo.findCommitByHash('HEAD~1~2'); // ~1~2 ==> 3 commits back from HEAD
t.is(res.hash, commit2.hash);
t.log('Test HEAD~1~1~1~1');
res = repo.findCommitByHash('HEAD~1~1~1~1'); // ~1~1~1~1 ==> 4 commits back from HEAD
t.is(res.hash, commit1.hash);
});
test('HEAD~n --- ERROR INPUTS', async (t) => {
const repoPath = getRandomPath();
const repo = await Repository.initExt(repoPath);
t.log('Test HEAD~A for failure');
const error0 = t.throws(() => repo.findCommitByHash('HEAD~A'));
t.is(error0.message, "invalid commit-hash 'HEAD~A'");
t.log('Test HEAD~6 for failure');
const error1 = t.throws(() => repo.findCommitByHash('HEAD~6'));
t.is(error1.message, "commit hash 'HEAD~6' out of history");
}); | the_stack |
import { _, QueryPredicate, QuerybaseUtils} from './QuerybaseUtils';
import { QuerybaseQuery } from './QuerybaseQuery';
import * as firebase from 'firebase';
export type DatabaseReference = firebase.database.Reference;
export type DatabaseQuery = firebase.database.Query;
export type CompleteCallback = (a: Error) => any;
/**
* Querybase - Provides composite keys and a simplified query API.
*
* @param {DatabaseReference} ref
* @param {indexOn} string[]
*
* @example
* // Querybase for multiple equivalency
* const firebaseRef = firebase.database.ref().child('people');
* const querybaseRef = querybase.ref(firebaseRef, ['name', 'age', 'location']);
*
* // Automatically handles composite keys
* querybaseRef.push({
* name: 'David',
* age: 27
* });
*
* const compositeRef = querybaseRef.where({
* name: 'David',
* age: 27
* })
* // .where() with multiple criteria returns a Firebase ref
* compositeRef.on('value', (snap) => console.log(snap.val());
*
* // Querybase for single criteria, returns a Firebase Ref
* querybaseRef.where({ name: 'David'});
*
* // Querybase for a single string criteria, returns
* // a QuerybaseQuery, which returns a Firebase Ref
* querybaseRef.where('name').startsWith('Da');
* querybaseRef.where('age').lessThan(30);
* querybaseRef.where('age').greaterThan(20);
* querybaseRef.where('age').between(20, 30);
*/
export class Querybase {
INDEX_LENGTH = 3;
// read only properties
// Returns a read-only Database reference
ref: () => DatabaseReference;
// Returns a read-only set of indexes
indexOn: () => string[];
// the key of the Database ref
key: string;
// the set of indexOn keys base64 encoded
private encodedKeys: () => string[];
/**
* The constructor provides the backing values
* for the read-only properties
*/
constructor(ref: DatabaseReference, indexOn: string[]) {
// Check for constructor params and throw if not provided
this._assertFirebaseRef(ref);
this._assertIndexes(indexOn);
this._assertIndexLength(indexOn);
this.ref = () => ref;
this.indexOn = () => indexOn.sort(_.lexicographicallySort);
/* istanbul ignore next */
this.key = this.ref().key;
this.encodedKeys = () => this.encodeKeys(this.indexOn());
}
/**
* Check for a Firebase Database reference. Throw an exception if not provided.
* @parameter {DatabaseReference}
* @return {void}
*/
private _assertFirebaseRef(ref: DatabaseReference) {
if (ref === null || ref === undefined || !ref.on) {
throw new Error(`No Firebase Database Reference provided in the Querybase constructor.`);
}
}
/**
* Check for indexes. Throw an exception if not provided.
* @param {string[]} indexes
* @return {void}
*/
private _assertIndexes(indexes: any[]) {
if (indexes === null || indexes === undefined) {
throw new Error(`No indexes provided in the Querybase constructor. Querybase uses the indexOn() getter to create the composite queries for the where() method.`);
}
}
/**
* Check for indexes length. Throw and exception if greater than the INDEX_LENGTH value.
* @param {string[]} indexes
* @return {void}
*/
private _assertIndexLength(indexes: any[]) {
if (indexes.length > this.INDEX_LENGTH) {
throw new Error(`Querybase supports only ${this.INDEX_LENGTH} indexes for multiple querying.`)
}
}
/**
* Save data to the realtime database with composite keys
* @param {any} data
* @return Promise
*/
set(data, onComplete?: CompleteCallback) {
const dataWithIndex = this.indexify(data);
return this.ref().set(dataWithIndex, onComplete);
}
/**
* Update data to the realtime database with composite keys
* @param {any} data
* @return {void}
*/
update(data, onComplete?: CompleteCallback) {
const dataWithIndex = this.indexify(data);
return this.ref().update(dataWithIndex);
}
/**
* Push a child node to the realtime database with composite keys, if
* there is more than one property in the object
* @param {any} data
* @return {ThenableReference}
*/
push(data, onComplete?: CompleteCallback) {
// TODO: Should we return a Querybase with the option
// to specify child indexes?
if (!data) { return this.ref().push() }
// If there is only one key there's no need to indexify
if (_.keys(data).length === 1) {
return this.ref().push(data);
}
// Create indexes with indexed data values
const dataWithIndex = this.indexify(data);
// merge basic data with indexes with data
const indexesAndData = _.merge(dataWithIndex, data);
let firebaseRef = this.ref().push();
firebaseRef.set(indexesAndData, onComplete);
return firebaseRef;
}
/**
* Remove the current value from the Firebase reference
* @return {void}
*/
remove(onComplete?: CompleteCallback) {
return this.ref().remove(onComplete);
}
/**
* Create a child reference with a specified path and provide
* specific indexes for the child path
* @param {any} data
* @return {DatabaseReference}
*/
child(path, indexOn: string[]) {
return new Querybase(this.ref().child(path), indexOn);
}
/**
* Creates a QueryPredicate based on the criteria object passed. It
* combines the keys and values of the criteria object into a predicate
* and value string respectively.
* @param {Object} criteria
* @return {DatabaseReference}
*/
private _createQueryPredicate(criteria): QueryPredicate {
// Sort provided object lexicographically to match keys in database
const sortedCriteria = _.sortObjectLexicographically(criteria);
// retrieve the keys and values array
const keys = _.keys(sortedCriteria);
const values = _.values(sortedCriteria);
// warn about the indexes for indexOn rules
this._warnAboutIndexOnRule();
// for only one criteria in the object, use the key and vaue
if (!_.hasMultipleCriteria(keys)) {
return {
predicate: keys[0],
value: values[0]
};
}
// for multiple criteria in the object,
// encode the keys and values provided
const criteriaIndex = this.encodeKey(keys.join(_.indexKey()));
const criteriaValues = this.encodeKey(values.join(_.indexKey()));
return {
predicate: criteriaIndex,
value: criteriaValues
};
}
/**
* Creates an orderByChild() FirebaseQuery from a string criteria.
* @param {string} stringCriteria
* @return {QuerybaseQuery}
*/
private _createChildOrderedQuery(stringCriteria: string): QuerybaseQuery {
return new QuerybaseQuery(this.ref().orderByChild(stringCriteria));
}
/**
* Creates an equalTo() FirebaseQuery from a QueryPredicate.
* @param {Object} criteria
* @return {DatabaseReference}
*/
private _createEqualToQuery(criteria: QueryPredicate): DatabaseQuery {
return this.ref().orderByChild(criteria.predicate).equalTo(criteria.value);
}
/**
* Find a set of records by a set of criteria or a string property.
* Works with equivalency only.
* @param {Object} criteria
* @return {DatabaseReference}
* @example
* // set of criteria
* const firebaseRef = firebase.database.ref.child('people');
* const querybaseRef = querybase.ref(firebaseRef, ['name', 'age', 'location']);
* querybaseRef.where({
* name: 'David',
* age: 27
* }).on('value', (snap) => {});
*
* // single criteria property
* querybaseRef.where({ name: 'David' }).on('value', (snap) => {});
*
* // string property
* querybaseRef.where('age').between(20, 30).on('value', (snap) => {});
*/
where(criteria): any {
// for strings create a QuerybaseQuery for advanced querying
if (_.isString(criteria)) {
return this._createChildOrderedQuery(criteria);
}
// Create the query predicate to build the Firebase Query
const queryPredicate = this._createQueryPredicate(criteria);
return this._createEqualToQuery(queryPredicate);
}
/**
* Creates a set of composite keys with composite data. Creates every
* possible combination of keys with respecive combined values. Redudant
* keys are not included ('name~~age' vs. 'age~~name').
* @param {any[]} indexes
* @param {Object} data
* @param {Object?} indexHash for recursive check
* @return {Object}
* @example
* const indexes = ['name', 'age', 'location'];
* const data = { name: 'David', age: 27, location: 'SF' };
* const compositeKeys = _createCompositeIndex(indexes, data);
*
* // compositeKeys
* {
* 'name~~age': 'David~~27',
* 'name~~age~~location': 'David~~27~~SF',
* 'name~~location': 'David~~SF',
* 'age~~location': '27~~SF'
* }
*/
private _createCompositeIndex(indexes: any[], data: Object, indexHash?: Object) {
if(!Array.isArray(indexes)) {
throw new Error(`_createCompositeIndex expects an array for the first parameter: found ${indexes}`)
}
if(indexes.length === 0) {
throw new Error(`_createCompositeIndex expect an array with multiple elements for the first parameter. Found an array with length of ${indexes.length}`);
}
if(!_.isObject(data)) {
throw new Error(`_createCompositeIndex expects an object for the second parameter: found ${data}`);
}
// create a copy of the array to not modifiy the original properties
const propCop = indexes.slice();
// remove the first property, this ensures no
// redundant keys are created (age~~name vs. name~~age)
const mainProp = propCop.shift();
// recursive check for the indexHash
indexHash = indexHash || {};
propCop.forEach((prop) => {
let propString = "";
let valueString = "";
// first level keys
// ex: ['name', 'age', 'location']
// -> 'name~~age'
// -> 'name~~location'
// -> 'age~~location'
indexHash[_.createKey(mainProp, prop)] =
_.createKey(data[mainProp], data[prop]);
// create indexes for all property combinations
// ex: ['name', 'age', 'location']
// -> 'name~~age~~location'
propCop.forEach((subProp) => {
propString = _.createKey(propString, subProp);
valueString = _.createKey(valueString, data[subProp]);
});
indexHash[mainProp + propString] = data[mainProp] + valueString;
});
// recursive check
if (propCop.length !== 0) {
this._createCompositeIndex(propCop, data, indexHash);
}
return indexHash;
}
/**
* Encode (base64) all keys and data to avoid collisions with the
* chosen Querybase delimiter key (_)
* @param {Object} indexWithData
* @return {Object}
*/
private _encodeCompositeIndex(indexWithData: Object) {
if(!_.isObject(indexWithData)) {
throw new Error(`_encodeCompositeIndex expects an object: found ${indexWithData.toString()}`);
}
const values = _.values(indexWithData);
const keys = _.keys(indexWithData);
const encodedValues = this.encodeKeys(values);
const encodedKeys = this.encodeKeys(keys);
return _.arraysToObject(encodedKeys, encodedValues);
}
/**
* Encode (base64) all keys and data to avoid collisions with the
* chosen Querybase delimiter key (~~)
* @param {Object} indexWithData
* @return {Object}
*/
indexify(data: Object) {
const compositeIndex = this._createCompositeIndex(this.indexOn(), data);
const encodedIndexes = this._encodeCompositeIndex(compositeIndex);
return encodedIndexes;
}
/**
* Encode (base64) a single key with the Querybase format
* @param {string} value
* @return {string}
*/
encodeKey(value: string): string {
return `querybase${_.indexKey()}` + _.encodeBase64(value);
}
/**
* Encode (base64) a set of keys with the Querybase format
* @param {string[]} values
* @return {string}
*/
encodeKeys(values: string[]): string[] {
return values.map((value) => this.encodeKey(value));
}
/**
* Print a warning to the console about using ".indexOn" rules for
* the generated keys. This warning has a copy-and-pastable security rule
* based upon the keys provided.
* @param {string} value
* @return {void}
*/
private _warnAboutIndexOnRule() {
const indexKeys = this.encodedKeys();
const _indexOnRule = `
"${_.getPathFromRef(this.ref())}": {
".indexOn": [${_.keys(indexKeys).map((key) => { return `"${indexKeys[key]}"`; }).join(", ")}]
}`;
console.warn(`If you haven't yet, add this rule to drastically improve performance of your Realtime Database queries: \n ${_indexOnRule}`);
}
} | the_stack |
import {
GetScheduleDistributionInput,
PaymentScheduleDistribution,
} from '@island.is/api/schema'
import { FieldBaseProps } from '@island.is/application/core'
import {
AccordionItem,
AlertMessage,
Box,
Text,
} from '@island.is/island-ui/core'
import { useLocale } from '@island.is/localization'
import { RadioController } from '@island.is/shared/form-fields'
import React, { useCallback, useEffect, useState } from 'react'
import { useFormContext } from 'react-hook-form'
import HtmlParser from 'react-html-parser'
import { useLazyDistribution } from '../../hooks/useLazyDistribution'
import { shared } from '../../lib/messages'
import { paymentPlan } from '../../lib/messages/paymentPlan'
import { formatIsk } from '../../lib/paymentPlanUtils'
import { AMOUNT, MONTHS } from '../../shared/constants'
import {
getEmptyPaymentPlanEntryKey,
getPaymentPlanKeyById,
} from '../../shared/utils'
import {
PaymentModeState,
PaymentPlanExternalData,
PublicDebtPaymentPlan,
} from '../../types'
import { PaymentPlanTable } from '../components/PaymentPlanTable/PaymentPlanTable'
import { PlanSlider } from '../components/PlanSlider/PlanSlider'
import { PaymentPlanCard } from '../PaymentPlanList/PaymentPlanCard/PaymentPlanCard'
import * as styles from './PaymentPlan.css'
import { useDebouncedSliderValues } from './useDebouncedSliderValues'
// An array might not work for this schema
// Might need to define specific fields for each one
export const PaymentPlan = ({ application, field }: FieldBaseProps) => {
const { formatMessage } = useLocale()
const { register } = useFormContext()
const getDistribution = useLazyDistribution()
const [isLoading, setIsLoading] = useState(false)
const [
distributionData,
setDistributionData,
] = useState<PaymentScheduleDistribution | null>(null)
const [displayInfo, setDisplayInfo] = useState(false)
const externalData = application.externalData as PaymentPlanExternalData
const answers = application.answers as PublicDebtPaymentPlan
const index = field.defaultValue as number
// Assign a payment to this screen by using the index of the step
const payment = externalData.paymentPlanPrerequisites?.data?.debts[index]
// Geta min/max month and min/max payment data
const initialMinMaxData = externalData.paymentPlanPrerequisites?.data?.allInitialSchedules.find(
(x) => x.scheduleType === payment?.type,
)
// Locate the entry of the payment plan in answers.
const entryKey = getPaymentPlanKeyById(
answers.paymentPlans,
payment?.type || '',
)
// If no entry is found, find an empty entry to assign to this payment
const answerKey = (entryKey ||
getEmptyPaymentPlanEntryKey(
answers.paymentPlans,
)) as keyof typeof answers.paymentPlans
const entry = `paymentPlans.${answerKey}`
const currentAnswers = answers.paymentPlans
? answers.paymentPlans[answerKey]
: undefined
const [paymentMode, setPaymentMode] = useState<PaymentModeState | undefined>(
currentAnswers?.paymentMode,
)
const getDistributionCallback = useCallback(
async ({
monthAmount = null,
monthCount = null,
totalAmount,
scheduleType,
}: GetScheduleDistributionInput) => {
const { data } = await getDistribution({
input: {
monthAmount,
monthCount,
totalAmount,
scheduleType,
},
})
return data
},
[getDistribution],
)
const {
debouncedAmount,
debouncedMonths,
setAmount,
setMonths,
} = useDebouncedSliderValues(currentAnswers)
useEffect(() => {
if (payment && paymentMode !== undefined && initialMinMaxData) {
setIsLoading(true)
getDistributionCallback({
monthAmount:
paymentMode === AMOUNT
? debouncedAmount === undefined
? initialMinMaxData?.minPayment
: debouncedAmount
: initialMinMaxData?.minPayment,
monthCount:
paymentMode === MONTHS
? debouncedMonths === undefined
? initialMinMaxData?.maxCountMonth
: debouncedMonths
: null,
totalAmount: payment.totalAmount,
scheduleType: payment.type,
})
.then((response) => {
setDistributionData(response?.paymentScheduleDistribution || null)
setIsLoading(false)
const monthlyPayments =
response?.paymentScheduleDistribution.payments[0].payment
const finalMonthPayment =
response?.paymentScheduleDistribution.payments[
response?.paymentScheduleDistribution.payments.length - 1
].payment
if (monthlyPayments && finalMonthPayment)
setDisplayInfo(monthlyPayments < finalMonthPayment)
})
.catch((error) => {
console.error(
'An error occured fetching payment distribution: ',
error,
)
})
}
}, [
debouncedAmount,
debouncedMonths,
getDistributionCallback,
payment,
paymentMode,
initialMinMaxData,
])
const handleSelectPaymentMode = (mode: any) => {
setPaymentMode(mode)
}
const handleAmountChange = (value: number) => {
setMonths(undefined)
setAmount(value)
}
const handleMonthChange = (value: number) => {
setMonths(value)
setAmount(undefined)
}
if (!payment)
// TODO: Better error message
return (
<div>Eitthvað fór úrskeiðis, núverandi greiðsludreifing fannst ekki</div>
)
const SliderDescriptor = () => {
if (!distributionData || distributionData?.payments?.length < 1) return null
const monthlyPayments = distributionData.payments[0].payment
const lastMonthsPayment =
distributionData.payments[distributionData.payments.length - 1].payment
let count = 0
if (monthlyPayments === lastMonthsPayment) {
count = distributionData.payments.length === 1 ? 0 : 1
} else {
count = 2
}
return (
<Box display="flex" justifyContent="flexEnd">
<Text variant="small" fontWeight="semiBold">
{formatMessage(paymentPlan.labels.sliderDescriptor, {
count,
monthlyPayments: HtmlParser(
`<span class="${styles.valueLabel}">${formatIsk(
monthlyPayments,
)}</span>`,
),
monthsAmount:
count === 0 || count === 1
? distributionData.payments.length
: distributionData.payments.length - 1,
lastMonthsPayment: HtmlParser(
`<span class="${styles.valueLabel}">${formatIsk(
lastMonthsPayment,
)}</span>`,
),
lastMonth: distributionData.payments.length,
})}
</Text>
</Box>
)
}
return (
<div>
<input
type="hidden"
value={payment.type}
ref={register({ required: true })}
name={`${entry}.id`}
/>
<input
type="hidden"
value={payment.totalAmount}
ref={register({ required: true })}
name={`${entry}.totalAmount`}
/>
<input
type="hidden"
value={JSON.stringify(distributionData?.payments || '')}
ref={register({ required: true })}
name={`${entry}.distribution`}
/>
<Text marginBottom={5}>
{formatMessage(paymentPlan.general.paymentPlanDescription)}
</Text>
<Box marginBottom={[5, 5, 8]}>
<PaymentPlanCard payment={payment} />
</Box>
<Text variant="h4" marginBottom={3}>
{formatMessage(paymentPlan.labels.paymentModeTitle)}
</Text>
<RadioController
id={`${entry}.paymentMode`}
disabled={false}
name={`${entry}.paymentMode`}
largeButtons={true}
defaultValue={paymentMode}
onSelect={handleSelectPaymentMode}
options={[
{
value: AMOUNT,
label: formatMessage(paymentPlan.labels.payByAmount),
},
{
value: MONTHS,
label: formatMessage(paymentPlan.labels.payByMonths),
},
]}
/>
{paymentMode === AMOUNT && (
<PlanSlider
id={`${entry}.amountPerMonth`}
minValue={initialMinMaxData?.minPayment || 5000}
maxValue={initialMinMaxData?.maxPayment || 10000}
currentValue={initialMinMaxData?.minPayment || 5000}
multiplier={10000}
heading={paymentPlan.labels.chooseAmountPerMonth}
onChange={handleAmountChange}
label={{
singular: 'kr.',
plural: 'kr.',
}}
descriptor={<SliderDescriptor />}
/>
)}
{paymentMode === MONTHS && (
<PlanSlider
id={`${entry}.numberOfMonths`}
minValue={initialMinMaxData?.minCountMonth || 1}
maxValue={initialMinMaxData?.maxCountMonth || 12}
currentValue={initialMinMaxData?.maxCountMonth || 12}
heading={paymentPlan.labels.chooseNumberOfMonths}
onChange={handleMonthChange}
label={{
singular: formatMessage(shared.month),
plural: formatMessage(shared.months),
}}
descriptor={<SliderDescriptor />}
/>
)}
{distributionData && (
<Box marginTop={5}>
<AccordionItem
id="payment-plan-table"
label="Greiðsluáætlun skuldar"
visibleContent={formatMessage(
paymentPlan.labels.distributionDataTitle,
)}
startExpanded
>
<PaymentPlanTable
isLoading={isLoading}
data={distributionData}
totalAmount={payment.totalAmount}
/>
</AccordionItem>
</Box>
)}
{displayInfo && (
<Box marginTop={3}>
<AlertMessage
type="info"
title={formatMessage(paymentPlan.labels.infoTitle)}
message={formatMessage(paymentPlan.labels.infoDescription)}
/>
</Box>
)}
</div>
)
} | the_stack |
import { reflectSpecifics } from "../../generated/types";
import type {
SpecificStatics,
CoreAccountSpecifics,
CoreOperationSpecifics,
CoreCurrencySpecifics,
} from "../../generated/types";
declare class CoreWalletPool {
newInstance(
name: string,
pwd: string,
httpClient: CoreHttpClient,
webSocket: CoreWebSocketClient,
pathResolver: CorePathResolver,
logPrinter: CoreLogPrinter,
threadDispatcher: CoreThreadDispatcher,
rng: CoreRandomNumberGenerator,
backend: CoreDatabaseBackend,
walletDynObject: CoreDynamicObject
): Promise<CoreWalletPool>;
getWallet(name: string): Promise<CoreWallet>;
getCurrency(id: string): Promise<CoreCurrency>;
updateWalletConfig(
walletName: string,
config: CoreDynamicObject
): Promise<void>;
createWallet(
walletName: string,
currency: CoreCurrency,
config: CoreDynamicObject
): Promise<CoreWallet>;
freshResetAll(): Promise<void>;
changePassword(oldPassword: string, newPassword: string): Promise<void>;
getName(): Promise<string>;
}
declare class CoreWallet {
getAccountCreationInfo(
accountIndex: number
): Promise<CoreAccountCreationInfo>;
getNextAccountCreationInfo(): Promise<CoreAccountCreationInfo>;
newAccountWithInfo(info: CoreAccountCreationInfo): Promise<CoreAccount>;
getCurrency(): Promise<CoreCurrency>;
getAccount(index: number): Promise<CoreAccount>;
getExtendedKeyAccountCreationInfo(
index: number
): Promise<CoreExtendedKeyAccountCreationInfo>;
newAccountWithExtendedKeyInfo(
keys?: CoreExtendedKeyAccountCreationInfo
): Promise<CoreAccount>;
}
export const TimePeriod = {
HOUR: 0,
DAY: 1,
WEEK: 2,
MONTH: 3,
};
declare type CoreAccount = {
getBalance(): Promise<CoreAmount>;
getBalanceHistory(
from: string,
to: string,
timePeriod: typeof TimePeriod[keyof typeof TimePeriod]
): Promise<CoreAmount[]>;
getLastBlock(): Promise<CoreBlock>;
getFreshPublicAddresses(): Promise<CoreAddress[]>;
getRestoreKey(): Promise<string>;
synchronize(): Promise<CoreEventBus>;
queryOperations(): Promise<CoreOperationQuery>;
} & CoreAccountSpecifics;
declare type CoreOperation = {
getDate(): Promise<string>;
getOperationType(): Promise<OperationType>;
getAmount(): Promise<CoreAmount>;
getFees(): Promise<CoreAmount | null | undefined>;
getBlockHeight(): Promise<number | null | undefined>;
getRecipients(): Promise<string[]>;
getSelfRecipients(): Promise<string[]>;
getSenders(): Promise<string[]>;
} & CoreOperationSpecifics;
declare type CoreCurrency = Record<string, never> & CoreCurrencySpecifics;
declare class CoreLedgerCore {
getStringVersion(): Promise<string>;
getIntVersion(): Promise<number>;
}
declare class CoreDatabaseBackend {
getSqlite3Backend(): Promise<CoreDatabaseBackend>;
flush(): Promise<void>;
}
declare class CoreHttpClient {
newInstance(): Promise<CoreHttpClient>;
flush(): Promise<void>;
}
declare class CoreWebSocketClient {
newInstance(): Promise<CoreWebSocketClient>;
flush(): Promise<void>;
}
declare class CorePathResolver {
newInstance(): Promise<CorePathResolver>;
flush(): Promise<void>;
}
declare class CoreLogPrinter {
newInstance(): Promise<CoreLogPrinter>;
flush(): Promise<void>;
}
declare class CoreRandomNumberGenerator {
newInstance(): Promise<CoreRandomNumberGenerator>;
flush(): Promise<void>;
}
declare class CoreBigInt {
fromIntegerString(s: string, radix: number): Promise<CoreBigInt>;
toString(base: number): Promise<string>;
}
declare class CoreAmount {
fromHex(arg0: CoreCurrency, arg1: string): Promise<CoreAmount>;
toBigInt(): Promise<CoreBigInt>;
}
declare class CoreBlock {
getHeight(): Promise<number>;
}
declare class CoreDerivationPath {
toString(): Promise<string>;
isNull(): Promise<boolean>;
}
export type OperationType = 0 | 1;
declare class CoreAddress {
isValid(recipient: string, currency: CoreCurrency): Promise<boolean>;
toString(): Promise<string>;
getDerivationPath(): Promise<string | null | undefined>;
}
declare class CoreOperationQuery {
offset(arg0: number): Promise<void>;
limit(arg0: number): Promise<void>;
partial(): Promise<void>;
complete(): Promise<void>;
addOrder(arg0: number, arg1: boolean): Promise<void>;
execute(): Promise<CoreOperation[]>;
}
declare class CoreAccountCreationInfo {
init(
index: number,
owners: string[],
derivations: string[],
publicKeys: string[],
chainCodes: string[]
): Promise<CoreAccountCreationInfo>;
getDerivations(): Promise<string[]>;
getChainCodes(): Promise<string[]>;
getPublicKeys(): Promise<string[]>;
getOwners(): Promise<string[]>;
getIndex(): Promise<number>;
}
declare class CoreExtendedKeyAccountCreationInfo {
init(
index: number,
owners: string[],
derivations: string[],
extendedKeys: string[]
): Promise<CoreExtendedKeyAccountCreationInfo>;
getIndex(): Promise<number>;
getExtendedKeys(): Promise<string[]>;
getOwners(): Promise<string[]>;
getDerivations(): Promise<string[]>;
}
declare class CoreDynamicObject {
newInstance(): Promise<CoreDynamicObject>;
flush(): Promise<void>;
putBoolean(arg0: string, arg1: boolean): Promise<void>;
putString(arg0: string, arg1: string): Promise<void>;
putInt(arg0: string, arg1: number): Promise<void>;
}
declare class CoreSerialContext {}
declare class CoreThreadDispatcher {
newInstance(): Promise<CoreThreadDispatcher>;
getMainExecutionContext(): Promise<CoreSerialContext>;
}
declare class CoreEventBus {
subscribe(
serialContext: CoreSerialContext,
eventReceiver: CoreEventReceiver
): Promise<void>;
}
declare class CoreEventReceiver {
newInstance(): Promise<CoreEventReceiver>;
}
export type CoreStatics = {
Account: CoreAccount;
AccountCreationInfo: CoreAccountCreationInfo;
Address: CoreAddress;
Amount: CoreAmount;
BigInt: CoreBigInt;
Block: CoreBlock;
Currency: CoreCurrency;
DatabaseBackend: CoreDatabaseBackend;
DerivationPath: CoreDerivationPath;
DynamicObject: CoreDynamicObject;
EventBus: CoreEventBus;
EventReceiver: CoreEventReceiver;
ExtendedKeyAccountCreationInfo: CoreExtendedKeyAccountCreationInfo;
HttpClient: CoreHttpClient;
LedgerCore: CoreLedgerCore;
LogPrinter: CoreLogPrinter;
Operation: CoreOperation;
OperationQuery: CoreOperationQuery;
PathResolver: CorePathResolver;
RandomNumberGenerator: CoreRandomNumberGenerator;
SerialContext: CoreSerialContext;
ThreadDispatcher: CoreThreadDispatcher;
Wallet: CoreWallet;
WalletPool: CoreWalletPool;
WebSocketClient: CoreWebSocketClient;
} & SpecificStatics;
export type Core = CoreStatics & {
flush: () => Promise<void>;
getPoolInstance: () => CoreWalletPool;
getThreadDispatcher: () => CoreThreadDispatcher;
};
export type {
CoreAccount,
CoreAccountCreationInfo,
CoreAddress,
CoreAmount,
CoreBigInt,
CoreBlock,
CoreCurrency,
CoreDatabaseBackend,
CoreDerivationPath,
CoreDynamicObject,
CoreEventBus,
CoreEventReceiver,
CoreExtendedKeyAccountCreationInfo,
CoreHttpClient,
CoreLedgerCore,
CoreLogPrinter,
CoreOperation,
CoreOperationQuery,
CorePathResolver,
CoreRandomNumberGenerator,
CoreSerialContext,
CoreThreadDispatcher,
CoreWallet,
CoreWalletPool,
CoreWebSocketClient,
};
type SpecMapF = {
params?: Array<(string | null | undefined) | string[]>;
returns?: string | string[];
njsField?: string;
njsInstanciateClass?: Array<Record<string, any>>;
njsBuggyMethodIsNotStatic?: boolean | ((...args: Array<any>) => any);
nodejsNotAvailable?: boolean;
};
export type Spec = {
njsUsesPlainObject?: boolean;
statics?: Record<string, SpecMapF>;
methods?: Record<string, SpecMapF>;
};
// To make the above contract possible with current libcore bindings,
// we need to define the code below and build-up abstraction wrappings on top of the lower level bindings.
// We do this at runtime but ideally in the future, it will be at build time (generated code).
export const reflect = (declare: (arg0: string, arg1: Spec) => void): void => {
const { AccountMethods, OperationMethods } = reflectSpecifics(declare).reduce(
(all, extra) => ({
AccountMethods: {
...all.AccountMethods,
...(extra && extra.AccountMethods),
},
OperationMethods: {
...all.OperationMethods,
...(extra && extra.OperationMethods),
},
}),
{ AccountMethods: {}, OperationMethods: {} }
);
declare("WalletPool", {
statics: {
newInstance: {
params: [
null,
null,
"HttpClient",
"WebSocketClient",
"PathResolver",
"LogPrinter",
"ThreadDispatcher",
"RandomNumberGenerator",
"DatabaseBackend",
"DynamicObject",
],
returns: "WalletPool",
},
},
methods: {
freshResetAll: {},
changePassword: {},
getName: {},
updateWalletConfig: {
params: [null, "DynamicObject"],
},
getWallet: {
returns: "Wallet",
},
getCurrency: {
returns: "Currency",
},
createWallet: {
params: [null, "Currency", "DynamicObject"],
returns: "Wallet",
},
},
});
declare("Wallet", {
methods: {
getAccountCreationInfo: {
returns: "AccountCreationInfo",
},
getNextAccountCreationInfo: {
returns: "AccountCreationInfo",
},
newAccountWithInfo: {
params: ["AccountCreationInfo"],
returns: "Account",
},
getCurrency: {
returns: "Currency",
},
getAccount: {
returns: "Account",
},
getExtendedKeyAccountCreationInfo: {
returns: "ExtendedKeyAccountCreationInfo",
},
newAccountWithExtendedKeyInfo: {
params: ["ExtendedKeyAccountCreationInfo"],
returns: "Account",
},
},
});
declare("Account", {
methods: {
...AccountMethods,
getBalance: {
returns: "Amount",
},
getBalanceHistory: {
returns: ["Amount"],
},
getLastBlock: {
returns: "Block",
},
getFreshPublicAddresses: {
returns: ["Address"],
},
getRestoreKey: {},
synchronize: {
returns: "EventBus",
},
queryOperations: {
returns: "OperationQuery",
},
},
});
declare("Operation", {
methods: {
...OperationMethods,
getDate: {},
getOperationType: {},
getAmount: {
returns: "Amount",
},
getFees: {
returns: "Amount",
},
getBlockHeight: {},
getRecipients: {},
getSelfRecipients: {},
getSenders: {},
},
});
declare("Currency", {
njsUsesPlainObject: true,
methods: {
getBitcoinLikeNetworkParameters: {
returns: "BitcoinLikeNetworkParameters",
njsField: "bitcoinLikeNetworkParameters",
},
},
});
declare("BigInt", {
statics: {
fromIntegerString: {
njsBuggyMethodIsNotStatic: () => ["", 0, "."],
returns: "BigInt",
},
},
methods: {
toString: {},
},
});
declare("Amount", {
statics: {
fromHex: {
params: ["Currency"],
returns: "Amount",
njsBuggyMethodIsNotStatic: true,
},
},
methods: {
toBigInt: {
returns: "BigInt",
},
},
});
declare("Block", {
njsUsesPlainObject: true,
methods: {
getHeight: {
njsField: "height",
},
},
});
declare("DerivationPath", {
methods: {
toString: {},
isNull: {},
},
});
declare("Address", {
statics: {
isValid: {
params: [null, "Currency"],
njsBuggyMethodIsNotStatic: true,
},
},
methods: {
toString: {},
getDerivationPath: {},
},
});
declare("OperationQuery", {
methods: {
limit: {},
offset: {},
partial: {},
complete: {},
addOrder: {},
execute: {
returns: ["Operation"],
},
},
});
declare("AccountCreationInfo", {
njsUsesPlainObject: true,
statics: {
init: {
params: [null, null, null, ["hex"], ["hex"]],
returns: "AccountCreationInfo",
njsInstanciateClass: [
{
index: 0,
owners: 1,
derivations: 2,
publicKeys: 3,
chainCodes: 4,
},
],
},
},
methods: {
getDerivations: {
njsField: "derivations",
},
getChainCodes: {
njsField: "chainCodes",
returns: ["hex"],
},
getPublicKeys: {
njsField: "publicKeys",
returns: ["hex"],
},
getOwners: {
njsField: "owners",
},
getIndex: {
njsField: "index",
},
},
});
declare("ExtendedKeyAccountCreationInfo", {
njsUsesPlainObject: true,
statics: {
init: {
returns: "ExtendedKeyAccountCreationInfo",
njsInstanciateClass: [
{
index: 0,
owners: 1,
derivations: 2,
extendedKeys: 3,
},
],
},
},
methods: {
getIndex: {
njsField: "index",
},
getExtendedKeys: {
njsField: "extendedKeys",
},
getOwners: {
njsField: "owners",
},
getDerivations: {
njsField: "derivations",
},
},
});
declare("DynamicObject", {
statics: {
flush: {},
newInstance: {
returns: "DynamicObject",
njsInstanciateClass: [],
},
},
methods: {
putBoolean: {},
putString: {},
putInt: {},
},
});
declare("SerialContext", {});
declare("ThreadDispatcher", {
statics: {
newInstance: {
returns: "ThreadDispatcher",
},
},
methods: {
getMainExecutionContext: {
nodejsNotAvailable: true,
returns: "SerialContext",
},
},
});
declare("EventBus", {
methods: {
subscribe: {
params: ["SerialContext", "EventReceiver"],
},
},
});
declare("EventReceiver", {
statics: {
newInstance: {
returns: "EventReceiver",
},
},
});
declare("HttpClient", {
statics: {
newInstance: {
returns: "HttpClient",
},
flush: {},
},
});
declare("WebSocketClient", {
statics: {
newInstance: {
returns: "WebSocketClient",
},
flush: {},
},
});
declare("PathResolver", {
statics: {
newInstance: {
returns: "PathResolver",
},
flush: {},
},
});
declare("LogPrinter", {
statics: {
newInstance: {
returns: "LogPrinter",
},
flush: {},
},
});
declare("RandomNumberGenerator", {
statics: {
newInstance: {
returns: "RandomNumberGenerator",
},
flush: {},
},
});
declare("DatabaseBackend", {
statics: {
flush: {},
getSqlite3Backend: {
returns: "DatabaseBackend",
},
},
});
declare("LedgerCore", {
statics: {
getStringVersion: {
njsBuggyMethodIsNotStatic: true,
},
getIntVersion: {
njsBuggyMethodIsNotStatic: true,
},
},
});
}; | the_stack |
import { dirname, join } from 'path';
import { appendFile, ensureDir, pathExists, readFile, remove, stat, unlink, writeFile } from 'fs-extra';
import { AlreadyEncoded, DeepkitFile, FileMode, FileType, FilterQuery, StreamBehaviorSubject } from '@deepkit/framework-shared';
import { eachKey, eachPair, ProcessLocker } from '@deepkit/core';
import * as crypto from 'crypto';
import { Database } from '@deepkit/orm';
import { Exchange, inject, injectable, LiveDatabase } from '@deepkit/framework';
import { ClassSchema, jsonSerializer, t } from '@deepkit/type';
export type PartialFile = { id: string, path: string, mode: FileMode, md5?: string, version: number };
export function getMd5(content: string | Buffer): string {
const buffer: Buffer = 'string' === typeof content ? new Buffer(content, 'utf8') : new Buffer(content);
const md5 = crypto.createHash('md5').update(buffer).digest('hex');
if (!md5) {
throw new Error(`md5 is empty`);
}
return md5;
}
const FSCacheMessage = t.schema({
id: t.string.optional,
md5: t.string.optional,
});
@injectable
export class FS<T extends DeepkitFile> {
constructor(
public readonly fileType: FileType<T>,
private exchange: Exchange,
private database: Database,
private liveDatabase: LiveDatabase,
private locker: ProcessLocker,
@inject('fs.dir') private fileDir: string /* .deepkit/data/files/ */,
) {
}
public setFileDir(dir: string) {
this.fileDir = dir;
}
public async removeAll(filter: FilterQuery<T>): Promise<boolean> {
const files = await this.database.query(this.fileType.classSchema).filter(filter).find();
return this.removeFiles(files);
}
public async remove(path: string, filter: FilterQuery<T> = {}): Promise<boolean> {
const file = await this.findOne(path, filter);
if (file) {
return this.removeFile(file);
}
return false;
}
public async removeFile(file: T): Promise<boolean> {
return this.removeFiles([file]);
}
public async removeFiles(files: T[]): Promise<boolean> {
const md5ToCheckMap: { [k: string]: number } = {};
const fileIds: string[] = [];
for (const file of files) {
if (file.md5) {
//we need to check whether the file is used by others
md5ToCheckMap[file.md5] = 0;
} else {
const split = this.getIdSplit(file.id);
const localPath = join(this.fileDir, 'streaming', split);
await remove(localPath);
}
fileIds.push(file.id);
this.exchange.publishFile(file.id, {
type: 'remove',
path: file.path
});
}
await this.database.query(this.fileType.classSchema).filter({
$and: [{
id: { $in: fileIds }
}]
} as FilterQuery<T>).deleteMany();
//find which md5s are still linked
const foundMd5s = await this.database.query(this.fileType.classSchema)
.select('md5')
.filter({ md5: { $in: Object.keys(md5ToCheckMap) } } as FilterQuery<T>)
.find();
//iterate over still linked md5 files, and remove missing ones
for (const row of foundMd5s) {
if (row.md5) md5ToCheckMap[row.md5]++;
}
const deletes: Promise<any>[] = [];
for (const [k, v] of eachPair(md5ToCheckMap)) {
if (v === 0) {
//no link for that md5 left, so delete file locally
const localPath = this.getLocalPathForMd5(k);
deletes.push(remove(localPath));
}
}
//delete them parallel
await Promise.all(deletes);
return true;
}
public async ls(filter: FilterQuery<T>): Promise<T[]> {
return await this.database.query(this.fileType.classSchema).filter(filter).find();
}
public async findOne(path: string, filter: FilterQuery<T> = {}): Promise<T | undefined> {
return await this.database.query(this.fileType.classSchema).filter({ path: path, ...filter } as T).findOneOrUndefined();
}
public async registerFile(md5: string, path: string, fields: Partial<T> = {}): Promise<T> {
const file = await this.database.query(this.fileType.classSchema).filter({ md5: md5 } as T).findOneOrUndefined();
if (!file) {
throw new Error(`No file with '${md5}' found.`);
}
if (!file.md5) {
throw new Error(`File ${file.id} has no md5 '${md5}'.`);
}
const localPath = this.getLocalPathForMd5(file.md5!);
if (await pathExists(localPath)) {
const newFile = this.fileType.fork(file, path);
for (const i of eachKey(fields)) {
(newFile as any)[i] = (fields as any)[i];
}
await this.database.persist(newFile);
return newFile;
} else {
throw new Error(`File with md5 '${md5}' not found (content deleted).`);
}
}
public async hasMd5InDb(md5: string): Promise<boolean> {
return await this.database.query(this.fileType.classSchema).filter({ md5 } as FilterQuery<T>).has();
}
public async hasMd5(md5: string) {
const file = await this.database.query(this.fileType.classSchema).filter({ md5: md5 } as FilterQuery<T>).findOneOrUndefined();
if (file && file.md5) {
const localPath = this.getLocalPathForMd5(md5);
return await pathExists(localPath);
}
return false;
}
public async read(path: string, filter?: FilterQuery<T>): Promise<Buffer | undefined> {
const file = await this.findOne(path, filter || {});
// console.log('Read file ' + path, filter, file ? file.id : undefined);
if (!file) {
return;
}
return new Promise<Buffer | undefined>(async (resolve, reject) => {
const localPath = this.getLocalPath(file);
if (await pathExists(localPath)) {
readFile(localPath, (err, data: Buffer) => {
if (err) {
reject(err);
}
resolve(data);
});
} else {
resolve(undefined);
}
});
}
public getMd5Split(md5: string) {
return md5.substr(0, 2) + '/' + md5.substr(2, 2) + '/' + md5.substr(4);
}
public getIdSplit(id: string) {
return id.substr(0, 8) + '/' + id.substr(9, 9) + '/' + id.substr(19);
}
public getLocalPathForMd5(md5: string): string {
if (!md5) {
console.error('md5', md5);
throw new Error('No md5 given.');
}
return join(this.fileDir, 'closed', this.getMd5Split(md5));
}
public getLocalPathForId(id: string): string {
return join(this.fileDir, 'streaming', this.getIdSplit(id));
}
public getLocalPath(file: PartialFile) {
if (file.mode === FileMode.closed) {
if (!file.md5) {
throw new Error(`Closed file has no md5 value: ${file.id} ${file.path}`);
}
return this.getLocalPathForMd5(file.md5);
}
if (!file.id) {
throw new Error(`File has no id ${file.path}`);
}
return this.getLocalPathForId(file.id);
}
/**
* Adds a new file or updates an existing one.
*/
public async write(path: string, data: string | Buffer, fields: Partial<T> = {}): Promise<PartialFile> {
let version = await this.exchange.version();
const meta = await this.getFileMetaCache(path, fields);
if ('string' === typeof data) {
data = Buffer.from(data, 'utf8');
}
const newMd5 = getMd5(data);
if (!meta.id) {
const file = new this.fileType.classType(path);
file.md5 = getMd5(data);
for (const i of eachKey(fields)) {
(file as any)[i] = (fields as any)[i];
}
file.size = data.byteLength;
meta.id = file.id;
version = 0;
await this.database.persist(file);
} else {
//when md5 changes, it's important to move
//the local file as well, since local path is based on md5.
//when there is still an file with that md5 in the database, do not remove the old one.
if (meta.md5 && meta.md5 !== newMd5) {
await this.database.query(this.fileType.classSchema as any as ClassSchema<DeepkitFile>).filter({ id: meta.id }).patchOne({ md5: newMd5, size: data.byteLength });
await this.refreshFileMetaCache(path, fields, meta.id, newMd5);
//we need to check whether the local file needs to be removed
if (!await this.hasMd5InDb(meta.md5)) {
//there's no db-file anymore linking using this local file, so remove it
const localPath = this.getLocalPathForMd5(meta.md5);
if (await pathExists(localPath)) {
try {
await unlink(localPath);
} catch (e) {
//Race condition could happen, but we don't care really.
}
}
}
}
}
const localPath = this.getLocalPathForMd5(newMd5);
const localDir = dirname(localPath);
await ensureDir(localDir);
const lock = await this.locker.acquireLock('file:' + path);
try {
await writeFile(localPath, data);
this.exchange.publishFile(meta.id, {
type: 'set',
version: version,
path: path,
});
} finally {
await lock.unlock();
}
return {
id: meta.id!,
mode: FileMode.closed,
path: path,
version: version,
md5: newMd5
};
}
public async refreshFileMetaCache(path: string, fields: Partial<T> = {}, id: string, md5?: string) {
const filter = { path, ...fields };
const cacheKey = JSON.stringify(jsonSerializer.for(this.fileType.classSchema).partialSerialize(filter));
await this.exchange.set('file-meta/' + cacheKey, FSCacheMessage, { id, md5 });
}
public async getFileMetaCache(path: string, fields: Partial<T> = {}): Promise<{ id?: string, md5?: string }> {
const filter = { path, ...fields };
const cacheKey = JSON.stringify(jsonSerializer.for(this.fileType.classSchema).partialSerialize(filter));
const fromCache = await this.exchange.get('file-meta/' + cacheKey, FSCacheMessage);
if (fromCache) return fromCache;
const item = await this.database.query(this.fileType.classSchema).filter({ path, ...fields }).findOneOrUndefined();
if (item) {
await this.refreshFileMetaCache(path, fields, item.id, item.md5);
return { id: item.id, md5: item.md5 };
}
return {};
}
/**
* Streams content by always appending data to the file's content and publishes the data to the exchange change feed.
*/
public async stream(
path: string,
data: Buffer,
fields: Partial<T> = {},
options: {
cropSizeAt?: number
cropSizeAtTo?: number
} = {}
) {
const lock = await this.locker.acquireLock('file:' + path);
let version = await this.exchange.version();
const meta = await this.getFileMetaCache(path, fields);
try {
let file: T | undefined;
if (!meta.id) {
file = new this.fileType.classType(path);
for (const i of eachKey(fields)) {
(file as any)[i] = (fields as any)[i];
}
file!.mode = FileMode.streaming;
meta.id = file!.id;
version = 0;
}
const localPath = this.getLocalPathForId(meta.id!);
const localDir = dirname(localPath);
if (!await pathExists(localDir)) {
await ensureDir(localDir);
}
await appendFile(localPath, data);
const stats = await stat(localPath);
if (options.cropSizeAt && options.cropSizeAtTo && stats.size > options.cropSizeAt) {
if (options.cropSizeAtTo >= options.cropSizeAt) {
throw new Error('cropSizeAtTo is not allowed to be bigger than cropSizeAt.');
}
const content = await readFile(localPath);
await writeFile(localPath, content.slice(stats.size - options.cropSizeAtTo));
}
if (file) {
//when a subscribes is listening to this file,
//we publish this only when the file is written to disk.
await this.database.persist(file);
this.refreshFileMetaCache(path, fields, meta.id!, undefined).catch(console.error);
}
await this.exchange.publishFile(meta.id!, {
type: 'append',
version: version,
path: path,
size: stats.size,
content: data.toString('base64'),
});
} finally {
await lock.unlock();
}
}
public async subscribe(path: string, fields: Partial<T> = {}): Promise<StreamBehaviorSubject<Uint8Array | undefined>> {
const subject = new StreamBehaviorSubject<any>(undefined);
const file = await this.findOne(path, fields);
const streamContent = async (id: string | number) => {
//it's important to stop writing/appending when we read initially the file
//and then subscribe, otherwise we are hit by a race condition where it can happen
//that we get older subscribeFile messages
const lock = await this.locker.acquireLock('file:' + path);
try {
//read initial content
const data = await this.read(path, fields);
if (subject.isStopped) {
return;
}
subject.next(data);
//it's important that this callback is called right after we returned the subject,
//and subscribed to the subject, otherwise append won't work correctly and might be hit by a race-condition.
const exchangeSubscription = await this.exchange.subscribeFile(id, async (message) => {
if (message.type === 'set') {
const data = await this.read(path, fields);
subject.next(data);
} else if (message.type === 'append') {
//message.size contains the new size after this append has been applied.
//this means we could track to avoid race conditions, but for the moment we use a lock.
//lock is acquired in stream() and makes sure we don't get file appends during
//reading and subscribing
//ConnectionMiddleware converts AlreadyEncoded correct: Meaning it doesnt touch it
subject.append(new AlreadyEncoded('Uint8Array', message.content) as any);
} else if (message.type === 'remove') {
subject.next(undefined);
}
});
subject.addTearDown(() => {
if (exchangeSubscription) {
exchangeSubscription.unsubscribe();
}
});
} finally {
await lock.unlock();
}
};
if (file) {
await streamContent(file.id);
} else {
subject.next(undefined);
const sub = this.liveDatabase.query(this.fileType.classSchema).filter({
path: path,
...fields
}).onCreation().subscribe((id) => {
if (!subject.isStopped) {
streamContent(id);
}
});
subject.addTearDown(() => {
if (sub) sub.unsubscribe();
});
}
return subject;
}
} | the_stack |
import { ImageEdits, ImageFormatTypes } from '../lib';
import { ThumborMapper } from '../thumbor-mapper';
describe('process()', () => {
describe('001/thumborRequest', () => {
it('Should pass if the proper edit translations are applied and in the correct order', () => {
// Arrange
const path = '/fit-in/200x300/filters:grayscale()/test-image-001.jpg';
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapPathToEdits(path);
// Assert
const expectedResult = {
edits: {
resize: {
width: 200,
height: 300,
fit: 'inside'
},
grayscale: true
}
};
expect(edits).toEqual(expectedResult.edits);
});
});
describe('002/resize/fit-in', () => {
it('Should pass if the proper edit translations are applied and in the correct order', () => {
// Arrange
const path = '/fit-in/400x300/test-image-001.jpg';
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapPathToEdits(path);
// Assert
const expectedResult = {
edits: {
resize: {
width: 400,
height: 300,
fit: 'inside'
}
}
};
expect(edits).toEqual(expectedResult.edits);
});
});
describe('003/resize/fit-in/noResizeValues', () => {
it('Should pass if the proper edit translations are applied and in the correct order', () => {
// Arrange
const path = '/fit-in/test-image-001.jpg';
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapPathToEdits(path);
// Assert
const expectedResult = {
edits: {
resize: { fit: 'inside' }
}
};
expect(edits).toEqual(expectedResult.edits);
});
});
describe('004/resize/not-fit-in', () => {
it('Should pass if the proper edit translations are applied and in the correct order', () => {
// Arrange
const path = '/400x300/test-image-001.jpg';
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapPathToEdits(path);
// Assert
const expectedResult = {
edits: {
resize: {
width: 400,
height: 300
}
}
};
expect(edits).toEqual(expectedResult.edits);
});
});
describe('005/resize/widthIsZero', () => {
it('Should pass if the proper edit translations are applied and in the correct order', () => {
// Arrange
const path = '/0x300/test-image-001.jpg';
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapPathToEdits(path);
// Assert
const expectedResult = {
edits: {
resize: {
width: null,
height: 300,
fit: 'inside'
}
}
};
expect(edits).toEqual(expectedResult.edits);
});
});
describe('006/resize/heightIsZero', () => {
it('Should pass if the proper edit translations are applied and in the correct order', () => {
// Arrange
const path = '/400x0/test-image-001.jpg';
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapPathToEdits(path);
// Assert
const expectedResult = {
edits: {
resize: {
width: 400,
height: null,
fit: 'inside'
}
}
};
expect(edits).toEqual(expectedResult.edits);
});
});
describe('007/resize/widthAndHeightAreZero', () => {
it('Should pass if the proper edit translations are applied and in the correct order', () => {
// Arrange
const path = '/0x0/test-image-001.jpg';
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapPathToEdits(path);
// Assert
const expectedResult = {
edits: {
resize: {
width: null,
height: null,
fit: 'inside'
}
}
};
expect(edits).toEqual(expectedResult.edits);
});
});
describe('008/crop', () => {
it('Should pass if the proper crop is applied', () => {
// Arrange
const path = '/10x0:100x200/test-image-001.jpg';
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapPathToEdits(path);
// Assert
const expectedResult = {
edits: {
crop: {
left: 10,
top: 0,
width: 90,
height: 200
}
}
};
expect(edits).toEqual(expectedResult.edits);
});
it('Should ignore crop if invalid dimension values are provided', () => {
// Arrange
const path = '/abc:0:10x200/test-image-001.jpg';
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapPathToEdits(path);
// Assert
const expectedResult = { edits: {} };
expect(edits).toEqual(expectedResult.edits);
});
it('Should pass if the proper crop and resize are applied', () => {
// Arrange
const path = '/10x0:100x200/10x20/test-image-001.jpg';
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapPathToEdits(path);
// Assert
const expectedResult = {
edits: {
crop: {
left: 10,
top: 0,
width: 90,
height: 200
},
resize: {
width: 10,
height: 20
}
}
};
expect(edits).toEqual(expectedResult.edits);
});
});
describe('009/noFileExtension', () => {
it('Should pass when format and quality filters are passed and file does not have extension', () => {
// Arrange
const path = '/filters:format(jpeg)/filters:quality(50)/image_without_extension';
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapPathToEdits(path);
// Assert
const expectedResult = { toFormat: 'jpeg', jpeg: { quality: 50 } };
expect(edits).toEqual(expectedResult);
});
it('Should pass when quality and format filters are passed and file does not have extension', () => {
// Arrange
const path = '/filters:quality(50)/filters:format(jpeg)/image_without_extension';
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapPathToEdits(path);
// Assert
const expectedResult = { toFormat: 'jpeg', jpeg: { quality: 50 } };
expect(edits).toEqual(expectedResult);
});
it('Should pass when quality and format filters are passed and file has extension', () => {
// Arrange
const path = '/filters:quality(50)/filters:format(jpeg)/image_without_extension.png';
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapPathToEdits(path);
// Assert
const expectedResult = { toFormat: 'jpeg', png: { quality: 50 } };
expect(edits).toEqual(expectedResult);
});
});
});
describe('parseCustomPath()', () => {
const OLD_ENV = {
REWRITE_MATCH_PATTERN: '/(filters-)/gm',
REWRITE_SUBSTITUTION: 'filters:'
};
beforeEach(() => {
process.env = { ...OLD_ENV };
});
afterEach(() => {
process.env = OLD_ENV;
});
describe('001/validPath', () => {
it('Should pass if the proper edit translations are applied and in the correct order', () => {
const path = '/filters-rotate(90)/filters-grayscale()/thumbor-image.jpg';
// Act
const thumborMapper = new ThumborMapper();
const result = thumborMapper.parseCustomPath(path);
// Assert
const expectedResult = '/filters:rotate(90)/filters:grayscale()/thumbor-image.jpg';
expect(result).toEqual(expectedResult);
});
});
describe('002/undefinedPath', () => {
it('Should throw an error if the path is not defined', () => {
const path = undefined;
// Act
const thumborMapper = new ThumborMapper();
// Assert
expect(() => {
thumborMapper.parseCustomPath(path);
}).toThrowError(new Error('ThumborMapping::ParseCustomPath::PathUndefined'));
});
});
describe('003/REWRITE_MATCH_PATTERN', () => {
it('Should throw an error if the environment variables are left undefined', () => {
const path = '/filters-rotate(90)/filters-grayscale()/thumbor-image.jpg';
// Act
delete process.env.REWRITE_MATCH_PATTERN;
const thumborMapper = new ThumborMapper();
// Assert
expect(() => {
thumborMapper.parseCustomPath(path);
}).toThrowError(new Error('ThumborMapping::ParseCustomPath::RewriteMatchPatternUndefined'));
});
});
describe('004/REWRITE_SUBSTITUTION', () => {
it('Should throw an error if the path is not defined', () => {
const path = '/filters-rotate(90)/filters-grayscale()/thumbor-image.jpg';
// Act
delete process.env.REWRITE_SUBSTITUTION;
const thumborMapper = new ThumborMapper();
// Assert
expect(() => {
thumborMapper.parseCustomPath(path);
}).toThrowError(new Error('ThumborMapping::ParseCustomPath::RewriteSubstitutionUndefined'));
});
});
});
describe('mapFilter()', () => {
describe('001/autojpg', () => {
it('Should pass if the filter is successfully converted from Thumbor:autojpg()', () => {
// Arrange
const edit = 'filters:autojpg()';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { toFormat: 'jpeg' };
expect(edits).toEqual(expectedResult);
});
});
describe('002/background_color', () => {
it('Should pass if the filter is successfully translated from Thumbor:background_color()', () => {
// Arrange
const edit = 'filters:background_color(ffff)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = {
flatten: { background: { r: 255, g: 255, b: 255 } }
};
expect(edits).toEqual(expectedResult);
});
});
describe('003/blur/singleParameter', () => {
it('Should pass if the filter is successfully translated from Thumbor:blur()', () => {
// Arrange
const edit = 'filters:blur(60)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { blur: 30 };
expect(edits).toEqual(expectedResult);
});
});
describe('004/blur/doubleParameter', () => {
it('Should pass if the filter is successfully translated from Thumbor:blur()', () => {
// Arrange
const edit = 'filters:blur(60, 2)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { blur: 2 };
expect(edits).toEqual(expectedResult);
});
});
describe('005/convolution', () => {
it('Should pass if the filter is successfully translated from Thumbor:convolution()', () => {
// Arrange
const edit = 'filters:convolution(1;2;1;2;4;2;1;2;1,3,true)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = {
convolve: {
width: 3,
height: 3,
kernel: [1, 2, 1, 2, 4, 2, 1, 2, 1]
}
};
expect(edits).toEqual(expectedResult);
});
});
describe('006/equalize', () => {
it('Should pass if the filter is successfully translated from Thumbor:equalize()', () => {
// Arrange
const edit = 'filters:equalize()';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { normalize: true };
expect(edits).toEqual(expectedResult);
});
});
describe('007/fill/resizeUndefined', () => {
it('Should pass if the filter is successfully translated from Thumbor:fill()', () => {
// Arrange
const edit = 'filters:fill(fff)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { resize: { background: { r: 255, g: 255, b: 255 }, fit: 'contain' } };
expect(edits).toEqual(expectedResult);
});
});
describe('008/fill/resizeDefined', () => {
it('Should pass if the filter is successfully translated from Thumbor:fill()', () => {
// Arrange
const edit = 'filters:fill(fff)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
let edits: ImageEdits = { resize: {} };
edits = thumborMapper.mapFilter(edit, filetype, edits);
// Assert
const expectedResult = { resize: { background: { r: 255, g: 255, b: 255 }, fit: 'contain' } };
expect(edits).toEqual(expectedResult);
});
});
describe('009/format/supportedFileType', () => {
it('Should pass if the filter is successfully translated from Thumbor:format()', () => {
// Arrange
const edit = 'filters:format(png)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { toFormat: 'png' };
expect(edits).toEqual(expectedResult);
});
});
describe('010/format/unsupportedFileType', () => {
it('Should return undefined if an accepted file format is not specified', () => {
// Arrange
const edit = 'filters:format(test)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = {};
expect(edits).toEqual(expectedResult);
});
});
describe('011/no_upscale/resizeUndefined', () => {
it('Should pass if the filter is successfully translated from Thumbor:no_upscale()', () => {
// Arrange
const edit = 'filters:no_upscale()';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { resize: { withoutEnlargement: true } };
expect(edits).toEqual(expectedResult);
});
});
describe('012/no_upscale/resizeDefined', () => {
it('Should pass if the filter is successfully translated from Thumbor:no_upscale()', () => {
// Arrange
const edit = 'filters:no_upscale()';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
let edits: ImageEdits = { resize: { height: 400, width: 300 } };
edits = thumborMapper.mapFilter(edit, filetype, edits);
// Assert
const expectedResult = { resize: { height: 400, width: 300, withoutEnlargement: true } };
expect(edits).toEqual(expectedResult);
});
});
describe('013/proportion/resizeDefined', () => {
it('Should pass if the filter is successfully translated from Thumbor:proportion()', () => {
// Arrange
const edit = 'filters:proportion(0.3)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
let edits: ImageEdits = { resize: { height: 200, width: 200 } };
edits = thumborMapper.mapFilter(edit, filetype, edits);
// Assert
const expectedResult = { resize: { height: 60, width: 60 } };
expect(edits).toEqual(expectedResult);
});
});
describe('014/proportion/resizeUndefined', () => {
it('Should pass if the filter is successfully translated from Thumbor:resize()', () => {
// Arrange
const edit = 'filters:proportion(0.3)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
expect(edits.resize).not.toBeUndefined();
});
});
describe('015/quality/jpg', () => {
it('Should pass if the filter is successfully translated from Thumbor:quality()', () => {
// Arrange
const edit = 'filters:quality(50)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { jpeg: { quality: 50 } };
expect(edits).toEqual(expectedResult);
});
});
describe('016/quality/png', () => {
it('Should pass if the filter is successfully translated from Thumbor:quality()', () => {
// Arrange
const edit = 'filters:quality(50)';
const filetype = ImageFormatTypes.PNG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { png: { quality: 50 } };
expect(edits).toEqual(expectedResult);
});
});
describe('017/quality/webp', () => {
it('Should pass if the filter is successfully translated from Thumbor:quality()', () => {
// Arrange
const edit = 'filters:quality(50)';
const filetype = ImageFormatTypes.WEBP;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { webp: { quality: 50 } };
expect(edits).toEqual(expectedResult);
});
});
describe('018/quality/tiff', () => {
it('Should pass if the filter is successfully translated from Thumbor:quality()', () => {
// Arrange
const edit = 'filters:quality(50)';
const filetype = ImageFormatTypes.TIFF;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { tiff: { quality: 50 } };
expect(edits).toEqual(expectedResult);
});
});
describe('019/quality/heif', () => {
it('Should pass if the filter is successfully translated from Thumbor:quality()', () => {
// Arrange
const edit = 'filters:quality(50)';
const filetype = ImageFormatTypes.HEIF;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { heif: { quality: 50 } };
expect(edits).toEqual(expectedResult);
});
});
describe('020/quality/other', () => {
it('Should return undefined if an unsupported file type is provided', () => {
// Arrange
const edit = 'filters:quality(50)';
const filetype = 'xml' as ImageFormatTypes;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = {};
expect(edits).toEqual(expectedResult);
});
});
describe('021/rgb', () => {
it('Should pass if the filter is successfully translated from Thumbor:rgb()', () => {
// Arrange
const edit = 'filters:rgb(10, 10, 10)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { tint: { r: 25.5, g: 25.5, b: 25.5 } };
expect(edits).toEqual(expectedResult);
});
});
describe('022/rotate', () => {
it('Should pass if the filter is successfully translated from Thumbor:rotate()', () => {
// Arrange
const edit = 'filters:rotate(75)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { rotate: 75 };
expect(edits).toEqual(expectedResult);
});
});
describe('023/sharpen', () => {
it('Should pass if the filter is successfully translated from Thumbor:sharpen()', () => {
// Arrange
const edit = 'filters:sharpen(75, 5)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { sharpen: 3.5 };
expect(edits).toEqual(expectedResult);
});
});
describe('024/stretch/default', () => {
it('Should pass if the filter is successfully translated from Thumbor:stretch()', () => {
// Arrange
const edit = 'filters:stretch()';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { resize: { fit: 'fill' } };
expect(edits).toEqual(expectedResult);
});
});
describe('025/stretch/resizeDefined', () => {
it('Should pass if the filter is successfully translated from Thumbor:stretch()', () => {
// Arrange
const edit = 'filters:stretch()';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
let edits: ImageEdits = { resize: { width: 300, height: 400 } };
edits = thumborMapper.mapFilter(edit, filetype, edits);
// Assert
const expectedResult = { resize: { width: 300, height: 400, fit: 'fill' } };
expect(edits).toEqual(expectedResult);
});
});
describe('026/stretch/fit-in', () => {
it('Should pass if the filter is successfully translated from Thumbor:stretch()', () => {
// Arrange
const edit = 'filters:stretch()';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
let edits: ImageEdits = { resize: { fit: 'inside' } };
edits = thumborMapper.mapFilter(edit, filetype, edits);
// Assert
const expectedResult = { resize: { fit: 'inside' } };
expect(edits).toEqual(expectedResult);
});
});
describe('027/stretch/fit-in/resizeDefined', () => {
it('Should pass if the filter is successfully translated from Thumbor:stretch()', () => {
// Arrange
const edit = 'filters:stretch()';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
let edits: ImageEdits = { resize: { width: 400, height: 300, fit: 'inside' } };
edits = thumborMapper.mapFilter(edit, filetype, edits);
// Assert
const expectedResult = { resize: { width: 400, height: 300, fit: 'inside' } };
expect(edits).toEqual(expectedResult);
});
});
describe('028/strip_exif', () => {
it('Should pass if the filter is successfully translated from Thumbor:strip_exif()', () => {
// Arrange
const edit = 'filters:strip_exif()';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { rotate: null };
expect(edits).toEqual(expectedResult);
});
});
describe('029/strip_icc', () => {
it('Should pass if the filter is successfully translated from Thumbor:strip_icc()', () => {
// Arrange
const edit = 'filters:strip_icc()';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { rotate: null };
expect(edits).toEqual(expectedResult);
});
});
describe('030/upscale', () => {
it('Should pass if the filter is successfully translated from Thumbor:upscale()', () => {
// Arrange
const edit = 'filters:upscale()';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = { resize: { fit: 'inside' } };
expect(edits).toEqual(expectedResult);
});
});
describe('031/upscale/resizeNotUndefined', () => {
it('Should pass if the filter is successfully translated from Thumbor:upscale()', () => {
// Arrange
const edit = 'filters:upscale()';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
let edits: ImageEdits = { resize: {} };
edits = thumborMapper.mapFilter(edit, filetype, edits);
// Assert
const expectedResult = { resize: { fit: 'inside' } };
expect(edits).toEqual(expectedResult);
});
});
describe('032/watermark/positionDefined', () => {
it('Should pass if the filter is successfully translated from Thumbor:watermark()', () => {
// Arrange
const edit = 'filters:watermark(bucket,key,100,100,0)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = {
overlayWith: {
bucket: 'bucket',
key: 'key',
alpha: '0',
wRatio: undefined,
hRatio: undefined,
options: {
left: '100',
top: '100'
}
}
};
expect(edits).toEqual(expectedResult);
});
});
describe('033/watermark/positionDefinedByPercentile', () => {
it('Should pass if the filter is successfully translated from Thumbor:watermark()', () => {
// Arrange
const edit = 'filters:watermark(bucket,key,50p,30p,0)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = {
overlayWith: {
bucket: 'bucket',
key: 'key',
alpha: '0',
wRatio: undefined,
hRatio: undefined,
options: {
left: '50p',
top: '30p'
}
}
};
expect(edits).toEqual(expectedResult);
});
});
describe('034/watermark/positionDefinedWrong', () => {
it('Should pass if the filter is successfully translated from Thumbor:watermark()', () => {
// Arrange
const edit = 'filters:watermark(bucket,key,x,x,0)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = {
overlayWith: {
bucket: 'bucket',
key: 'key',
alpha: '0',
wRatio: undefined,
hRatio: undefined,
options: {}
}
};
expect(edits).toEqual(expectedResult);
});
});
describe('035/watermark/ratioDefined', () => {
it('Should pass if the filter is successfully translated from Thumbor:watermark()', () => {
// Arrange
const edit = 'filters:watermark(bucket,key,100,100,0,10,10)';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = {
overlayWith: {
bucket: 'bucket',
key: 'key',
alpha: '0',
wRatio: '10',
hRatio: '10',
options: {
left: '100',
top: '100'
}
}
};
expect(edits).toEqual(expectedResult);
});
});
describe('036/elseCondition', () => {
it('Should pass if undefined is returned for an unsupported filter', () => {
// Arrange
const edit = 'filters:notSupportedFilter()';
const filetype = ImageFormatTypes.JPG;
// Act
const thumborMapper = new ThumborMapper();
const edits = thumborMapper.mapFilter(edit, filetype);
// Assert
const expectedResult = {};
expect(edits).toEqual(expectedResult);
});
});
}); | the_stack |
import MenuItem from "@material-ui/core/MenuItem"
import { mount, ReactWrapper } from "enzyme"
import { createMemoryHistory, MemoryHistory } from "history"
import { SnackbarProvider } from "notistack"
import React from "react"
import { Router } from "react-router"
import { AnalyticsAction } from "./analytics"
import {
cleanupMockAnalyticsCalls,
expectIncrs,
mockAnalyticsCalls,
} from "./analytics_test_helpers"
import { ApiButton, ButtonSet } from "./ApiButton"
import { InstrumentedButton } from "./instrumentedComponents"
import LogActions from "./LogActions"
import { EMPTY_FILTER_TERM, FilterLevel, FilterSource } from "./logfilters"
import OverviewActionBar, {
ActionBarBottomRow,
ActionBarTopRow,
ButtonLeftPill,
CopyButton,
createLogSearch,
Endpoint,
FilterRadioButton,
FilterTermField,
FILTER_FIELD_ID,
FILTER_INPUT_DEBOUNCE,
} from "./OverviewActionBar"
import { EmptyBar, FullBar } from "./OverviewActionBar.stories"
import { disableButton, oneButton, oneResource } from "./testdata"
let history: MemoryHistory
beforeEach(() => {
mockAnalyticsCalls()
history = createMemoryHistory()
history.push({ pathname: "/" })
})
afterEach(() => {
cleanupMockAnalyticsCalls()
jest.useRealTimers()
})
function mountBar(e: JSX.Element) {
return mount(
<Router history={history}>
<SnackbarProvider>{e}</SnackbarProvider>
</Router>
)
}
it("shows endpoints", () => {
let root = mountBar(<FullBar />)
let topBar = root.find(ActionBarTopRow)
expect(topBar).toHaveLength(1)
let endpoints = topBar.find(Endpoint)
expect(endpoints).toHaveLength(2)
})
it("shows pod ID", () => {
const root = mountBar(<FullBar />)
const podId = root.find(ActionBarTopRow).find(CopyButton)
expect(podId).toHaveLength(1)
expect(podId.text()).toContain("my-deadbeef-pod Pod ID") // Hardcoded from test data
})
it("skips the top bar when empty", () => {
let root = mountBar(<EmptyBar />)
let topBar = root.find(ActionBarTopRow)
expect(topBar).toHaveLength(0)
})
it("navigates to warning filter", () => {
let root = mountBar(<FullBar />)
let warnFilter = root
.find(FilterRadioButton)
.filter({ level: FilterLevel.warn })
expect(warnFilter).toHaveLength(1)
let leftButton = warnFilter.find(ButtonLeftPill)
expect(leftButton).toHaveLength(1)
leftButton.simulate("click")
expect(history.location.search).toEqual("?level=warn&source=")
expectIncrs({
name: "ui.web.filterLevel",
tags: { action: AnalyticsAction.Click, level: "warn", source: "" },
})
})
it("navigates to build warning filter", () => {
let root = mountBar(<FullBar />)
let warnFilter = root
.find(FilterRadioButton)
.filter({ level: FilterLevel.warn })
expect(warnFilter).toHaveLength(1)
let sourceItems = warnFilter.find(MenuItem)
expect(sourceItems).toHaveLength(3)
let buildItem = sourceItems.filter({ "data-filter": FilterSource.build })
expect(buildItem).toHaveLength(1)
buildItem.simulate("click")
expect(history.location.search).toEqual("?level=warn&source=build")
})
describe("disabled resource view", () => {
let root: ReactWrapper<any, any>
beforeEach(() => {
const resource = oneResource({
name: "i-am-not-enabled",
disabled: true,
})
const filterSet = {
level: FilterLevel.all,
source: FilterSource.all,
term: EMPTY_FILTER_TERM,
}
const buttonSet: ButtonSet = {
default: [oneButton(0, "i-am-not-enabled")],
toggleDisable: disableButton("i-am-not-enabled", false),
}
root = mountBar(
<OverviewActionBar
resource={resource}
filterSet={filterSet}
buttons={buttonSet}
/>
)
})
it("should display the disable toggle button", () => {
const bottomRowButtons = root.find(ActionBarBottomRow).find(ApiButton)
expect(bottomRowButtons.length).toBeGreaterThanOrEqual(1)
expect(
bottomRowButtons.at(bottomRowButtons.length - 1).prop("uiButton").metadata
?.name
).toEqual("toggle-i-am-not-enabled-disable")
})
it("should NOT display any `default` custom buttons", () => {
const topRowButtons = root.find(ActionBarTopRow).find(ApiButton)
expect(topRowButtons.length).toBe(0)
})
it("should NOT display the filter menu", () => {
const bottomRow = root.find(ActionBarBottomRow)
const filterButtons = bottomRow.find(FilterRadioButton)
const filterTermField = bottomRow.find(FilterTermField)
const logActionsMenu = bottomRow.find(LogActions)
expect(filterButtons).toHaveLength(0)
expect(filterTermField).toHaveLength(0)
expect(logActionsMenu).toHaveLength(0)
})
it("should NOT display endpoint information", () => {
const endpoints = root.find(ActionBarTopRow).find(Endpoint)
expect(endpoints).toHaveLength(0)
})
it("should NOT display podId information", () => {
const podInfo = root.find(ActionBarTopRow).find(CopyButton)
expect(podInfo).toHaveLength(0)
})
})
describe("buttons", () => {
it("shows endpoint buttons", () => {
let root = mountBar(<FullBar />)
let topBar = root.find(ActionBarTopRow)
expect(topBar).toHaveLength(1)
let endpoints = topBar.find(Endpoint)
expect(endpoints).toHaveLength(2)
})
it("disables a button that should be disabled", () => {
let uiButtons = [oneButton(1, "vigoda")]
uiButtons[0].spec!.disabled = true
let filterSet = {
level: FilterLevel.all,
source: FilterSource.all,
term: EMPTY_FILTER_TERM,
}
let root = mountBar(
<OverviewActionBar
filterSet={filterSet}
buttons={{ default: uiButtons }}
/>
)
let topBar = root.find(ActionBarTopRow)
let buttons = topBar.find(InstrumentedButton)
expect(buttons).toHaveLength(1)
expect(buttons.at(0).prop("disabled")).toBe(true)
})
it("renders disable-resource buttons separately from other buttons", () => {
const root = mountBar(<FullBar />)
const topRowButtons = root.find(ActionBarTopRow).find(ApiButton)
expect(topRowButtons).toHaveLength(1)
expect(topRowButtons.at(0).prop("uiButton").metadata?.name).toEqual(
"button2"
)
const bottomRowButtons = root.find(ActionBarBottomRow).find(ApiButton)
expect(bottomRowButtons.length).toBeGreaterThanOrEqual(1)
expect(
bottomRowButtons.at(bottomRowButtons.length - 1).prop("uiButton").metadata
?.name
).toEqual("toggle-vigoda-disable")
})
})
describe("term filter input", () => {
const FILTER_INPUT = `input#${FILTER_FIELD_ID}`
let root: ReactWrapper<any, Readonly<{}>, React.Component<{}, {}, any>>
it("renders with no initial value if there is no existing term filter", () => {
history.push({
pathname: "/",
search: createLogSearch("", {}).toString(),
})
root = mountBar(<FullBar />)
const inputField = root.find(FILTER_INPUT)
expect(inputField.props().value).toBe("")
})
it("renders with an initial value if there is an existing term filter", () => {
history.push({
pathname: "/",
search: createLogSearch("", { term: "bleep bloop" }).toString(),
})
root = mountBar(<FullBar />)
const inputField = root.find(FILTER_INPUT)
expect(inputField.props().value).toBe("bleep bloop")
})
it("changes the global term filter state when its value changes", () => {
jest.useFakeTimers()
root = mountBar(<FullBar />)
const inputField = root.find(FILTER_INPUT)
inputField.simulate("change", { target: { value: "docker" } })
jest.advanceTimersByTime(FILTER_INPUT_DEBOUNCE)
expect(history.location.search.toString()).toEqual("?term=docker")
})
it("uses debouncing to update the global term filter state", () => {
jest.useFakeTimers()
root = mountBar(<FullBar />)
const inputField = root.find(FILTER_INPUT)
inputField.simulate("change", { target: { value: "doc" } })
jest.advanceTimersByTime(FILTER_INPUT_DEBOUNCE / 2)
// The debouncing time hasn't passed yet, so we don't expect to see any changes
expect(history.location.search.toString()).toEqual("")
inputField.simulate("change", { target: { value: "docker" } })
// The debouncing time hasn't passed yet, so we don't expect to see any changes
expect(history.location.search.toString()).toEqual("")
jest.advanceTimersByTime(FILTER_INPUT_DEBOUNCE)
// Since the debouncing time has passed, we expect to see the final
// change reflected
expect(history.location.search.toString()).toEqual("?term=docker")
})
it("retains any current level and source filters when its value changes", () => {
jest.useFakeTimers()
history.push({ pathname: "/", search: "level=warn&source=build" })
root = mountBar(<FullBar />)
const inputField = root.find(FILTER_INPUT)
inputField.simulate("change", { target: { value: "help" } })
jest.advanceTimersByTime(FILTER_INPUT_DEBOUNCE)
expect(history.location.search.toString()).toEqual(
"?level=warn&source=build&term=help"
)
})
})
describe("createLogSearch", () => {
let currentSearch: URLSearchParams
beforeEach(() => (currentSearch = new URLSearchParams()))
it("sets the params that are passed in", () => {
expect(
createLogSearch(currentSearch.toString(), {
level: FilterLevel.all,
term: "find me",
source: FilterSource.build,
}).toString()
).toBe("level=&source=build&term=find+me")
expect(
createLogSearch(currentSearch.toString(), {
level: FilterLevel.warn,
}).toString()
).toBe("level=warn")
expect(
createLogSearch(currentSearch.toString(), {
term: "",
source: FilterSource.runtime,
}).toString()
).toBe("source=runtime&term=")
})
it("overrides params if a new value is defined", () => {
currentSearch.set("level", FilterLevel.warn)
expect(
createLogSearch(currentSearch.toString(), {
level: FilterLevel.error,
}).toString()
).toBe("level=error")
currentSearch.delete("level")
currentSearch.set("level", "a meaningless value")
currentSearch.set("term", "")
expect(
createLogSearch(currentSearch.toString(), {
level: FilterLevel.all,
term: "service",
}).toString()
).toBe("level=&term=service")
})
it("preserves existing params if no new value is defined", () => {
currentSearch.set("source", FilterSource.build)
expect(
createLogSearch(currentSearch.toString(), {
term: "test",
}).toString()
).toBe("source=build&term=test")
})
}) | the_stack |
import { CDK_DEBUG, debugModeEnabled } from './debug';
import { IResolvable, IResolveContext } from './resolvable';
import { captureStackTrace } from './stack-trace';
import { Token } from './token';
/**
* Interface for lazy string producers
*/
export interface IStringProducer {
/**
* Produce the string value
*/
produce(context: IResolveContext): string | undefined;
}
/**
* Interface for (stable) lazy string producers
*/
export interface IStableStringProducer {
/**
* Produce the string value
*/
produce(): string | undefined;
}
/**
* Interface for lazy list producers
*/
export interface IListProducer {
/**
* Produce the list value
*/
produce(context: IResolveContext): string[] | undefined;
}
/**
* Interface for (stable) lazy list producers
*/
export interface IStableListProducer {
/**
* Produce the list value
*/
produce(): string[] | undefined;
}
/**
* Interface for lazy number producers
*/
export interface INumberProducer {
/**
* Produce the number value
*/
produce(context: IResolveContext): number | undefined;
}
/**
* Interface for (stable) lazy number producers
*/
export interface IStableNumberProducer {
/**
* Produce the number value
*/
produce(): number | undefined;
}
/**
* Interface for lazy untyped value producers
*/
export interface IAnyProducer {
/**
* Produce the value
*/
produce(context: IResolveContext): any;
}
/**
* Interface for (stable) lazy untyped value producers
*/
export interface IStableAnyProducer {
/**
* Produce the value
*/
produce(): any;
}
/**
* Options for creating a lazy string token
*/
export interface LazyStringValueOptions {
/**
* Use the given name as a display hint
*
* @default - No hint
*/
readonly displayHint?: string;
}
/**
* Options for creating a lazy list token
*/
export interface LazyListValueOptions {
/**
* Use the given name as a display hint
*
* @default - No hint
*/
readonly displayHint?: string;
/**
* If the produced list is empty, return 'undefined' instead
*
* @default false
*/
readonly omitEmpty?: boolean;
}
/**
* Options for creating lazy untyped tokens
*/
export interface LazyAnyValueOptions {
/**
* Use the given name as a display hint
*
* @default - No hint
*/
readonly displayHint?: string;
/**
* If the produced value is an array and it is empty, return 'undefined' instead
*
* @default false
*/
readonly omitEmptyArray?: boolean;
}
/**
* Lazily produce a value
*
* Can be used to return a string, list or numeric value whose actual value
* will only be calculated later, during synthesis.
*/
export class Lazy {
/**
* Defer the calculation of a string value to synthesis time
*
* Use this if you want to render a string to a template whose actual value depends on
* some state mutation that may happen after the construct has been created.
*
* If you are simply looking to force a value to a `string` type and don't need
* the calculation to be deferred, use `Token.asString()` instead.
*
* @deprecated Use `Lazy.string()` or `Lazy.uncachedString()` instead.
*/
public static stringValue(producer: IStringProducer, options: LazyStringValueOptions = {}) {
return Token.asString(new LazyString(producer, false), options);
}
/**
* Defer the one-time calculation of a string value to synthesis time
*
* Use this if you want to render a string to a template whose actual value depends on
* some state mutation that may happen after the construct has been created.
*
* If you are simply looking to force a value to a `string` type and don't need
* the calculation to be deferred, use `Token.asString()` instead.
*
* The inner function will only be invoked once, and the resolved value
* cannot depend on the Stack the Token is used in.
*/
public static string(producer: IStableStringProducer, options: LazyStringValueOptions = {}) {
return Token.asString(new LazyString(producer, true), options);
}
/**
* Defer the calculation of a string value to synthesis time
*
* Use of this function is not recommended; unless you know you need it for sure, you
* probably don't. Use `Lazy.string()` instead.
*
* The inner function may be invoked multiple times during synthesis. You
* should only use this method if the returned value depends on variables
* that may change during the Aspect application phase of synthesis, or if
* the value depends on the Stack the value is being used in. Both of these
* cases are rare, and only ever occur for AWS Construct Library authors.
*/
public static uncachedString(producer: IStringProducer, options: LazyStringValueOptions = {}) {
return Token.asString(new LazyString(producer, false), options);
}
/**
* Defer the one-time calculation of a number value to synthesis time
*
* Use this if you want to render a number to a template whose actual value depends on
* some state mutation that may happen after the construct has been created.
*
* If you are simply looking to force a value to a `number` type and don't need
* the calculation to be deferred, use `Token.asNumber()` instead.
*
* @deprecated Use `Lazy.number()` or `Lazy.uncachedNumber()` instead.
*/
public static numberValue(producer: INumberProducer) {
return Token.asNumber(new LazyNumber(producer, false));
}
/**
* Defer the one-time calculation of a number value to synthesis time
*
* Use this if you want to render a number to a template whose actual value depends on
* some state mutation that may happen after the construct has been created.
*
* If you are simply looking to force a value to a `number` type and don't need
* the calculation to be deferred, use `Token.asNumber()` instead.
*
* The inner function will only be invoked once, and the resolved value
* cannot depend on the Stack the Token is used in.
*/
public static number(producer: IStableNumberProducer) {
return Token.asNumber(new LazyNumber(producer, true));
}
/**
* Defer the calculation of a number value to synthesis time
*
* Use of this function is not recommended; unless you know you need it for sure, you
* probably don't. Use `Lazy.number()` instead.
*
* The inner function may be invoked multiple times during synthesis. You
* should only use this method if the returned value depends on variables
* that may change during the Aspect application phase of synthesis, or if
* the value depends on the Stack the value is being used in. Both of these
* cases are rare, and only ever occur for AWS Construct Library authors.
*/
public static uncachedNumber(producer: INumberProducer) {
return Token.asNumber(new LazyNumber(producer, false));
}
/**
* Defer the one-time calculation of a list value to synthesis time
*
* Use this if you want to render a list to a template whose actual value depends on
* some state mutation that may happen after the construct has been created.
*
* If you are simply looking to force a value to a `string[]` type and don't need
* the calculation to be deferred, use `Token.asList()` instead.
*
* @deprecated Use `Lazy.list()` or `Lazy.uncachedList()` instead.
*/
public static listValue(producer: IListProducer, options: LazyListValueOptions = {}) {
return Token.asList(new LazyList(producer, false, options), options);
}
/**
* Defer the calculation of a list value to synthesis time
*
* Use of this function is not recommended; unless you know you need it for sure, you
* probably don't. Use `Lazy.list()` instead.
*
* The inner function may be invoked multiple times during synthesis. You
* should only use this method if the returned value depends on variables
* that may change during the Aspect application phase of synthesis, or if
* the value depends on the Stack the value is being used in. Both of these
* cases are rare, and only ever occur for AWS Construct Library authors.
*/
public static uncachedList(producer: IListProducer, options: LazyListValueOptions = {}) {
return Token.asList(new LazyList(producer, false, options), options);
}
/**
* Defer the one-time calculation of a list value to synthesis time
*
* Use this if you want to render a list to a template whose actual value depends on
* some state mutation that may happen after the construct has been created.
*
* If you are simply looking to force a value to a `string[]` type and don't need
* the calculation to be deferred, use `Token.asList()` instead.
*
* The inner function will only be invoked once, and the resolved value
* cannot depend on the Stack the Token is used in.
*/
public static list(producer: IStableListProducer, options: LazyListValueOptions = {}) {
return Token.asList(new LazyList(producer, true, options), options);
}
/**
* Defer the one-time calculation of an arbitrarily typed value to synthesis time
*
* Use this if you want to render an object to a template whose actual value depends on
* some state mutation that may happen after the construct has been created.
*
* @deprecated Use `Lazy.any()` or `Lazy.uncachedAny()` instead.
*/
public static anyValue(producer: IAnyProducer, options: LazyAnyValueOptions = {}): IResolvable {
return new LazyAny(producer, false, options);
}
/**
* Defer the one-time calculation of an arbitrarily typed value to synthesis time
*
* Use this if you want to render an object to a template whose actual value depends on
* some state mutation that may happen after the construct has been created.
*
* The inner function will only be invoked one time and cannot depend on
* resolution context.
*/
public static any(producer: IStableAnyProducer, options: LazyAnyValueOptions = {}): IResolvable {
return new LazyAny(producer, true, options);
}
/**
* Defer the calculation of an untyped value to synthesis time
*
* Use of this function is not recommended; unless you know you need it for sure, you
* probably don't. Use `Lazy.any()` instead.
*
* The inner function may be invoked multiple times during synthesis. You
* should only use this method if the returned value depends on variables
* that may change during the Aspect application phase of synthesis, or if
* the value depends on the Stack the value is being used in. Both of these
* cases are rare, and only ever occur for AWS Construct Library authors.
*/
public static uncachedAny(producer: IAnyProducer, options: LazyAnyValueOptions = {}): IResolvable {
return new LazyAny(producer, false, options);
}
private constructor() {
}
}
interface ILazyProducer<A> {
produce(context: IResolveContext): A | undefined;
}
abstract class LazyBase<A> implements IResolvable {
public readonly creationStack: string[];
private _cached?: A;
constructor(private readonly producer: ILazyProducer<A>, private readonly cache: boolean) {
// Stack trace capture is conditionned to `debugModeEnabled()`, because
// lazies can be created in a fairly thrashy way, and the stack traces are
// large and slow to obtain; but are mostly useful only when debugging a
// resolution issue.
this.creationStack = debugModeEnabled()
? captureStackTrace(this.constructor)
: [`Execute again with ${CDK_DEBUG}=true to capture stack traces`];
}
public resolve(context: IResolveContext) {
if (this.cache) {
return this._cached ?? (this._cached = this.producer.produce(context));
} else {
return this.producer.produce(context);
}
}
public toString() {
return Token.asString(this);
}
/**
* Turn this Token into JSON
*
* Called automatically when JSON.stringify() is called on a Token.
*/
public toJSON(): any {
return '<unresolved-lazy>';
}
}
class LazyString extends LazyBase<string> {
}
class LazyNumber extends LazyBase<number> {
}
class LazyList extends LazyBase<Array<string>> {
constructor(producer: IListProducer, cache: boolean, private readonly options: LazyListValueOptions = {}) {
super(producer, cache);
}
public resolve(context: IResolveContext) {
const resolved = super.resolve(context);
if (resolved?.length === 0 && this.options.omitEmpty) {
return undefined;
}
return resolved;
}
}
class LazyAny extends LazyBase<any> {
constructor(producer: IAnyProducer, cache: boolean, private readonly options: LazyAnyValueOptions = {}) {
super(producer, cache);
}
public resolve(context: IResolveContext) {
const resolved = super.resolve(context);
if (Array.isArray(resolved) && resolved.length === 0 && this.options.omitEmptyArray) {
return undefined;
}
return resolved;
}
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyusd_windowroute_Information {
interface tab_CTITab_Sections {
CTI: DevKit.Controls.Section;
MultipleMatchesTab: DevKit.Controls.Section;
NoMatchesTab: DevKit.Controls.Section;
SingleMatchTab: DevKit.Controls.Section;
}
interface tab_GeneralTab_Sections {
_B27D995D_EA0A_4463_9253_92F19878B844_SECTION_2: DevKit.Controls.Section;
}
interface tab_ResultTab_Sections {
EntitySearch: DevKit.Controls.Section;
OptionsSection: DevKit.Controls.Section;
Result: DevKit.Controls.Section;
Tab: DevKit.Controls.Section;
}
interface tab_tab_5_Sections {
tab_5_section_2: DevKit.Controls.Section;
}
interface tab_CTITab extends DevKit.Controls.ITab {
Section: tab_CTITab_Sections;
}
interface tab_GeneralTab extends DevKit.Controls.ITab {
Section: tab_GeneralTab_Sections;
}
interface tab_ResultTab extends DevKit.Controls.ITab {
Section: tab_ResultTab_Sections;
}
interface tab_tab_5 extends DevKit.Controls.ITab {
Section: tab_tab_5_Sections;
}
interface Tabs {
CTITab: tab_CTITab;
GeneralTab: tab_GeneralTab;
ResultTab: tab_ResultTab;
tab_5: tab_tab_5;
}
interface Body {
Tab: Tabs;
msdyusd_Action: DevKit.Controls.OptionSet;
/** Unique identifier for UII Hosted Application associated with Window Route. */
msdyusd_Application: DevKit.Controls.Lookup;
msdyusd_Condition: DevKit.Controls.String;
msdyusd_DashboardFrame: DevKit.Controls.String;
msdyusd_Destination: DevKit.Controls.OptionSet;
msdyusd_Direction: DevKit.Controls.OptionSet;
/** Unique identifier for Entity Numeric Mapping associated with Window Route. */
msdyusd_Entity: DevKit.Controls.Lookup;
/** Unique identifier for Entity Search associated with Routing Rule. */
msdyusd_EntitySearch: DevKit.Controls.Lookup;
msdyusd_field: DevKit.Controls.String;
/** Unique identifier for UII Hosted Application associated with Window Route. */
msdyusd_From: DevKit.Controls.Lookup;
/** Unique identifier for Entity Search associated with Window Route. */
msdyusd_FromSearch: DevKit.Controls.Lookup;
msdyusd_HideNavBar: DevKit.Controls.Boolean;
msdyusd_HideRibbon: DevKit.Controls.Boolean;
/** Unique identifier for Entity Type associated with Routing Rule. */
msdyusd_InitiatingActivity: DevKit.Controls.Lookup;
/** Unique identifier for Action Call associated with Routing Rule. */
msdyusd_MultipleMatches: DevKit.Controls.Lookup;
msdyusd_MultipleMatchesDecision: DevKit.Controls.OptionSet;
/** The name of the custom entity. */
msdyusd_name: DevKit.Controls.String;
msdyusd_NoMatchDecision: DevKit.Controls.OptionSet;
/** Unique identifier for Action Call associated with Routing Rule. */
msdyusd_NoMatchesAction: DevKit.Controls.Lookup;
msdyusd_Order: DevKit.Controls.Integer;
msdyusd_RouteType: DevKit.Controls.OptionSet;
/** Unique identifier for UII Hosted Application associated with Window Route. */
msdyusd_showtab: DevKit.Controls.Lookup;
/** Unique identifier for Action Call associated with Routing Rule. */
msdyusd_SingleMatchAction: DevKit.Controls.Lookup;
msdyusd_SingleMatchDecision: DevKit.Controls.OptionSet;
msdyusd_SourceFrame: DevKit.Controls.String;
msdyusd_url: DevKit.Controls.String;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
}
interface Footer extends DevKit.Controls.IFooter {
/** Status of the Window Route */
statecode: DevKit.Controls.OptionSet;
}
interface Navigation {
nav_msdyusd_windowroute_agentscriptaction: DevKit.Controls.NavigationItem,
nav_msdyusd_windowroute_ctisearch: DevKit.Controls.NavigationItem
}
interface Grid {
CTISearches: DevKit.Controls.Grid;
}
}
class Formmsdyusd_windowroute_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyusd_windowroute_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 msdyusd_windowroute_Information */
Body: DevKit.Formmsdyusd_windowroute_Information.Body;
/** The Footer section of form msdyusd_windowroute_Information */
Footer: DevKit.Formmsdyusd_windowroute_Information.Footer;
/** The Navigation of form msdyusd_windowroute_Information */
Navigation: DevKit.Formmsdyusd_windowroute_Information.Navigation;
/** The Grid of form msdyusd_windowroute_Information */
Grid: DevKit.Formmsdyusd_windowroute_Information.Grid;
}
class msdyusd_windowrouteApi {
/**
* DynamicsCrm.DevKit msdyusd_windowrouteApi
* @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;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
msdyusd_Action: DevKit.WebApi.OptionSetValue;
/** Unique identifier for UII Hosted Application associated with Window Route. */
msdyusd_Application: DevKit.WebApi.LookupValue;
/** Unique identifier for Agent Script Action associated with Window Route. */
msdyusd_ApplicationAction: DevKit.WebApi.LookupValue;
msdyusd_Condition: DevKit.WebApi.StringValue;
msdyusd_DashboardFrame: DevKit.WebApi.StringValue;
msdyusd_Destination: DevKit.WebApi.OptionSetValue;
msdyusd_Direction: DevKit.WebApi.OptionSetValue;
/** Unique identifier for Entity Numeric Mapping associated with Window Route. */
msdyusd_Entity: DevKit.WebApi.LookupValue;
/** Unique identifier for Entity Search associated with Routing Rule. */
msdyusd_EntitySearch: DevKit.WebApi.LookupValue;
msdyusd_field: DevKit.WebApi.StringValue;
/** Unique identifier for UII Hosted Application associated with Window Route. */
msdyusd_From: DevKit.WebApi.LookupValue;
/** Unique identifier for Entity Search associated with Window Route. */
msdyusd_FromSearch: DevKit.WebApi.LookupValue;
msdyusd_HideNavBar: DevKit.WebApi.BooleanValue;
msdyusd_HideRibbon: DevKit.WebApi.BooleanValue;
/** Unique identifier for Entity Type associated with Routing Rule. */
msdyusd_InitiatingActivity: DevKit.WebApi.LookupValue;
msdyusd_loadarea: DevKit.WebApi.StringValue;
/** Unique identifier for Action Call associated with Routing Rule. */
msdyusd_MultipleMatches: DevKit.WebApi.LookupValue;
msdyusd_MultipleMatchesDecision: DevKit.WebApi.OptionSetValue;
/** The name of the custom entity. */
msdyusd_name: DevKit.WebApi.StringValue;
msdyusd_NoMatchDecision: DevKit.WebApi.OptionSetValue;
/** Unique identifier for Action Call associated with Routing Rule. */
msdyusd_NoMatchesAction: DevKit.WebApi.LookupValue;
msdyusd_Order: DevKit.WebApi.IntegerValue;
msdyusd_RouteType: DevKit.WebApi.OptionSetValue;
/** Unique identifier for UII Hosted Application associated with Window Route. */
msdyusd_showtab: DevKit.WebApi.LookupValue;
/** Unique identifier for Action Call associated with Routing Rule. */
msdyusd_SingleMatchAction: DevKit.WebApi.LookupValue;
msdyusd_SingleMatchDecision: DevKit.WebApi.OptionSetValue;
msdyusd_SourceFrame: DevKit.WebApi.StringValue;
msdyusd_url: DevKit.WebApi.StringValue;
/** Unique identifier for entity instances */
msdyusd_windowrouteId: DevKit.WebApi.GuidValue;
/** 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 for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Status of the Window Route */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Window Route */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyusd_windowroute {
enum msdyusd_Action {
/** 803750000 */
Create_Session,
/** 803750004 */
Default,
/** 803750005 */
In_Place,
/** 803750003 */
None,
/** 803750002 */
Route_Window,
/** 803750001 */
Show_Outside
}
enum msdyusd_Destination {
/** 803750001 */
Entity_Search,
/** 803750000 */
Tab
}
enum msdyusd_Direction {
/** 2 */
Both,
/** 1 */
Inbound,
/** 0 */
Outbound
}
enum msdyusd_MultipleMatchesDecision {
/** 803750002 */
Create_Session_then_Do_Action,
/** 803750000 */
Do_Action,
/** 803750001 */
Next_Rule
}
enum msdyusd_NoMatchDecision {
/** 803750002 */
Create_Session_then_Do_Action,
/** 803750000 */
Do_Action,
/** 803750001 */
Next_Rule
}
enum msdyusd_RouteType {
/** 803750003 */
In_Place,
/** 803750002 */
Menu_Chosen,
/** 803750001 */
OnLoad,
/** 803750000 */
Popup
}
enum msdyusd_SingleMatchDecision {
/** 803750003 */
Create_Session_Load_Match_then_Do_Action,
/** 803750002 */
Create_Session_then_Do_Action,
/** 803750000 */
Do_Action,
/** 803750001 */
Next_Rule
}
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 React, { useState, useEffect, Suspense } from 'react';
import loadable from '@loadable/component';
import { useAB } from '@guardian/ab-react';
import { tests } from '@frontend/web/experiments/ab-tests';
import { ShareCount } from '@frontend/web/components/ShareCount';
import { MostViewedFooter } from '@frontend/web/components/MostViewed/MostViewedFooter/MostViewedFooter';
import { ReaderRevenueLinks } from '@frontend/web/components/ReaderRevenueLinks';
import { SlotBodyEnd } from '@root/src/web/components/SlotBodyEnd/SlotBodyEnd';
import { Links } from '@frontend/web/components/Links';
import { ContributionSlot } from '@frontend/web/components/ContributionSlot';
import { GetMatchNav } from '@frontend/web/components/GetMatchNav';
import { Discussion } from '@frontend/web/components/Discussion';
import { StickyBottomBanner } from '@root/src/web/components/StickyBottomBanner/StickyBottomBanner';
import { SignInGateSelector } from '@root/src/web/components/SignInGate/SignInGateSelector';
import {
getWeeklyArticleHistory,
incrementWeeklyArticleCount,
} from '@guardian/automat-contributions';
import {
QandaAtom,
GuideAtom,
ProfileAtom,
TimelineAtom,
ChartAtom,
PersonalityQuizAtom,
KnowledgeQuizAtom,
} from '@guardian/atoms-rendering';
import { AudioAtomWrapper } from '@frontend/web/components/AudioAtomWrapper';
import { Portal } from '@frontend/web/components/Portal';
import {
HydrateOnce,
HydrateInteractiveOnce,
} from '@frontend/web/components/HydrateOnce';
import { Lazy } from '@frontend/web/components/Lazy';
import { Placeholder } from '@root/src/web/components/Placeholder';
import { decideTheme } from '@root/src/web/lib/decideTheme';
import { decideDisplay } from '@root/src/web/lib/decideDisplay';
import { decideDesign } from '@root/src/web/lib/decideDesign';
import { useOnce } from '@root/src/web/lib/useOnce';
import { initPerf } from '@root/src/web/browser/initPerf';
import { getUser } from '@root/src/web/lib/getUser';
import { FocusStyleManager } from '@guardian/source-foundations';
import {
ArticleDisplay,
ArticleDesign,
storage,
log,
getCookie,
} from '@guardian/libs';
import type { ArticleFormat } from '@guardian/libs';
import { incrementAlreadyVisited } from '@root/src/web/lib/alreadyVisited';
import { incrementDailyArticleCount } from '@frontend/web/lib/dailyArticleCount';
import { hasOptedOutOfArticleCount } from '@frontend/web/lib/contributions';
import { ReaderRevenueDevUtils } from '@root/src/web/lib/readerRevenueDevUtils';
import { buildAdTargeting } from '@root/src/lib/ad-targeting';
import { getSharingUrls } from '@root/src/lib/sharing-urls';
import { updateIframeHeight } from '@root/src/web/browser/updateIframeHeight';
import { ClickToView } from '@root/src/web/components/ClickToView';
import { LabsHeader } from '@root/src/web/components/LabsHeader';
import { EmbedBlockComponent } from '@root/src/web/components/elements/EmbedBlockComponent';
import { UnsafeEmbedBlockComponent } from '@root/src/web/components/elements/UnsafeEmbedBlockComponent';
import type { BrazeMessagesInterface } from '@guardian/braze-components/logic';
import { OphanRecordFunction } from '@guardian/ab-core/dist/types';
import { WeeklyArticleHistory } from '@guardian/automat-contributions/dist/lib/types';
import {
submitComponentEvent,
OphanComponentEvent,
} from '../browser/ophan/ophan';
import { buildBrazeMessages } from '../lib/braze/buildBrazeMessages';
import { CommercialMetrics } from './CommercialMetrics';
import { GetMatchTabs } from './GetMatchTabs';
// *******************************
// ****** Dynamic imports ********
// *******************************
const EditionDropdown = loadable(
() => import('@frontend/web/components/EditionDropdown'),
{
resolveComponent: (module) => module.EditionDropdown,
},
);
const MostViewedRightWrapper = React.lazy(() => {
const { start, end } = initPerf('MostViewedRightWrapper');
start();
return import(
/* webpackChunkName: "MostViewedRightWrapper" */ '@frontend/web/components/MostViewed/MostViewedRight/MostViewedRightWrapper'
).then((module) => {
end();
return { default: module.MostViewedRightWrapper };
});
});
const OnwardsUpper = React.lazy(() => {
const { start, end } = initPerf('OnwardsUpper');
start();
return import(
/* webpackChunkName: "OnwardsUpper" */ '@frontend/web/components/Onwards/OnwardsUpper'
).then((module) => {
end();
return { default: module.OnwardsUpper };
});
});
const OnwardsLower = React.lazy(() => {
const { start, end } = initPerf('OnwardsLower');
start();
return import(
/* webpackChunkName: "OnwardsLower" */ '@frontend/web/components/Onwards/OnwardsLower'
).then((module) => {
end();
return { default: module.OnwardsLower };
});
});
const GetMatchStats = React.lazy(() => {
const { start, end } = initPerf('GetMatchStats');
start();
return import(
/* webpackChunkName: "GetMatchStats" */ '@frontend/web/components/GetMatchStats'
).then((module) => {
end();
return { default: module.GetMatchStats };
});
});
type Props = {
CAPI: CAPIBrowserType;
ophanRecord: OphanRecordFunction;
};
let renderCount = 0;
export const App = ({ CAPI, ophanRecord }: Props) => {
log('dotcom', `App.tsx render #${(renderCount += 1)}`);
const isSignedIn = !!getCookie({ name: 'GU_U', shouldMemoize: true });
const [user, setUser] = useState<UserProfile | null>();
const [brazeMessages, setBrazeMessages] =
useState<Promise<BrazeMessagesInterface>>();
const pageViewId = window.guardian?.config?.ophan?.pageViewId;
const componentEventHandler =
(componentType: any, id: any, action: any) => () => {
const componentEvent: OphanComponentEvent = {
component: {
componentType,
id,
products: [],
labels: [],
},
action,
};
submitComponentEvent(componentEvent, ophanRecord);
};
const [asyncArticleCount, setAsyncArticleCount] =
useState<Promise<WeeklyArticleHistory | undefined>>();
// *******************************
// ** Setup AB Test Tracking *****
// *******************************
const ABTestAPI = useAB();
useEffect(() => {
const allRunnableTests = ABTestAPI.allRunnableTests(tests);
ABTestAPI.trackABTests(allRunnableTests);
ABTestAPI.registerImpressionEvents(allRunnableTests);
ABTestAPI.registerCompleteEvents(allRunnableTests);
log('dotcom', 'AB tests initialised');
}, [ABTestAPI]);
useOnce(() => {
// useOnce means this code will only run once isSignedIn is defined, and only
// run one time
if (isSignedIn) {
getUser(CAPI.config.discussionApiUrl)
.then((theUser) => {
if (theUser) {
setUser(theUser);
log('dotcom', 'State: user set');
}
})
.catch((e) => console.error(`getUser - error: ${e}`));
} else {
setUser(null);
}
}, [isSignedIn, CAPI.config.discussionApiUrl]);
useEffect(() => {
incrementAlreadyVisited();
}, []);
// Log an article view using the Slot Machine client lib
// This function must be called once per article serving.
// We should monitor this function call to ensure it only happens within an
// article pages when other pages are supported by DCR.
useEffect(() => {
const incrementArticleCountsIfConsented = async () => {
const hasOptedOut = await hasOptedOutOfArticleCount();
if (!hasOptedOut) {
incrementDailyArticleCount();
incrementWeeklyArticleCount(
storage.local,
CAPI.pageId,
CAPI.config.keywordIds.split(','),
);
}
};
setAsyncArticleCount(
incrementArticleCountsIfConsented().then(() =>
getWeeklyArticleHistory(storage.local),
),
);
}, [CAPI.pageId, CAPI.config.keywordIds]);
// Ensure the focus state of any buttons/inputs in any of the Source
// components are only applied when navigating via keyboard.
// READ: https://www.theguardian.design/2a1e5182b/p/6691bb-accessibility/t/32e9fb
useEffect(() => {
FocusStyleManager.onlyShowFocusOnTabs();
}, []);
useEffect(() => {
// Used internally only, so only import each function on demand
const loadAndRun =
<K extends keyof ReaderRevenueDevUtils>(key: K) =>
(asExistingSupporter: boolean) =>
import(
/* webpackChunkName: "readerRevenueDevUtils" */ '@frontend/web/lib/readerRevenueDevUtils'
)
.then((utils) =>
utils[key](
asExistingSupporter,
CAPI.shouldHideReaderRevenue,
),
)
/* eslint-disable no-console */
.catch((error) =>
console.log(
'Error loading readerRevenueDevUtils',
error,
),
);
/* eslint-enable no-console */
if (window && window.guardian) {
window.guardian.readerRevenue = {
changeGeolocation: loadAndRun('changeGeolocation'),
showMeTheEpic: loadAndRun('showMeTheEpic'),
showMeTheBanner: loadAndRun('showMeTheBanner'),
showNextVariant: loadAndRun('showNextVariant'),
showPreviousVariant: loadAndRun('showPreviousVariant'),
};
}
}, [CAPI.shouldHideReaderRevenue]);
useOnce(() => {
setBrazeMessages(buildBrazeMessages(CAPI.config.idApiUrl));
}, [CAPI.config.idApiUrl]);
const display: ArticleDisplay = decideDisplay(CAPI.format);
const design: ArticleDesign = decideDesign(CAPI.format);
const pillar: ArticleTheme = decideTheme(CAPI.format);
const format: ArticleFormat = {
display,
design,
theme: pillar,
};
const adTargeting: AdTargeting = buildAdTargeting({
isAdFreeUser: CAPI.isAdFreeUser,
isSensitive: CAPI.config.isSensitive,
videoDuration: CAPI.config.videoDuration,
edition: CAPI.config.edition,
section: CAPI.config.section,
sharedAdTargeting: CAPI.config.sharedAdTargeting,
adUnit: CAPI.config.adUnit,
});
// There are docs on loadable in ./docs/loadable-components.md
const YoutubeBlockComponent = loadable(
() => {
if (
CAPI.elementsToHydrate.filter(
(element) =>
element._type ===
'model.dotcomrendering.pageElements.YoutubeBlockElement',
).length > 0
) {
return import(
'@frontend/web/components/elements/YoutubeBlockComponent'
);
}
return Promise.reject();
},
{
resolveComponent: (module) => module.YoutubeBlockComponent,
},
);
const RichLinkComponent = loadable(
() => {
if (
CAPI.elementsToHydrate.filter(
(element) =>
element._type ===
'model.dotcomrendering.pageElements.RichLinkBlockElement',
).length > 0
) {
return import(
'@frontend/web/components/elements/RichLinkComponent'
);
}
return Promise.reject();
},
{
resolveComponent: (module) => module.RichLinkComponent,
},
);
const InteractiveBlockComponent = loadable(
() => {
if (
CAPI.elementsToHydrate.filter(
(element) =>
element._type ===
'model.dotcomrendering.pageElements.InteractiveBlockElement',
).length > 0
) {
return import(
'@frontend/web/components/elements/InteractiveBlockComponent'
);
}
return Promise.reject();
},
{
resolveComponent: (module) => module.InteractiveBlockComponent,
},
);
const InteractiveContentsBlockElement = loadable(
() => {
if (
CAPI.elementsToHydrate.filter(
(element) =>
element._type ===
'model.dotcomrendering.pageElements.InteractiveContentsBlockElement',
).length > 0
) {
return import(
'@frontend/web/components/elements/InteractiveContentsBlockComponent'
);
}
return Promise.reject();
},
{
resolveComponent: (module) =>
module.InteractiveContentsBlockComponent,
},
);
const CalloutBlockComponent = loadable(
() => {
if (
CAPI.elementsToHydrate.filter(
(element) =>
element._type ===
'model.dotcomrendering.pageElements.CalloutBlockElement',
).length > 0
) {
return import(
'@frontend/web/components/elements/CalloutBlockComponent'
);
}
return Promise.reject();
},
{
resolveComponent: (module) => module.CalloutBlockComponent,
},
);
const DocumentBlockComponent = loadable(
() => {
if (
CAPI.elementsToHydrate.filter(
(element) =>
element._type ===
'model.dotcomrendering.pageElements.DocumentBlockElement',
).length > 0
) {
return import(
'@frontend/web/components/elements/DocumentBlockComponent'
);
}
return Promise.reject();
},
{
resolveComponent: (module) => module.DocumentBlockComponent,
},
);
const MapEmbedBlockComponent = loadable(
() => {
if (
CAPI.elementsToHydrate.filter(
(element) =>
element._type ===
'model.dotcomrendering.pageElements.MapBlockElement',
).length > 0
) {
return import(
'@frontend/web/components/elements/MapEmbedBlockComponent'
);
}
return Promise.reject();
},
{
resolveComponent: (module) => module.MapEmbedBlockComponent,
},
);
const SpotifyBlockComponent = loadable(
() => {
if (
CAPI.elementsToHydrate.filter(
(element) =>
element._type ===
'model.dotcomrendering.pageElements.SpotifyBlockElement',
).length > 0
) {
return import(
'@frontend/web/components/elements/SpotifyBlockComponent'
);
}
return Promise.reject();
},
{
resolveComponent: (module) => module.SpotifyBlockComponent,
},
);
const VideoFacebookBlockComponent = loadable(
() => {
if (
CAPI.elementsToHydrate.filter(
(element) =>
element._type ===
'model.dotcomrendering.pageElements.VideoFacebookBlockElement',
).length > 0
) {
return import(
'@frontend/web/components/elements/VideoFacebookBlockComponent'
);
}
return Promise.reject();
},
{
resolveComponent: (module) => module.VideoFacebookBlockComponent,
},
);
const VineBlockComponent = loadable(
() => {
if (
CAPI.elementsToHydrate.filter(
(element) =>
element._type ===
'model.dotcomrendering.pageElements.VineBlockElement',
).length > 0
) {
return import(
'@frontend/web/components/elements/VineBlockComponent'
);
}
return Promise.reject();
},
{
resolveComponent: (module) => module.VineBlockComponent,
},
);
const InstagramBlockComponent = loadable(
() => {
if (
CAPI.elementsToHydrate.filter(
(element) =>
element._type ===
'model.dotcomrendering.pageElements.InstagramBlockElement',
).length > 0
) {
return import(
'@frontend/web/components/elements/InstagramBlockComponent'
);
}
return Promise.reject();
},
{
resolveComponent: (module) => module.InstagramBlockComponent,
},
);
// We use this function to filter the elementsToHydrate array by a particular
// type so that we can hydrate them. We use T to force the type and keep TS
// content because *we* know that if _type equals a thing then the type is
// guaranteed but TS isn't so sure and needs assurance
const elementsByType = <T extends CAPIElement>(
elements: CAPIElement[],
type: string,
): T[] => elements.filter((element) => element._type === type) as T[];
const youTubeAtoms = elementsByType<YoutubeBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.YoutubeBlockElement',
);
const quizAtoms = elementsByType<QuizAtomBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.QuizAtomBlockElement',
);
const callouts = elementsByType<CalloutBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.CalloutBlockElement',
);
const chartAtoms = elementsByType<ChartAtomBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.ChartAtomBlockElement',
);
const audioAtoms = elementsByType<AudioAtomBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.AudioAtomBlockElement',
);
const qandaAtoms = elementsByType<QABlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.QABlockElement',
);
const guideAtoms = elementsByType<GuideAtomBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.GuideAtomBlockElement',
);
const profileAtoms = elementsByType<ProfileAtomBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.ProfileAtomBlockElement',
);
const timelineAtoms = elementsByType<TimelineBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.TimelineBlockElement',
);
const documents = elementsByType<DocumentBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.DocumentBlockElement',
);
const embeds = elementsByType<EmbedBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.EmbedBlockElement',
);
const instas = elementsByType<InstagramBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.InstagramBlockElement',
);
const maps = elementsByType<MapBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.MapBlockElement',
);
const spotifies = elementsByType<SpotifyBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.SpotifyBlockElement',
);
const facebookVideos = elementsByType<VideoFacebookBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.VideoFacebookBlockElement',
);
const vines = elementsByType<VineBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.VineBlockElement',
);
const richLinks = elementsByType<RichLinkBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.RichLinkBlockElement',
);
const interactiveElements = elementsByType<InteractiveBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.InteractiveBlockElement',
);
const interactiveContentsElement =
elementsByType<InteractiveContentsBlockElement>(
CAPI.elementsToHydrate,
'model.dotcomrendering.pageElements.InteractiveContentsBlockElement',
);
return (
// Do you need to HydrateOnce or do you want a Portal?
//
// HydrateOnce: If your component is server rendered and you're hydrating it with
// more data or making it interactive on the client and you do not need to access
// global application state.
//
// Portal: If your component is not server rendered but a pure client-side component
// and/or you want to access global application state, you want to use a Portal.
//
// Note: Both require a 'root' element that needs to be server rendered.
<React.StrictMode>
{[
CAPI.config.switches.commercialMetrics,
window.guardian.config?.ophan !== undefined,
].every(Boolean) && <CommercialMetrics pageViewId={pageViewId} />}
<Portal rootId="reader-revenue-links-header">
<ReaderRevenueLinks
urls={CAPI.nav.readerRevenueLinks.header}
edition={CAPI.editionId}
dataLinkNamePrefix="nav2 : "
inHeader={true}
remoteHeaderEnabled={CAPI.config.remoteHeader}
pageViewId={pageViewId}
contributionsServiceUrl={CAPI.contributionsServiceUrl}
ophanRecord={ophanRecord}
/>
</Portal>
<HydrateOnce rootId="links-root" waitFor={[user]}>
<Links
supporterCTA={CAPI.nav.readerRevenueLinks.header.supporter}
userId={user ? user.userId : undefined}
idUrl={CAPI.config.idUrl}
mmaUrl={CAPI.config.mmaUrl}
/>
</HydrateOnce>
<HydrateOnce rootId="edition-root">
<EditionDropdown
edition={CAPI.editionId}
dataLinkName="nav2 : topbar : edition-picker: toggle"
/>
</HydrateOnce>
<HydrateOnce rootId="labs-header">
<LabsHeader />
</HydrateOnce>
{CAPI.config.switches.serverShareCounts && (
<Portal rootId="share-count-root">
<ShareCount
ajaxUrl={CAPI.config.ajaxUrl}
pageId={CAPI.pageId}
format={format}
/>
</Portal>
)}
{youTubeAtoms.map((youTubeAtom) => (
<HydrateOnce rootId={youTubeAtom.elementId}>
<YoutubeBlockComponent
format={format}
hideCaption={false}
// eslint-disable-next-line jsx-a11y/aria-role
role="inline"
adTargeting={adTargeting}
isMainMedia={false}
id={youTubeAtom.id}
assetId={youTubeAtom.assetId}
expired={youTubeAtom.expired}
overrideImage={youTubeAtom.overrideImage}
posterImage={youTubeAtom.posterImage}
duration={youTubeAtom.duration}
mediaTitle={youTubeAtom.mediaTitle}
altText={youTubeAtom.altText}
/>
</HydrateOnce>
))}
{interactiveElements.map((interactiveBlock) => (
<HydrateInteractiveOnce rootId={interactiveBlock.elementId}>
<InteractiveBlockComponent
url={interactiveBlock.url}
scriptUrl={interactiveBlock.scriptUrl}
alt={interactiveBlock.alt}
role={interactiveBlock.role}
caption={interactiveBlock.caption}
format={format}
/>
</HydrateInteractiveOnce>
))}
{interactiveContentsElement.map((interactiveBlock) => (
<HydrateOnce rootId={interactiveBlock.elementId}>
<InteractiveContentsBlockElement
subheadingLinks={interactiveBlock.subheadingLinks}
endDocumentElementId={
interactiveBlock.endDocumentElementId
}
/>
</HydrateOnce>
))}
{quizAtoms.map((quizAtom) => (
<HydrateOnce rootId={quizAtom.elementId}>
<>
{quizAtom.quizType === 'personality' && (
<PersonalityQuizAtom
id={quizAtom.id}
questions={quizAtom.questions}
resultBuckets={quizAtom.resultBuckets}
sharingUrls={getSharingUrls(
CAPI.pageId,
CAPI.webTitle,
)}
theme={format.theme}
/>
)}
{quizAtom.quizType === 'knowledge' && (
<KnowledgeQuizAtom
id={quizAtom.id}
questions={quizAtom.questions}
resultGroups={quizAtom.resultGroups}
sharingUrls={getSharingUrls(
CAPI.pageId,
CAPI.webTitle,
)}
theme={format.theme}
/>
)}
</>
</HydrateOnce>
))}
{CAPI.matchUrl && (
<Portal rootId="match-nav">
<GetMatchNav matchUrl={CAPI.matchUrl} />
</Portal>
)}
{CAPI.matchUrl && (
<Portal rootId="match-tabs">
<GetMatchTabs matchUrl={CAPI.matchUrl} format={format} />
</Portal>
)}
{/*
Rules for when to show <ContributionSlot />:
1. shouldHideReaderRevenue is false ("Prevent membership/contribution appeals" is not checked in Composer)
2. The article is not paid content
3. The reader is not signed in
4. An ad blocker has been detected
Note. We specifically say isSignedIn === false so that we prevent render until the cookie has been
checked to avoid flashing this content
*/}
<Portal rootId="top-right-ad-slot">
<ContributionSlot
shouldHideReaderRevenue={CAPI.shouldHideReaderRevenue}
isPaidContent={CAPI.pageType.isPaidContent}
/>
</Portal>
{richLinks.map((richLink, index) => (
<Portal rootId={richLink.elementId}>
<RichLinkComponent
element={richLink}
ajaxEndpoint={CAPI.config.ajaxUrl}
richLinkIndex={index}
/>
</Portal>
))}
{callouts.map((callout) => (
<HydrateOnce rootId={callout.elementId}>
<CalloutBlockComponent callout={callout} format={format} />
</HydrateOnce>
))}
{chartAtoms.map((chartAtom) => (
<HydrateOnce rootId={chartAtom.elementId}>
<ChartAtom id={chartAtom.id} html={chartAtom.html} />
</HydrateOnce>
))}
{audioAtoms.map((audioAtom) => (
<HydrateOnce rootId={audioAtom.elementId}>
<AudioAtomWrapper
id={audioAtom.id}
trackUrl={audioAtom.trackUrl}
kicker={audioAtom.kicker}
title={audioAtom.title}
duration={audioAtom.duration}
pillar={pillar}
contentIsNotSensitive={!CAPI.config.isSensitive}
aCastisEnabled={CAPI.config.switches.acast}
readerCanBeShownAds={!CAPI.isAdFreeUser}
/>
</HydrateOnce>
))}
{qandaAtoms.map((qandaAtom) => (
<HydrateOnce rootId={qandaAtom.elementId}>
<QandaAtom
id={qandaAtom.id}
title={qandaAtom.title}
html={qandaAtom.html}
image={qandaAtom.img}
credit={qandaAtom.credit}
pillar={pillar}
likeHandler={componentEventHandler(
'QANDA_ATOM',
qandaAtom.id,
'LIKE',
)}
dislikeHandler={componentEventHandler(
'QANDA_ATOM',
qandaAtom.id,
'DISLIKE',
)}
expandCallback={componentEventHandler(
'QANDA_ATOM',
qandaAtom.id,
'EXPAND',
)}
/>
</HydrateOnce>
))}
{guideAtoms.map((guideAtom) => (
<HydrateOnce rootId={guideAtom.elementId}>
<GuideAtom
id={guideAtom.id}
title={guideAtom.title}
html={guideAtom.html}
image={guideAtom.img}
credit={guideAtom.credit}
pillar={pillar}
likeHandler={componentEventHandler(
'GUIDE_ATOM',
guideAtom.id,
'LIKE',
)}
dislikeHandler={componentEventHandler(
'GUIDE_ATOM',
guideAtom.id,
'DISLIKE',
)}
expandCallback={componentEventHandler(
'GUIDE_ATOM',
guideAtom.id,
'EXPAND',
)}
/>
</HydrateOnce>
))}
{profileAtoms.map((profileAtom) => (
<HydrateOnce rootId={profileAtom.elementId}>
<ProfileAtom
id={profileAtom.id}
title={profileAtom.title}
html={profileAtom.html}
image={profileAtom.img}
credit={profileAtom.credit}
pillar={pillar}
likeHandler={componentEventHandler(
'PROFILE_ATOM',
profileAtom.id,
'LIKE',
)}
dislikeHandler={componentEventHandler(
'PROFILE_ATOM',
profileAtom.id,
'DISLIKE',
)}
expandCallback={componentEventHandler(
'PROFILE_ATOM',
profileAtom.id,
'EXPAND',
)}
/>
</HydrateOnce>
))}
{timelineAtoms.map((timelineAtom) => (
<HydrateOnce rootId={timelineAtom.elementId}>
<TimelineAtom
id={timelineAtom.id}
title={timelineAtom.title}
events={timelineAtom.events}
description={timelineAtom.description}
pillar={pillar}
likeHandler={componentEventHandler(
'TIMELINE_ATOM',
timelineAtom.id,
'LIKE',
)}
dislikeHandler={componentEventHandler(
'TIMELINE_ATOM',
timelineAtom.id,
'DISLIKE',
)}
expandCallback={componentEventHandler(
'TIMELINE_ATOM',
timelineAtom.id,
'EXPAND',
)}
/>
</HydrateOnce>
))}
{documents.map((document) => (
<HydrateOnce rootId={document.elementId}>
<ClickToView
role={document.role}
isTracking={document.isThirdPartyTracking}
source={document.source}
sourceDomain={document.sourceDomain}
>
<DocumentBlockComponent
embedUrl={document.embedUrl}
height={document.height}
width={document.width}
title={document.title}
source={document.source}
/>
</ClickToView>
</HydrateOnce>
))}
{embeds.map((embed, index) => (
<HydrateOnce rootId={embed.elementId}>
{embed.safe ? (
<ClickToView
role={embed.role}
isTracking={embed.isThirdPartyTracking}
source={embed.source}
sourceDomain={embed.sourceDomain}
>
<EmbedBlockComponent
html={embed.html}
caption={embed.caption}
/>
</ClickToView>
) : (
<ClickToView
role={embed.role}
isTracking={embed.isThirdPartyTracking}
source={embed.source}
sourceDomain={embed.sourceDomain}
onAccept={() =>
updateIframeHeight(
`iframe[name="unsafe-embed-${index}"]`,
)
}
>
<UnsafeEmbedBlockComponent
key={embed.elementId}
html={embed.html}
alt={embed.alt || ''}
index={index}
/>
</ClickToView>
)}
</HydrateOnce>
))}
{instas.map((insta, index) => (
<HydrateOnce rootId={insta.elementId}>
<ClickToView
role={insta.role}
isTracking={insta.isThirdPartyTracking}
source={insta.source}
sourceDomain={insta.sourceDomain}
onAccept={() =>
updateIframeHeight(
`iframe[name="instagram-embed-${index}"]`,
)
}
>
<InstagramBlockComponent
element={insta}
index={index}
/>
</ClickToView>
</HydrateOnce>
))}
{maps.map((map) => (
<HydrateOnce rootId={map.elementId}>
<ClickToView
role={map.role}
isTracking={map.isThirdPartyTracking}
source={map.source}
sourceDomain={map.sourceDomain}
>
<MapEmbedBlockComponent
format={format}
embedUrl={map.embedUrl}
height={map.height}
width={map.width}
caption={map.caption}
credit={map.source}
title={map.title}
/>
</ClickToView>
</HydrateOnce>
))}
{spotifies.map((spotify) => (
<HydrateOnce rootId={spotify.elementId}>
<ClickToView
role={spotify.role}
isTracking={spotify.isThirdPartyTracking}
source={spotify.source}
sourceDomain={spotify.sourceDomain}
>
<SpotifyBlockComponent
embedUrl={spotify.embedUrl}
height={spotify.height}
width={spotify.width}
title={spotify.title}
format={format}
caption={spotify.caption}
credit="Spotify"
/>
</ClickToView>
</HydrateOnce>
))}
{facebookVideos.map((facebookVideo) => (
<HydrateOnce rootId={facebookVideo.elementId}>
<ClickToView
role={facebookVideo.role}
isTracking={facebookVideo.isThirdPartyTracking}
source={facebookVideo.source}
sourceDomain={facebookVideo.sourceDomain}
>
<VideoFacebookBlockComponent
format={format}
embedUrl={facebookVideo.embedUrl}
height={facebookVideo.height}
width={facebookVideo.width}
caption={facebookVideo.caption}
credit={facebookVideo.caption}
title={facebookVideo.caption}
/>
</ClickToView>
</HydrateOnce>
))}
{vines.map((vine) => (
<HydrateOnce rootId={vine.elementId}>
<ClickToView
// No role given by CAPI
// eslint-disable-next-line jsx-a11y/aria-role
role="inline"
isTracking={vine.isThirdPartyTracking}
source={vine.source}
sourceDomain={vine.sourceDomain}
>
<VineBlockComponent element={vine} />
</ClickToView>
</HydrateOnce>
))}
<Portal rootId="most-viewed-right">
<Lazy margin={100}>
<Suspense fallback={<></>}>
<MostViewedRightWrapper
isAdFreeUser={CAPI.isAdFreeUser}
/>
</Suspense>
</Lazy>
</Portal>
{CAPI.matchUrl && (
<Portal rootId="match-stats">
<Lazy margin={300}>
<Suspense fallback={<Placeholder height={800} />}>
<GetMatchStats matchUrl={CAPI.matchUrl} />
</Suspense>
</Lazy>
</Portal>
)}
<Portal rootId="slot-body-end">
<SlotBodyEnd
contentType={CAPI.contentType}
sectionName={CAPI.sectionName}
sectionId={CAPI.config.section}
shouldHideReaderRevenue={CAPI.shouldHideReaderRevenue}
isMinuteArticle={CAPI.pageType.isMinuteArticle}
isPaidContent={CAPI.pageType.isPaidContent}
tags={CAPI.tags}
contributionsServiceUrl={CAPI.contributionsServiceUrl}
brazeMessages={brazeMessages}
idApiUrl={CAPI.config.idApiUrl}
stage={CAPI.stage}
asyncArticleCount={asyncArticleCount}
/>
</Portal>
<Portal
rootId={
isSignedIn
? 'onwards-upper-whensignedin'
: 'onwards-upper-whensignedout'
}
>
<Lazy margin={300}>
<Suspense fallback={<></>}>
<OnwardsUpper
ajaxUrl={CAPI.config.ajaxUrl}
hasRelated={CAPI.hasRelated}
hasStoryPackage={CAPI.hasStoryPackage}
isAdFreeUser={CAPI.isAdFreeUser}
pageId={CAPI.pageId}
isPaidContent={CAPI.config.isPaidContent || false}
showRelatedContent={CAPI.config.showRelatedContent}
keywordIds={CAPI.config.keywordIds}
contentType={CAPI.contentType}
tags={CAPI.tags}
format={format}
pillar={pillar}
edition={CAPI.editionId}
shortUrlId={CAPI.config.shortUrlId}
/>
</Suspense>
</Lazy>
</Portal>
<Portal
rootId={
isSignedIn
? 'onwards-lower-whensignedin'
: 'onwards-lower-whensignedout'
}
>
<Lazy margin={300}>
<Suspense fallback={<></>}>
<OnwardsLower
ajaxUrl={CAPI.config.ajaxUrl}
hasStoryPackage={CAPI.hasStoryPackage}
tags={CAPI.tags}
format={format}
/>
</Suspense>
</Lazy>
</Portal>
<Portal rootId="sign-in-gate">
<SignInGateSelector
format={format}
contentType={CAPI.contentType}
sectionName={CAPI.sectionName}
tags={CAPI.tags}
isPaidContent={CAPI.pageType.isPaidContent}
isPreview={!!CAPI.isPreview}
host={CAPI.config.host}
pageId={CAPI.pageId}
idUrl={CAPI.config.idUrl}
pageViewId={pageViewId}
/>
</Portal>
<HydrateOnce rootId="comments" waitFor={[user]}>
<Discussion
format={format}
discussionApiUrl={CAPI.config.discussionApiUrl}
shortUrlId={CAPI.config.shortUrlId}
isCommentable={CAPI.isCommentable}
user={user || undefined}
discussionD2Uid={CAPI.config.discussionD2Uid}
discussionApiClientHeader={
CAPI.config.discussionApiClientHeader
}
enableDiscussionSwitch={CAPI.config.enableDiscussionSwitch}
isAdFreeUser={CAPI.isAdFreeUser}
shouldHideAds={CAPI.shouldHideAds}
beingHydrated={true}
/>
</HydrateOnce>
<Portal rootId="most-viewed-footer">
<MostViewedFooter
format={format}
sectionName={CAPI.sectionName}
ajaxUrl={CAPI.config.ajaxUrl}
/>
</Portal>
<Portal rootId="reader-revenue-links-footer">
<Lazy margin={300}>
<ReaderRevenueLinks
urls={CAPI.nav.readerRevenueLinks.footer}
edition={CAPI.editionId}
dataLinkNamePrefix="footer : "
inHeader={false}
remoteHeaderEnabled={false}
pageViewId={pageViewId}
contributionsServiceUrl={CAPI.contributionsServiceUrl}
ophanRecord={ophanRecord}
/>
</Lazy>
</Portal>
<Portal rootId="bottom-banner">
<StickyBottomBanner
brazeMessages={brazeMessages}
asyncArticleCount={asyncArticleCount}
contentType={CAPI.contentType}
sectionName={CAPI.sectionName}
section={CAPI.config.section}
tags={CAPI.tags}
isPaidContent={CAPI.pageType.isPaidContent}
isPreview={!!CAPI.isPreview}
shouldHideReaderRevenue={CAPI.shouldHideReaderRevenue}
isMinuteArticle={CAPI.pageType.isMinuteArticle}
isSensitive={CAPI.config.isSensitive}
contributionsServiceUrl={CAPI.contributionsServiceUrl}
idApiUrl={CAPI.config.idApiUrl}
switches={CAPI.config.switches}
/>
</Portal>
</React.StrictMode>
);
}; | the_stack |
import { join } from "path";
import { readFile } from "fs-extra";
import {
LanguageServiceHost, IScriptSnapshot, getDefaultCompilerOptions,
ScriptSnapshot, CompilerOptions, getDefaultLibFilePath, MapLike, createLanguageService,
IndentStyle, SemicolonPreference,
} from "typescript";
import { Nullable, IStringDictionary } from "../../../shared/types";
import { LGraph, LiteGraph } from "litegraph.js";
import { Tools } from "../tools/tools";
import { GraphNode, CodeGenerationOutputType, CodeGenerationExecutionType } from "./node";
import { CodeGenerationUtils } from "./generation/utils";
import {
ICodeGenerationStackFinalOutput, IGlobalCodeGenerationOutput, ICodeGenerationStackOutput,
ICodeGenerationFunctionProperties, ICodeGenerationStack,
} from "./generation/types";
export class GraphCodeGenerator {
private static _Initialized: boolean = false;
private static _Template: string = "";
/**
* Initializes the graph code generator.
*/
public static async Init(): Promise<void> {
if (this._Initialized) { return; }
this._Template = await readFile(join(Tools.GetAppPath(), `assets/scripts/graph.ts`), { encoding: "utf-8" });
}
/**
* Converts the given graph into code that games can execute.
* @param graph defines the reference to the graph that should be converted to code.
*/
public static GenerateCode(graph: LGraph): Nullable<string> {
const result = this._GenerateCode(graph);
if (result.error) { return null; }
const requires = result.nodeOutputs.filter((o) => o.requires);
const modules: IStringDictionary<string[]> = { };
requires.forEach((r) => {
r.requires!.forEach((r) => {
if (!modules[r.module]) { modules[r.module] = []; }
r.classes.forEach((c) => {
if (modules[r.module].indexOf(c) !== -1) { return; }
modules[r.module].push(c);
});
});
});
const imports = Object.keys(modules).map((m) => `import { ${modules[m].join(", ")} } from "${m}"`);
const start = result.output.filter((o) => o.type === CodeGenerationExecutionType.Start);
const update = result.output.filter((o) => o.type === CodeGenerationExecutionType.Update);
const properties = result.output.filter((o) => o.type === CodeGenerationExecutionType.Properties);
const finalStr = this._Template.replace("// ${requires}", imports.join("\n"))
.replace("// ${onStart}", start.map((o) => o.code).join(""))
.replace("// ${onUpdate}", update.map((o) => o.code).join(""))
.replace("// ${properties}", properties.map((o) => o.code).join(""));
const bFinalStr = this._FormatTsCode(finalStr);
return bFinalStr;
}
/**
* Converts the given graph into code.
* @param graph defines the reference to the graph that should be converted to code.
* @param stack defines the current stack of code generation.
*/
public static _GenerateCode(graph: LGraph, stack: ICodeGenerationStack = { }): ICodeGenerationStackFinalOutput {
stack.nodes = stack.nodes ?? graph.computeExecutionOrder(false, true) as GraphNode[];
stack.visited = stack.visited ?? [];
const output: ICodeGenerationStackOutput[] = [];
let previous: IGlobalCodeGenerationOutput;
let index = -1;
// Traverse nodes and generate code
for (const n of stack.nodes) {
index++;
// Check if the
if (n === stack.node) { continue; }
// Check if alreay done
const done = stack.visited!.find((o) => o.id === n.id);
if (done) { continue; }
// Get all inputs
const filteredInputs = n.inputs.filter((i) => i.type !== LiteGraph.EVENT as any);
const inputs: IGlobalCodeGenerationOutput[] = new Array(filteredInputs.length);
for (const linkId in graph.links) {
const link = graph.links[linkId];
if (link.target_id !== n.id || link.type === LiteGraph.EVENT as any) { continue; }
const output = stack.visited!.find((o) => o.id === link.origin_id) ?? stack.nodeOutput;
const inputIndex = filteredInputs.indexOf(filteredInputs.find((fi) => fi.link === link.id)!);
if (!output || inputIndex === -1) { continue; }
if (output.outputsCode && output.outputsCode[link.origin_slot]) {
const outputCode = output.outputsCode[link.origin_slot];
let code = outputCode.code!;
if (outputCode.thisVariable) {
code = `this.${output.variable?.name}`;
if (outputCode.code) {
code = `${code}.${outputCode.code}`;
}
}
inputs[inputIndex] = { ...output, code };
// Simple input
} else {
inputs[inputIndex] = output;
}
}
// Generate the code of the current node
try {
previous = {
id: n.id,
...n.generateCode(...inputs),
} as IGlobalCodeGenerationOutput;
} catch (e) {
return {
output,
nodeOutputs: stack.visited,
error: { node: n, error: e },
};
}
// Register output.
stack.visited!.push(previous);
// Get execution type
const executionType = previous.executionType ?? CodeGenerationExecutionType.Update;
// According to the node type, build the final code string
switch (previous.type) {
// Constant. Nothing to do for constant nodes, just keep the generated code.
case CodeGenerationOutputType.Constant:
break;
// Variable
case CodeGenerationOutputType.Variable:
if (!previous.variable) {
throw new Error(`Variables nodes must provide a ".variable" property.`);
}
previous.variable.name = previous.variable.name.replace(/ /g, "_");
const count = stack.visited!.filter((o) => o.variable?.name === previous.variable?.name);
if (count.length > 1) {
previous.variable.name = `${previous.variable.name}_${count.length}`;
}
previous.code = `this.${previous.variable.name}`;
previous.code = previous.code!.replace(/ \t\n\r/g, "");
const decorator = previous.variable.visibleInInspector ? `@visibleInInspector("${previous.variable.type}", "${previous.variable.name}", ${previous.variable.value.toString()})` : "";
output.push({
code: `${decorator}\npublic ${previous.variable.name}: ${previous.variable.type} = ${previous.variable.value.toString()};\n`,
type: executionType,
});
break;
// Just a function call
case CodeGenerationOutputType.Function:
output.push({ code: previous.code, type: executionType });
break;
// Function with callback, means it has a trigger output
case CodeGenerationOutputType.CallbackFunction:
const callbackResult = this._FunctionCallback(graph, { stack, output, previous, executionType, node: n, nodeIndex: index, inputs });
if (callbackResult?.error) {
return callbackResult;
}
break;
// Condition that as an if / else
case CodeGenerationOutputType.Condition:
case CodeGenerationOutputType.FunctionWithCallback:
const conditionResult = this._Condition(graph, previous.type, { stack, output, previous, executionType, node: n, nodeIndex: index, inputs });
if (conditionResult?.error) {
return conditionResult;
}
break;
}
};
return {
output,
nodeOutputs: stack.visited,
};
}
/**
* Converts the current node as a function callback.
*/
private static _FunctionCallback(graph: LGraph, properties: ICodeGenerationFunctionProperties): Nullable<ICodeGenerationStackFinalOutput> {
const callbackNodes = CodeGenerationUtils.GetAncestors(graph, properties.node, properties.stack.nodes!, properties.nodeIndex);
const callbackResult = this._GenerateCode(graph, {
nodes: callbackNodes,
visited: properties.stack.visited,
node: properties.node,
nodeOutput: {
id: properties.node.id,
...properties.node.generateCode(...properties.inputs),
},
});
if (callbackResult.error) {
return { output: properties.output, nodeOutputs: properties.stack.visited!, error: callbackResult.error };
}
const output = CodeGenerationUtils.DeconstructOutput(callbackResult.output);
properties.previous.code = properties.previous.code.replace(
"{{generated__body}}",
output.common.map((o) => o.code).join("\n"),
);
output.properties.forEach((o) => properties.output.push(o));
properties.output.push({
code: properties.previous.code,
type: properties.executionType,
});
return null;
}
/**
* Converts the current node as a condition.
*/
private static _Condition(graph: LGraph, type: CodeGenerationOutputType, properties: ICodeGenerationFunctionProperties): Nullable<ICodeGenerationStackFinalOutput> {
const yesChildren: GraphNode[] = CodeGenerationUtils.GetChildren(graph, properties.node, 0);
const noChildren: GraphNode[] = CodeGenerationUtils.GetChildren(graph, properties.node, 1);
const yesNodes: GraphNode[] = CodeGenerationUtils.GetAncestors(graph, properties.node, properties.stack.nodes!, properties.nodeIndex, yesChildren);
const noNodes: GraphNode[] = CodeGenerationUtils.GetAncestors(graph, properties.node, properties.stack.nodes!, properties.nodeIndex, noChildren);
const nodeOutput = {
id: properties.node.id,
...properties.node.generateCode(...properties.inputs),
};
const yesResult = this._GenerateCode(graph, {
nodes: yesNodes,
visited: properties.stack.visited,
node: properties.node,
nodeOutput,
});
if (yesResult.error) {
return { output: properties.output, nodeOutputs: properties.stack.visited!, error: yesResult.error };
}
const noResult = this._GenerateCode(graph, {
nodes: noNodes,
visited: properties.stack.visited,
node: properties.node,
nodeOutput,
});
if (noResult.error) {
return { output: properties.output, nodeOutputs: properties.stack.visited!, error: noResult.error };
}
// Build output
const output1 = CodeGenerationUtils.DeconstructOutput(yesResult.output);
const output2 = CodeGenerationUtils.DeconstructOutput(noResult.output);
if (type === CodeGenerationOutputType.Condition) {
if (!yesNodes.length && !noNodes.length) { return null; }
properties.previous.code = properties.previous.code.replace("{{generated__equals__body}}", output1.common.map((o) => o.code).join("\n"));
properties.previous.code = properties.previous.code.replace("{{generated__not__equals__body}}", output2.common.map((o) => o.code).join("\n"));
} else {
properties.previous.code = properties.previous.code.replace("{{generated__body}}", output1.common.map((o) => o.code).join("\n"));
properties.previous.code = properties.previous.code.replace("{{generated__callback__body}}", output2.common.map((o) => o.code).join("\n"));
}
properties.output.push({
code: properties.previous.code,
type: properties.executionType,
});
output1.properties.forEach((o) => properties.output.push(o));
output2.properties.forEach((o) => properties.output.push(o));
return null;
}
/**
* Formats the given TypeScript code.
*/
private static _FormatTsCode(code: string): string {
class _LanguageServiceHost implements LanguageServiceHost {
files: MapLike<IScriptSnapshot> = {};
addFile(fileName: string, text: string) {
this.files[fileName] = ScriptSnapshot.fromString(text);
}
// for ts.LanguageServiceHost
getCompilationSettings = () => getDefaultCompilerOptions();
getScriptFileNames = () => Object.keys(this.files);
getScriptVersion = (_fileName: string) => "0";
getScriptSnapshot = (fileName: string) => this.files[fileName];
getCurrentDirectory = () => process.cwd();
getDefaultLibFileName = (options: CompilerOptions) => getDefaultLibFilePath(options);
}
const host = new _LanguageServiceHost();
host.addFile("graph.ts", code);
const languageService = createLanguageService(host);
const edits = languageService.getFormattingEditsForDocument("graph.ts", {
baseIndentSize: 0,
indentSize: 4,
tabSize: 4,
indentStyle: IndentStyle.Smart,
newLineCharacter: "\r\n",
convertTabsToSpaces: false,
semicolons: SemicolonPreference.Insert,
insertSpaceAfterCommaDelimiter: true,
insertSpaceAfterSemicolonInForStatements: true,
insertSpaceBeforeAndAfterBinaryOperators: true,
insertSpaceAfterConstructor: false,
insertSpaceAfterKeywordsInControlFlowStatements: true,
insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
insertSpaceAfterTypeAssertion: false,
insertSpaceBeforeFunctionParenthesis: false,
placeOpenBraceOnNewLineForFunctions: false,
placeOpenBraceOnNewLineForControlBlocks: false,
insertSpaceBeforeTypeAnnotation: false,
});
edits
.sort((a, b) => a.span.start - b.span.start)
.reverse()
.forEach(edit => {
const head = code.slice(0, edit.span.start);
const tail = code.slice(edit.span.start + edit.span.length);
code = `${head}${edit.newText}${tail}`;
});
return code;
}
} | the_stack |
import { bigNumberify } from 'ethers/utils';
import { ClientType, ColonyClientV5 } from '@colony/colony-js';
import { Address } from '~types/index';
import { log } from '~utils/debug';
import apolloCache from './cache';
import {
UnsubscribeFromColonyMutationResult,
SubscribeToColonyMutationResult,
UserColoniesQuery,
UserColoniesQueryVariables,
UserColoniesDocument,
ColonyMembersWithReputationQuery,
ColonyMembersWithReputationQueryVariables,
ColonyMembersWithReputationDocument,
ProcessedColonyQuery,
ProcessedColonyQueryVariables,
ProcessedColonyDocument,
} from './generated';
import { ContextModule, TEMP_getContext } from '~context/index';
type Cache = typeof apolloCache;
const cacheUpdates = {
unsubscribeFromColony(colonyAddress: Address) {
return (cache: Cache, { data }: UnsubscribeFromColonyMutationResult) => {
/*
* Update the list of subscribed user, with reputation, but only for the
* "All Domains" selection
*/
try {
if (data?.unsubscribeFromColony) {
const {
id: unsubscribedUserWalletAddress,
} = data.unsubscribeFromColony;
const cacheData = cache.readQuery<
ColonyMembersWithReputationQuery,
ColonyMembersWithReputationQueryVariables
>({
query: ColonyMembersWithReputationDocument,
variables: {
colonyAddress,
/*
* We only care about the "All Domains" entry here, since this is
* the only one that displays all the subscribed colony members
*
* The other, actual domains, show all users that have reputation,
* iregardless of wheter they're subscribed to the colony or not
*/
domainId: 0,
},
});
if (cacheData?.colonyMembersWithReputation) {
const { colonyMembersWithReputation } = cacheData;
// eslint-disable-next-line max-len
const updatedUsersWithReputationList = colonyMembersWithReputation.filter(
(userAddress) => !(userAddress === unsubscribedUserWalletAddress),
);
cache.writeQuery<
ColonyMembersWithReputationQuery,
ColonyMembersWithReputationQueryVariables
>({
query: ColonyMembersWithReputationDocument,
data: {
colonyMembersWithReputation: updatedUsersWithReputationList,
},
variables: {
colonyAddress,
domainId: 0,
},
});
}
}
} catch (e) {
log.verbose(e);
log.verbose(
'Cannot update the colony subscriptions cache - not loaded yet',
);
}
/*
* Update the list of colonies the user is subscribed to
* This is in use in the subscribed colonies component(s)
*/
try {
if (data?.unsubscribeFromColony) {
const {
id: unsubscribedUserWalletAddress,
} = data.unsubscribeFromColony;
const cacheData = cache.readQuery<
UserColoniesQuery,
UserColoniesQueryVariables
>({
query: UserColoniesDocument,
variables: {
address: unsubscribedUserWalletAddress,
},
});
if (cacheData?.user?.processedColonies) {
const {
user: { processedColonies },
user,
} = cacheData;
const updatedSubscribedColonies = processedColonies.filter(
(subscribedColony) =>
!(subscribedColony?.colonyAddress === colonyAddress),
);
cache.writeQuery<UserColoniesQuery, UserColoniesQueryVariables>({
query: UserColoniesDocument,
data: {
user: {
...user,
processedColonies: updatedSubscribedColonies,
},
},
variables: {
address: unsubscribedUserWalletAddress,
},
});
}
}
} catch (e) {
log.verbose(e);
log.verbose(
'Cannot update the colony subscriptions cache - not loaded yet',
);
}
};
},
subscribeToColony(colonyAddress: Address) {
return async (cache: Cache, { data }: SubscribeToColonyMutationResult) => {
const apolloClient = TEMP_getContext(ContextModule.ApolloClient);
/*
* Update the list of subscribed user, with reputation, but only for the
* "All Domains" selection
*/
try {
if (data?.subscribeToColony) {
const { id: subscribedUserAddress } = data.subscribeToColony;
const cacheData = cache.readQuery<
ColonyMembersWithReputationQuery,
ColonyMembersWithReputationQueryVariables
>({
query: ColonyMembersWithReputationDocument,
variables: {
colonyAddress,
/*
* We only care about the "All Domains" entry here, since this is
* the only one that displays all the subscribed colony members
*
* The other, actual domains, show all users that have reputation,
* iregardless of wheter they're subscribed to the colony or not
*/
domainId: 0,
},
});
if (cacheData?.colonyMembersWithReputation) {
const { colonyMembersWithReputation } = cacheData;
const updatedUsersWithReputationList = [
...colonyMembersWithReputation,
subscribedUserAddress,
];
cache.writeQuery<
ColonyMembersWithReputationQuery,
ColonyMembersWithReputationQueryVariables
>({
query: ColonyMembersWithReputationDocument,
data: {
colonyMembersWithReputation: updatedUsersWithReputationList,
},
variables: {
colonyAddress,
domainId: 0,
},
});
}
}
} catch (e) {
log.verbose(e);
log.verbose(
'Cannot update the colony subscriptions cache - not loaded yet',
);
}
/*
* Update the list of colonies the user is subscribed to
* This is in use in the subscribed colonies component(s)
*/
try {
if (data?.subscribeToColony) {
const { id: subscribedUserAddress } = data.subscribeToColony;
const cacheData = cache.readQuery<
UserColoniesQuery,
UserColoniesQueryVariables
>({
query: UserColoniesDocument,
variables: {
address: subscribedUserAddress,
},
});
if (cacheData?.user?.processedColonies) {
const {
user: { processedColonies },
user,
} = cacheData;
let newlySubscribedColony;
try {
newlySubscribedColony = cache.readQuery<
ProcessedColonyQuery,
ProcessedColonyQueryVariables
>({
query: ProcessedColonyDocument,
variables: {
address: colonyAddress,
},
});
} catch (error) {
const newColonyQuery = await apolloClient.query<
ProcessedColonyQuery,
ProcessedColonyQueryVariables
>({
query: ProcessedColonyDocument,
variables: {
address: colonyAddress,
},
});
newlySubscribedColony = newColonyQuery?.data;
}
if (newlySubscribedColony?.processedColony) {
const updatedSubscribedColonies = [
...processedColonies,
newlySubscribedColony.processedColony,
];
cache.writeQuery<UserColoniesQuery, UserColoniesQueryVariables>({
query: UserColoniesDocument,
data: {
user: {
...user,
processedColonies: updatedSubscribedColonies,
},
},
variables: {
address: subscribedUserAddress,
},
});
}
}
}
} catch (e) {
log.verbose(e);
log.verbose(
'Cannot update the colony subscriptions cache - not loaded yet',
);
}
};
},
setNativeTokenPermissions() {
return async (cache: Cache) => {
try {
const colonyManager = TEMP_getContext(ContextModule.ColonyManager);
if (colonyManager?.colonyClients?.entries()?.next()?.value) {
const [
colonyAddress,
] = colonyManager.colonyClients.entries().next().value;
const colonyClient = (await colonyManager.getClient(
ClientType.ColonyClient,
colonyAddress,
)) as ColonyClientV5;
let canMintNativeToken = true;
try {
await colonyClient.estimate.mintTokens(bigNumberify(1));
} catch (error) {
canMintNativeToken = false;
}
let canUnlockNativeToken = true;
try {
await colonyClient.estimate.unlockToken();
} catch (error) {
canUnlockNativeToken = false;
}
const data = cache.readQuery<
ProcessedColonyQuery,
ProcessedColonyQueryVariables
>({
query: ProcessedColonyDocument,
variables: {
address: colonyAddress,
},
});
if (data?.processedColony) {
cache.modify({
id: cache.identify(data.processedColony),
fields: {
canMintNativeToken: () => canMintNativeToken,
canUnlockNativeToken: () => canUnlockNativeToken,
},
});
}
}
} catch (e) {
log.verbose(e);
log.verbose(
'Not updating store - cannot set mint native tokens caches',
);
}
};
},
};
export default cacheUpdates; | the_stack |
import * as d3 from "d3";
import { RawData, SeriesGraph } from "./series_graph";
export class CTimeseriesGraph extends SeriesGraph {
protected readonly baseUrl = "/stats/cumulative_timeseries?series_id=";
protected readonly margin = { top: 20, right: 50, bottom: 80, left: 40 };
private readonly bisector = d3.bisector((d: Date) => d.getTime()).left;
// scales
private x: d3.ScaleTime<number, number>;
private y: d3.ScaleLinear<number, number>;
private color: d3.ScaleOrdinal<string, unknown>;
// tooltips things
private tooltip: d3.Selection<HTMLDivElement, unknown, HTMLElement, unknown>;
private tooltipIndex = -1; // used to prevent unnecessary tooltip updates
private tooltipLine: d3.Selection<SVGLineElement, unknown, HTMLElement, any>;
private tooltipDots: d3.Selection<
Element | SVGCircleElement | d3.EnterElement | Document | Window | null,
unknown,
SVGGElement,
any
>;
// data
// eslint-disable-next-line camelcase
private data: { ex_id: string, ex_data: { bin: d3.Bin<Date, Date>, cSum: number }[] }[] = [];
private maxSum: number; // largest y-value = either subscribed students or max value
private dateArray: Date[]; // an array of dates from minDate -> maxDate (in days)
/**
* Draws the graph's svg (and other) elements on the screen
* No more data manipulation is done in this function
* @param {Boolean} animation Whether to play animations (disabled on a resize redraw)
*/
protected override draw(animation=true): void {
this.height = 400;
super.draw();
const minDate = this.dateArray[0];
const maxDate = this.dateArray[this.dateArray.length - 1];
// Y scale
this.y = d3.scaleLinear()
.domain([0, 1])
.range([this.innerHeight, 0]);
// Y axis
this.graph.append("g")
.call(d3.axisLeft(this.y).ticks(5, ".0%"));
// X scale
this.x = d3.scaleTime()
.domain([minDate, maxDate])
.range([0, this.innerWidth]);
// add x-axis
this.graph.append("g")
.attr("transform", `translate(0, ${this.y(0)})`)
.call(d3.axisBottom(this.x)
.tickValues(this.dateArray.filter((e, i, a) => {
if (a.length < 10) return true;
if (i === 0 || i === a.length - 1) return true;
if (i % Math.floor(a.length / 10) === 0) return true;
return false;
}))
.tickFormat(d3.timeFormat(I18n.t("date.formats.weekday_short")))
);
// Color scale
this.color = d3.scaleOrdinal()
.range(d3.schemeDark2)
.domain(this.exOrder);
// Tooltip
this.tooltip = this.container.append("div")
.attr("class", "d3-tooltip")
.attr("pointer-events", "none")
.style("opacity", 0)
.style("z-index", 5);
this.tooltipLine = this.graph.append("line")
.attr("y1", 0)
.attr("y2", this.innerHeight)
.attr("pointer-events", "none")
.attr("stroke", "currentColor")
.attr("opacity", 0);
this.tooltipDots = this.graph.selectAll(".tooltipDot")
.data(this.data, ex => ex.ex_id)
.join("circle")
.attr("class", "tooltipDot")
.attr("r", 4)
.attr("opacity", 0)
.style("fill", ex => this.color(ex.ex_id) as string);
this.legendInit();
// add lines
// eslint-disable-next-line camelcase
this.data.forEach(({ ex_data, ex_id }) => {
const exGroup = this.graph.append("g");
exGroup.selectAll("path")
// I have no idea why this is necessary but removing the '[]' breaks everything
// eslint-disable-next-line camelcase
.data([ex_data])
.join("path")
.style("stroke", this.color(ex_id) as string)
.style("fill", "none")
.attr("d", d3.line()
.x(d => this.x(d.bin["x0"]))
.y(this.innerHeight)
.curve(d3.curveMonotoneX)
)
.transition().duration(animation ? 500 : 0)
.attr("d", d3.line()
.x(d => this.x(d.bin["x0"]))
.y(d => this.y(d.cSum / this.maxSum))
.curve(d3.curveMonotoneX)
);
});
this.svg.on("mouseover", e => this.tooltipOver(e));
this.svg.on("mousemove", e => this.tooltipMove(e));
this.svg.on("mouseleave", () => this.tooltipOut());
}
/**
* Transforms the data from the server into a form usable by the graph.
*
* @param {RawData} raw The unprocessed return value of the fetch
*/
// eslint-disable-next-line camelcase
protected override processData({ data, exercises, student_count }: RawData): void {
// eslint-disable-next-line camelcase
data as { ex_id: number, ex_data: (string | Date)[] }[];
this.parseExercises(exercises, data.map(ex => ex.ex_id));
data.forEach(ex => {
// convert dates form strings to actual date objects
ex.ex_data = ex.ex_data.map((d: string) => new Date(d));
});
let [minDate, maxDate] = d3.extent(data.flatMap(ex => ex.ex_data)) as Date[];
minDate = d3.timeDay.offset(new Date(minDate), -1); // start 1 day earlier from 0
maxDate = new Date(maxDate);
minDate.setHours(0, 0, 0, 0); // set start to midnight
maxDate.setHours(23, 59, 59, 99); // set end right before midnight
this.dateArray = d3.timeDays(minDate, maxDate);
const threshold = d3.scaleTime()
.domain([minDate.getTime(), maxDate.getTime()])
.ticks(d3.timeDay);
// eslint-disable-next-line camelcase
this.maxSum = student_count; // max value
// bin data per day (for each exercise)
data.forEach(ex => {
const binned = d3.bin()
.value(d => d.getTime())
.thresholds(threshold)
.domain([minDate.getTime(), maxDate.getTime()])(ex.ex_data);
// combine bins with cumsum of the bins
const cSums = d3.cumsum(binned, d => d.length);
this.data.push({
ex_id: String(ex.ex_id),
ex_data: binned.map((bin, i) => ({ bin: bin, cSum: cSums[i] }))
});
// if 'students' undefined calculate max value from data
this.maxSum = Math.max(cSums[cSums.length - 1], this.maxSum);
});
}
// utility functions
/**
* Calculates the closest data point near the x-position of the mouse.
*
* @param {number} mx The x position of the mouse cursor
* @return {Object} The index of the cursor in the date array + the date of that position
*/
private bisect(mx: number): { "date": Date; "i": number } {
const min = this.dateArray[0];
const max = this.dateArray[this.dateArray.length - 1];
if (!this.dateArray) { // probably not necessary, but just to be safe
return { "date": new Date(0), "i": 0 };
}
const date = this.x.invert(mx);
const index = this.bisector(this.dateArray, date, 1);
const a = index > 0 ? this.dateArray[index - 1] : min;
const b = index < this.dateArray.length ? this.dateArray[index] : max;
if (
index < this.dateArray.length &&
date.getTime() - a.getTime() > b.getTime() - date.getTime()
) {
return { "date": b, "i": index };
} else {
return { "date": a, "i": index - 1 };
}
}
/**
* Hide tooltips on mouse out
*/
private tooltipOut(): void {
this.tooltipIndex = -1;
this.tooltip.style("opacity", 0);
this.tooltipLine.attr("opacity", 0);
this.tooltipDots.attr("opacity", 0);
}
/**
* Show tooltip with data for the closest data point
*
* @param {unknown} e The mouse event
*/
private tooltipOver(e: unknown): void {
if (!this.dateArray) {
return;
}
// find insert point in array
const { date, i } = this.bisect(d3.pointer(e, this.graph.node())[0]);
this.tooltip
.html(this.tooltipText(i))
.style("left", `${this.x(date) + this.margin.left + 5}px`)
.style("top", `${this.margin.top}px`);
this.tooltipLine
.attr("x1", this.x(date))
.attr("x2", this.x(date));
this.tooltipDots
.attr("cx", this.x(date))
.attr("cy", ex => this.y(ex.ex_data[i].cSum / this.maxSum));
}
/**
* Show tooltip with data for the closest data point
*
* @param {unknown} e The mouse event
*/
private tooltipMove(e: unknown): void {
if (!this.dateArray) {
return;
}
// find insert point in array
const { date, i } = this.bisect(d3.pointer(e, this.graph.node())[0]);
if (i !== this.tooltipIndex) { // check if tooltip position changed
this.tooltipIndex = i;
this.tooltip
.html(this.tooltipText(i))
.transition()
.duration(100)
.style("opacity", 0.9)
.style("left", `${this.x(date) + this.margin.left + 5}px`)
.style("top", `${this.margin.top}px`);
this.tooltipLine
.transition()
.duration(100)
.attr("opacity", 1)
.attr("x1", this.x(date))
.attr("x2", this.x(date));
this.tooltipDots
.transition()
.duration(100)
.attr("opacity", 1)
.attr("cx", this.x(date))
.attr("cy", ex => this.y(ex.ex_data[i].cSum / this.maxSum));
}
}
private tooltipText(i: number): string {
let result = `<b>${this.longDateFormat(this.dateArray[this.tooltipIndex])}</b>`;
this.exOrder.forEach(e => {
const ex = this.data.find(ex => ex.ex_id === e);
result += `<br><span style="color: ${this.color(e)}">◼</span> ${d3.format(".1%")(ex.ex_data[i].cSum / this.maxSum)}
(${ex.ex_data[i].cSum}/${this.maxSum})`;
});
return result;
}
private legendInit(): void {
// calculate legend element offsets
const legend = this.container
.append("div")
.attr("class", "legend")
.style("margin-top", "-50px")
.selectAll("div")
.data(this.exOrder)
.enter()
.append("div")
.attr("class", "legend-item");
legend
.append("div")
.attr("class", "legend-box")
.style("background", exId => this.color(exId));
legend
.append("span")
.attr("class", "legend-text")
.text(exId => this.exMap[exId])
.style("color", "currentColor")
.style("font-size", `${this.fontSize}px`);
}
} | the_stack |
import {fixJob} from "./job-adapter";
import {V1CommandLineToolModel} from "cwlts/models/v1.0";
import {CommandLineTool, CommandInputParameter} from "cwlts/mappings/v1.0";
import {JobHelper} from "cwlts/models/helpers/JobHelper";
import {CommandLineToolModel} from "cwlts/models";
import objectContaining = jasmine.objectContaining;
import any = jasmine.any;
describe("JobAdapter", () => {
it("should generate all values for an empty job", () => {
const model = makeToolWithInputs([
{id: "file_id", type: "File"},
{id: "string_id", type: "string"},
]);
const mockData = JobHelper.getJobInputs(model);
const adapted = fixJob({}, model);
expect(adapted).toEqual(objectContaining(mockData));
});
it("should remove entries for non-existing inputs", () => {
const model = makeToolWithInputs([
{id: "string_id", type: "string"}
]);
const mockData = JobHelper.getJobInputs(model);
const adapted = fixJob({foo: "bar"}, model);
expect(adapted).toEqual(objectContaining(mockData));
});
it("should add missing keys", () => {
const model = makeToolWithInputs([
{id: "boolean_id", type: "boolean"},
{id: "string_id", type: "string"}
]);
const mockData = JobHelper.getJobInputs(model);
expect(fixJob({
boolean_id: false
}, model)).toEqual(objectContaining({
boolean_id: false,
string_id: mockData.string_id
}));
});
describe("integer handling", () => {
it("should make non-numeric types ints", () => {
const tool = makeToolWithInputs([{id: "a", type: "int"}]);
const adapted = makeMapper("a", tool);
// Convertibles
expect(adapted(5.13)).toEqual(5, "Failed to convert float to int");
expect(adapted("42")).toEqual(42, "Failed to convert a numeric string to int");
expectAll(adapted, "foo", [], {}, null).toEqual(any(Number));
});
});
describe("float/double handling", () => {
it("should make non-numeric types floats", () => {
const tool = makeToolWithInputs([{id: "a", type: "float"}]);
const adapted = makeMapper("a", tool);
expect(adapted(5.13)).toEqual(5.13, "Failed to preserve float as-is");
expect(adapted("42.15")).toEqual(42.15, "Failed to convert a numeric string to float");
expectAll(adapted, "foo", [], {}, null).toEqual(any(Number));
})
});
describe("boolean", () => {
let tool, parse;
beforeEach(() => {
tool = makeToolWithInputs([{id: "a", type: "boolean"}]);
parse = makeMapper("a", tool);
});
it("should preserve only pure booleans", () => {
expect(parse(true)).toBe(true);
expect(parse(false)).toBe(false);
});
it("should make booleans from other type", () => {
expectAll(parse, "foo", [], {}, null, undefined).toBe(true);
});
});
it("should adapt strings", () => {
const tool = makeToolWithInputs([{id: "foo", type: "string"}]);
const parse = makeMapper("foo", tool);
expect(parse("something")).toEqual("something");
expectAll(parse, 13, [], {}, null, undefined).toEqual(any(String));
});
describe("files", () => {
let tool, adapted;
beforeEach(() => {
tool = makeToolWithInputs([{id: "foo", type: "File"}]);
adapted = makeMapper("foo", tool);
});
it("should keep a valid file shape", () => {
const minimal = {class: "File", path: "hello world"};
expect(adapted(minimal)).toBe(minimal);
});
it("should regenerate file type without a path", () => {
expect(adapted({class: "File"}).path).toEqual(any(String));
expect(adapted({class: "File", path: ""}).path.length).toBeGreaterThan(0);
});
it("should not accept a directory", () => {
expect(adapted({class: "Directory"})).toEqual(objectContaining({class: "File"}));
});
it("should convert other types", () => {
expectAll(adapted, {class: "Directory"}, "foo", 1, true, [], undefined, null).toEqual(objectContaining({class: "File"}));
});
});
describe("directories", () => {
let tool, adapted;
beforeEach(() => {
tool = makeToolWithInputs([{id: "foo", type: "Directory"}]);
adapted = makeMapper("foo", tool);
});
it("should keep a valid directory shape", () => {
const minimal = {class: "Directory", path: "hello world"};
expect(adapted(minimal)).toBe(minimal);
});
it("should regenerate directory type without a path", () => {
expect(adapted({class: "Directory"}).path).toEqual(any(String));
expect(adapted({class: "Directory", path: ""}).path.length).toBeGreaterThan(0);
});
it("should not accept a file", () => {
expect(adapted({class: "File"})).toEqual(objectContaining({class: "Directory"}));
});
it("should convert other types", () => {
expectAll(adapted, {class: "File"}, "foo", 1, true, [], undefined, null).toEqual(objectContaining({class: "Directory"}));
});
});
describe("arrays", () => {
it("should regenerate non-array types", () => {
const tool = makeToolWithInputs([{id: "foo", type: "string[]"}]);
const adapted = makeMapper("foo", tool);
expectAll(adapted, 10, "nein", {}, false, null, undefined).toEqual(any(Array));
});
describe("individual non-conforming value regeneration", () => {
it("should regenerate strings", () => {
const tool = makeToolWithInputs([{id: "foo", type: "string[]"}]);
const adapted = makeMapper("foo", tool);
const val = ["foo", 1, "bar", {}, true];
expect(adapted(val)).toEqual(["foo", any(String), "bar", any(String), any(String)]);
});
it("should regenerate numbers", () => {
const tool = makeToolWithInputs([{id: "foo", type: "int[]"}]);
const adapted = makeMapper("foo", tool);
const val = ["foo", 1, {}, true];
expect(adapted(val)).toEqual([any(Number), 1, any(Number), any(Number)]);
});
it("should regenerate files", () => {
const tool = makeToolWithInputs([{id: "foo", type: "File[]"}]);
const adapted = makeMapper("foo", tool);
const val = [
"foo", 3, {}, [], true,
{class: "File"},
{class: "Directory", path: "./"},
{class: "File", path: "preserved-file-path", size: 2000},
];
const fileStructure = {class: "File"};
expect(adapted(val)).toEqual([
objectContaining(fileStructure),
objectContaining(fileStructure),
objectContaining(fileStructure),
objectContaining(fileStructure),
objectContaining(fileStructure),
objectContaining(fileStructure),
objectContaining(fileStructure),
objectContaining({class: "File", path: "preserved-file-path", size: 2000}),
]);
});
it("should regenerate directories", () => {
const tool = makeToolWithInputs([{id: "foo", type: "Directory[]"}]);
const adapted = makeMapper("foo", tool);
const val = [
"foo", 3, {}, [], true,
{class: "Directory"},
{class: "File", path: "./myFile.txt"},
{class: "Directory", path: "preserved-directory-path", size: 2000},
];
const dirStructure = {class: "Directory"};
expect(adapted(val)).toEqual([
objectContaining(dirStructure),
objectContaining(dirStructure),
objectContaining(dirStructure),
objectContaining(dirStructure),
objectContaining(dirStructure),
objectContaining(dirStructure),
objectContaining(dirStructure),
objectContaining({class: "Directory", path: "preserved-directory-path", size: 2000}),
]);
});
it("should regenerate enums", () => {
const symbols = ["foo", "bar"];
const tool = makeToolWithInputs([{
id: "alpha", type: {
type: "array",
items: {type: "enum", symbols}
},
}]);
const parse = makeMapper("alpha", tool);
expect(parse(["foo", "bar", "baz", null])).toEqual(["foo", "bar", "foo", "foo"]);
});
});
});
describe("enums", () => {
let tool, parse;
beforeEach(() => {
tool = makeToolWithInputs([{id: "alpha", type: {type: "enum", symbols: ["foo", "bar"]}}]);
parse = makeMapper("alpha", tool);
});
it("should keep a valid symbol", () => {
expect(parse("bar")).toEqual("bar");
expect(parse("foo")).toEqual("foo");
expect(parse(null)).toEqual("foo");
});
it("should replace invalid symbols", () => {
expect(parse("moo")).toEqual("foo");
});
});
describe("maps", () => {
let tool, parse;
beforeEach(() => {
tool = makeToolWithInputs([{id: "alpha", type: "map"}]);
parse = makeMapper("alpha", tool);
});
it("should work valid map structures", () => {
const empty = {};
expect(parse(empty)).toEqual(empty);
const standardMap = {foo: "bar", baz: "15"};
expect(parse(standardMap)).toEqual(objectContaining(standardMap));
});
it("should convert non-maps to maps", () => {
expectAll(parse, 15, "str", [], false).toEqual(any(Object));
});
it("should serialize non-literal map values", () => {
const nonLiteral = {
arr: ["one", "two"],
obj: {one: 2}
};
expect(parse(nonLiteral)).toEqual(objectContaining({
arr: "one,two",
obj: `{"one":2}`
}));
});
});
describe("records", () => {
it("should work in ideal case", () => {
const tool = makeToolWithInputs([{
id: "rec",
type: {
type: "record",
fields: [
{name: "fl", type: "File"},
{name: "str", type: "string"},
{name: "arr", type: "int[]"},
{name: "en", type: {type: "enum", symbols: ["foo", "bar"]}}
]
}
}]);
const parse = makeMapper("rec", tool);
const goodRecord = {
fl: {class: "File", path: "./fl.txt"},
arr: [4, 12],
str: "hello",
en: "bar"
};
expect(parse(goodRecord)).toEqual(objectContaining(goodRecord));
});
it("should regenerate if not an object", () => {
const tool = makeToolWithInputs([{
id: "rec",
type: {type: "record", fields: [{name: "fl", type: "File"}]}
}]);
const parse = makeMapper("rec", tool);
expect(parse("hello").fl).toEqual(objectContaining({class: "File"}));
});
it("should remove keys that don't exist in record", () => {
const tool = makeToolWithInputs([{
id: "rec",
type: {
type: "record", fields: [
{name: "alpha", type: "string"},
{name: "beta", type: "int"},
]
}
}]);
const parse = makeMapper("rec", tool);
const parsed = parse({alpha: "a", gamma: 12, beta: 3, delta: 100});
expect(parsed).not.toEqual(objectContaining({gamma: 12, delta: 100}));
expect(parsed).toEqual(objectContaining({alpha: "a", beta: 3}));
});
it("should replace non-conforming keys", () => {
const tool = makeToolWithInputs([{
id: "rec", type: {
type: "record", fields: [
{name: "alpha", type: "string"},
{name: "beta", type: "int"},
]
}
}]);
const parse = makeMapper("rec", tool);
expect(parse({
alpha: "str",
beta: "str"
})).toEqual(objectContaining({
alpha: any(String),
beta: any(Number)
}));
});
describe("adapting nested structure", () => {
it("int[]", () => {
const tool = makeToolWithInputs([{
id: "rec", type: {
type: "record", fields: [{
name: "intArr", type: "int[]"
}]
}
}]);
const parse = makeMapper("rec", tool);
const parsed = parse({intArr: [2, 1, true, "foo", {}]});
expect(parsed.intArr).toEqual([2, 1, any(Number), any(Number), any(Number)])
});
it("enum[]", () => {
const tool = makeToolWithInputs([{
id: "rec", type: {
type: "record", fields: [{
name: "enumArr", type: {
type: "array",
items: {
type: "enum",
symbols: ["foo", "bar", "baz"]
}
}
}]
}
}]);
const parse = makeMapper("rec", tool);
expect(parse({enumArr: ["foo", "baz", "baz", "bar"]}).enumArr).toEqual(["foo", "baz", "baz", "bar"]);
expect(parse({enumArr: ["moo", "yay"]}).enumArr).toEqual(["foo", "foo"]);
expect(parse({enumArr: ["foo", "moo", "bar", "yar"]}).enumArr).toEqual(["foo", "foo", "bar", "foo"]);
});
it("enum[]", () => {
const tool = makeToolWithInputs([{
id: "rec", type: {
type: "record", fields: [{
name: "enumArr", type: {
type: "array",
items: {
type: "enum",
symbols: ["foo", "bar", "baz"]
}
}
}]
}
}]);
const parse = makeMapper("rec", tool);
expect(parse({enumArr: ["foo", "baz", "baz", "bar"]}).enumArr).toEqual(["foo", "baz", "baz", "bar"]);
expect(parse({enumArr: ["moo", "yay"]}).enumArr).toEqual(["foo", "foo"]);
expect(parse({enumArr: ["foo", "moo", "bar", "yar"]}).enumArr).toEqual(["foo", "foo", "bar", "foo"]);
});
it("record[]", () => {
const tool = makeToolWithInputs([{
id: "rec", type: {
type: "record", fields: [{
name: "nestedRecord", type: {
type: "array",
items: {
type: "record",
fields: [{
name: "file",
type: "File"
}, {
name: "bool",
type: "boolean"
}, {
name: "enum",
type: {type: "enum", symbols: ["foo", "bar"]}
}]
}
}
}]
}
}]);
const parse = makeMapper("rec", tool);
expect(parse({
nestedRecord: [
"invalid",
{file: {class: "File", path: "preserved"}, bool: false, enum: "moo"},
{file: {class: "File", path: "preserved-2"}, bool: 123, enum: "bar"},
[],
{file: {class: "File"}}
]
}).nestedRecord).toEqual([
objectContaining({
file: objectContaining({class: "File", path: any(String)}),
bool: any(Boolean),
enum: "foo"
}),
objectContaining({
file: objectContaining({class: "File", path: "preserved"}),
bool: false,
enum: "foo"
}),
objectContaining({
file: objectContaining({class: "File", path: "preserved-2"}),
bool: any(Boolean),
enum: "bar"
}),
objectContaining({
file: objectContaining({class: "File", path: any(String)}),
bool: any(Boolean),
enum: "foo"
}),
objectContaining({
file: objectContaining({class: "File", path: any(String)}),
bool: any(Boolean),
enum: "foo"
}),
]);
});
});
});
});
/**
* Utility function for checking if multiple values, when adapted, are equal or same as one given value.
* @example expectAll(val => Boolean(val), 1, "str", [], {} ).toBe(true)
*/
function expectAll(mappedBy: Function, ...values: any[]): {
toBe: (value: any) => void,
toEqual: (value: any) => void
} {
// Make an object with "toBe" and "toEqual" methods which evaluate appropriate jasmine methods on collection items
return ["toBe", "toEqual"].reduce((acc, fnName) => {
return Object.assign(acc, {
[fnName]: (result: any) => values.forEach(v => expect(mappedBy(v))[fnName](result))
});
}, {}) as any;
}
function makeMapper(inputID, tool): (value: any) => any {
return (value: any) => {
return fixJob({[inputID]: value}, tool)[inputID];
}
}
function makeToolWithInputs(inputs: CommandInputParameter[]): CommandLineToolModel {
return new V1CommandLineToolModel({
class: "CommandLineTool",
outputs: [],
inputs,
});
} | the_stack |
import { JSDOM } from 'jsdom';
const ishalfWidthImage = (element: CAPIElement): boolean => {
if (!element) return false;
return (
element._type ===
'model.dotcomrendering.pageElements.ImageBlockElement' &&
element.role === 'halfWidth'
);
};
const isMultiImage = (element: CAPIElement): boolean => {
if (!element) return false;
return (
element._type ===
'model.dotcomrendering.pageElements.MultiImageBlockElement'
);
};
const isImage = (element: CAPIElement): boolean => {
if (!element) return false;
return (
element._type === 'model.dotcomrendering.pageElements.ImageBlockElement'
);
};
const isTitle = (element: CAPIElement): boolean => {
if (!element) return false;
// Checks if this element is a 'title' based on the convention: <h2>Title text</h2>
if (
element._type !==
'model.dotcomrendering.pageElements.SubheadingBlockElement'
)
return false;
const frag = JSDOM.fragment(element.html);
return frag?.firstElementChild?.nodeName === 'H2';
};
const extractTitle = (element: CAPIElement): string => {
// We cast here because we're know this element is a subheading but TS isn't sure
const subHeading = element as SubheadingBlockElement;
// Extract 'title' based on the convention: <h2>Title text</h2>
const frag = JSDOM.fragment(subHeading.html);
if (!frag || !frag.firstElementChild) return '';
const isH2tag = frag.firstElementChild.nodeName === 'H2';
if (isH2tag) {
// element is an essay title
return (frag.textContent && frag.textContent.trim()) || '';
}
return '';
};
const isCaption = (element: CAPIElement): boolean => {
if (!element) return false;
// Checks if this element is a 'caption' based on the convention: <ul><li><Caption text</li></ul>
if (
element._type !== 'model.dotcomrendering.pageElements.TextBlockElement'
) {
return false;
}
const frag = JSDOM.fragment(element.html);
if (!frag || !frag.firstElementChild) return false;
const hasULwrapper = frag.firstElementChild.nodeName === 'UL';
const containsLItags = frag.firstElementChild.outerHTML.includes('<li>');
return hasULwrapper && containsLItags;
};
const extractCaption = (element: CAPIElement): string => {
// Extract 'caption' based on the convention: <ul><li><Caption text</li></ul>
// We cast here because we're know this element is a text element but TS isn't sure
const textElement = element as TextBlockElement;
const frag = JSDOM.fragment(textElement.html);
if (!frag || !frag.firstElementChild) return '';
const hasULwrapper = frag.firstElementChild.nodeName === 'UL';
const containsLItags = frag.firstElementChild.outerHTML.includes('<li>');
if (hasULwrapper && containsLItags) {
return textElement.html;
}
return '';
};
const constructMultiImageElement = (
thisElement: CAPIElement,
nextElement: CAPIElement,
): MultiImageBlockElement => {
// We cast here because we're certain each element is an image (because of the guards we set earlier) but
// TS isn't inferring that and needs a little help
const first = thisElement as ImageBlockElement;
const second = nextElement as ImageBlockElement;
return {
_type: 'model.dotcomrendering.pageElements.MultiImageBlockElement',
elementId: first.elementId,
images: [
{
...first,
data: {
...first.data,
caption: '', // Delete any existing caption (special captions might be added later)
},
},
{
...second,
data: {
...second.data,
caption: '', // ibid
},
},
],
};
};
const addMultiImageElements = (elements: CAPIElement[]): CAPIElement[] => {
const withMultiImageElements: CAPIElement[] = [];
elements.forEach((thisElement, i) => {
const nextElement = elements[i + 1];
if (ishalfWidthImage(thisElement) && ishalfWidthImage(nextElement)) {
// Pair found. Add a multi element and remove the next entry
withMultiImageElements.push(
constructMultiImageElement(thisElement, nextElement),
);
// Remove the next element
elements.splice(i + 1, 1);
} else {
// Pass through
withMultiImageElements.push(thisElement);
}
});
return withMultiImageElements;
};
const addTitles = (elements: CAPIElement[]): CAPIElement[] => {
const withTitles: CAPIElement[] = [];
elements.forEach((thisElement, i) => {
const nextElement = elements[i + 1];
const subsequentElement = elements[i + 2];
if (isImage(thisElement) && isTitle(nextElement)) {
// This element is an image and is immediately followed by a title
withTitles.push({
...thisElement,
title: extractTitle(nextElement),
} as ImageBlockElement);
// Remove the element
elements.splice(i + 1, 1);
} else if (
isImage(thisElement) &&
isCaption(nextElement) &&
isTitle(subsequentElement)
) {
// This element is an image, was followed by a caption, and then had a title after it
withTitles.push({
...thisElement,
title: extractTitle(subsequentElement),
} as ImageBlockElement);
// Remove the element
elements.splice(i + 2, 1);
} else {
// Pass through
withTitles.push(thisElement);
}
});
return withTitles;
};
const addCaptionsToImages = (elements: CAPIElement[]): CAPIElement[] => {
const withSpecialCaptions: CAPIElement[] = [];
elements.forEach((thisElement, i) => {
const nextElement = elements[i + 1];
const subsequentElement = elements[i + 2];
if (isImage(thisElement) && isCaption(nextElement)) {
const thisImage = thisElement as ImageBlockElement;
withSpecialCaptions.push({
...thisImage,
data: {
...thisImage.data,
caption: extractCaption(nextElement),
},
} as ImageBlockElement);
// Remove the next element
elements.splice(i + 1, 1);
} else if (
isImage(thisElement) &&
isTitle(nextElement) &&
isCaption(subsequentElement)
) {
const thisImage = thisElement as ImageBlockElement;
withSpecialCaptions.push({
...thisImage,
data: {
...thisImage.data,
caption: extractCaption(subsequentElement),
},
} as ImageBlockElement);
// Remove the subsequent element
elements.splice(i + 2, 1);
} else {
// Pass through
withSpecialCaptions.push(thisElement);
}
});
return withSpecialCaptions;
};
const addCaptionsToMultis = (elements: CAPIElement[]): CAPIElement[] => {
const withSpecialCaptions: CAPIElement[] = [];
elements.forEach((thisElement, i) => {
const nextElement = elements[i + 1];
const subsequentElement = elements[i + 2];
if (isMultiImage(thisElement) && isCaption(nextElement)) {
withSpecialCaptions.push({
...thisElement,
caption: extractCaption(nextElement),
} as MultiImageBlockElement);
// Remove the next element
elements.splice(i + 1, 1);
} else if (
isMultiImage(thisElement) &&
isTitle(nextElement) &&
isCaption(subsequentElement)
) {
withSpecialCaptions.push({
...thisElement,
caption: extractCaption(subsequentElement),
} as MultiImageBlockElement);
// Remove the subsequent element
elements.splice(i + 2, 1);
} else {
// Pass through
withSpecialCaptions.push(thisElement);
}
});
return withSpecialCaptions;
};
const stripCaptions = (elements: CAPIElement[]): CAPIElement[] => {
// Remove all captions from all images
const withoutCaptions: CAPIElement[] = [];
elements.forEach((thisElement) => {
if (
thisElement._type ===
'model.dotcomrendering.pageElements.ImageBlockElement'
) {
// Remove the caption from this image
withoutCaptions.push({
...thisElement,
data: {
...thisElement.data,
caption: '',
},
} as ImageBlockElement);
} else {
// Pass through
withoutCaptions.push(thisElement);
}
});
return withoutCaptions;
};
const removeCredit = (elements: CAPIElement[]): CAPIElement[] => {
// Remove credit from all images
const withoutCredit: CAPIElement[] = [];
elements.forEach((thisElement) => {
if (
thisElement._type ===
'model.dotcomrendering.pageElements.ImageBlockElement'
) {
// Remove the credit from this image
withoutCredit.push({
...thisElement,
data: {
...thisElement.data,
credit: '',
},
} as ImageBlockElement);
} else {
// Pass through
withoutCredit.push(thisElement);
}
});
return withoutCredit;
};
class Enhancer {
elements: CAPIElement[];
constructor(elements: CAPIElement[]) {
this.elements = elements;
}
stripCaptions() {
this.elements = stripCaptions(this.elements);
return this;
}
addMultiImageElements() {
this.elements = addMultiImageElements(this.elements);
return this;
}
addTitles() {
this.elements = addTitles(this.elements);
return this;
}
addCaptionsToMultis() {
this.elements = addCaptionsToMultis(this.elements);
return this;
}
addCaptionsToImages() {
this.elements = addCaptionsToImages(this.elements);
return this;
}
removeCredit() {
this.elements = removeCredit(this.elements);
return this;
}
}
const enhance = (
elements: CAPIElement[],
isPhotoEssay: boolean,
): CAPIElement[] => {
if (isPhotoEssay) {
return (
new Enhancer(elements)
// Photo essays by convention have all image captions removed and rely completely on
// special captions set using the ul/li trick
.stripCaptions()
// By convention, photo essays don't include credit for images in the caption
.removeCredit()
// Replace pairs of halfWidth images with MultiImageBlockElements
.addMultiImageElements()
// Photo essay have a convention of adding titles to images if the subsequent block is a h2
.addTitles()
// If any MultiImageBlockElement is followed by a ul/l caption, delete the special caption
// element and use the value for the multi image `caption` prop
.addCaptionsToMultis()
// In photo essays, we also use ul captions for normal images as well
.addCaptionsToImages().elements
);
}
return (
new Enhancer(elements)
// Replace pairs of halfWidth images with MultiImageBlockElements
.addMultiImageElements()
// If any MultiImageBlockElement is followed by a ul/l caption, delete the special caption
// element and use the value for the multi image `caption` prop
.addCaptionsToMultis().elements
);
};
export const enhanceImages = (data: CAPIType): CAPIType => {
const isPhotoEssay = data.format.design === 'PhotoEssayDesign';
const enhancedBlocks = data.blocks.map((block: Block) => {
return {
...block,
elements: enhance(block.elements, isPhotoEssay),
};
});
return {
...data,
blocks: enhancedBlocks,
} as CAPIType;
}; | the_stack |
export interface Trello {
id: IDBoardEnum;
name: BoardName;
desc: string;
descData: null;
closed: boolean;
idOrganization: null;
shortLink: ShortLink;
powerUps: any[];
dateLastActivity: string;
idTags: any[];
datePluginDisable: null;
creationMethod: null;
idBoardSource: string;
idMemberCreator: null;
idEnterprise: null;
pinned: boolean;
starred: boolean;
url: string;
shortUrl: string;
enterpriseOwned: boolean;
premiumFeatures: any[];
ixUpdate: string;
limits: TrelloLimits;
prefs: Prefs;
subscribed: boolean;
templateGallery: null;
dateLastView: string;
labelNames: LabelNames;
actions: Action[];
cards: CardElement[];
labels: Label[];
lists: List[];
members: MemberElement[];
checklists: ChecklistElement[];
customFields: CustomFieldElement[];
memberships: Membership[];
pluginData: PluginDatum[];
}
export interface Action {
id: string;
idMemberCreator: IDMemberCreator;
data: Data;
type: string;
date: string;
appCreator: AppCreator | null;
limits: ActionLimits;
memberCreator: MemberCreatorClass;
member?: MemberCreatorClass;
}
export interface AppCreator {
id: string;
name: string;
icon: Icon;
}
export interface Icon {
url: string;
}
export interface Data {
old?: Old;
customField?: DataCustomField;
customFieldItem?: CustomFieldItem;
board: Board;
card?: DataCard;
list?: ListClass;
listBefore?: ListClass;
listAfter?: ListClass;
idMember?: IDMemberCreator;
member?: ListClass;
fromCopy?: boolean;
cardSource?: Board;
deactivated?: boolean;
text?: string;
checklist?: ListClass;
checkItem?: DataCheckItem;
boardSource?: BoardSource;
}
export interface Board {
id: IDBoardEnum;
name: BoardName;
shortLink: ShortLink;
idShort?: number;
}
export enum IDBoardEnum {
The5F4800F49696D280D52Bb2Ff = "5f4800f49696d280d52bb2ff",
The5F58E6144A949F4C1879A32A = "5f58e6144a949f4c1879a32a",
}
export enum BoardName {
AgileSprintBoard = "Agile Sprint Board",
StandardTask = "Standard Task",
}
export enum ShortLink {
WduAIKhy = "wduAiKhy",
ZCbHMXU8 = "ZCbHMxU8",
}
export interface BoardSource {
id: string;
}
export interface DataCard {
id: string;
name: string;
idShort: number;
shortLink: string;
pos?: number;
idList?: IDMemberCreator;
due?: string;
dueReminder?: number;
cover?: OldCover;
desc?: string;
}
export interface OldCover {
color: null | string;
idAttachment: null;
idUploadedBackground: IDUploadedBackground | null;
size: MemberType;
brightness: Brightness;
url?: string;
}
export enum Brightness {
Dark = "dark",
Light = "light",
}
export enum IDUploadedBackground {
The5F46Cbb00E54E3660C1A7B22 = "5f46cbb00e54e3660c1a7b22",
The5F46Cbe1C839Ef48989Cd124 = "5f46cbe1c839ef48989cd124",
The5F46Cbe8B0A6Bb3B7F91A0B8 = "5f46cbe8b0a6bb3b7f91a0b8",
}
export enum MemberType {
Full = "full",
Normal = "normal",
}
export enum IDMemberCreator {
The5F4800A4621Dfe2935798972 = "5f4800a4621dfe2935798972",
The5F4800F49696D280D52Bb300 = "5f4800f49696d280d52bb300",
The5F4800F49696D280D52Bb301 = "5f4800f49696d280d52bb301",
The5F4800F49696D280D52Bb302 = "5f4800f49696d280d52bb302",
The5F4800F49696D280D52Bb303 = "5f4800f49696d280d52bb303",
The5F4800F49696D280D52Bb304 = "5f4800f49696d280d52bb304",
The5F480131E778365Be477Add3 = "5f480131e778365be477add3",
}
export interface DataCheckItem {
id: string;
name: string;
state: string;
}
export interface ListClass {
id: IDMemberCreator;
name: FullNameEnum;
}
export enum FullNameEnum {
Backlog = "Backlog",
Checklist = "Checklist",
JohnSmith = "John Smith",
InProgress = "In Progress",
SprintBacklog = "Sprint Backlog",
The8217SprintComplete = "8.2.17 Sprint - Complete",
The8917SprintComplete = "8.9.17 Sprint - Complete",
}
export interface DataCustomField {
id: IDCustomFieldEnum;
name: string;
type?: string;
}
export enum IDCustomFieldEnum {
The5F4802F5905B9A640C49Be08 = "5f4802f5905b9a640c49be08",
The5F480309D1D96A703F2F3143 = "5f480309d1d96a703f2f3143",
}
export interface CustomFieldItem {
id: string;
value: CustomFieldItemValue;
idCustomField: IDCustomFieldEnum;
idModel: string;
modelType: ModelType;
}
export enum ModelType {
Card = "card",
}
export interface CustomFieldItemValue {
number?: string;
checked?: string;
}
export interface Old {
value?: OldValue | null;
pos?: number;
idList?: IDMemberCreator;
name?: string;
due?: null;
dueReminder?: null;
cover?: OldCover;
desc?: string;
}
export interface OldValue {
number: string;
}
export interface ActionLimits {
reactions?: Reactions;
}
export interface Reactions {
perAction: PerBoard;
uniquePerAction: PerBoard;
}
export interface PerBoard {
status: Status;
disableAt: number;
warnAt: number;
}
export enum Status {
Ok = "ok",
}
export interface MemberCreatorClass {
id: IDMemberCreator;
username: Username;
activityBlocked: boolean;
avatarHash: AvatarHash;
avatarUrl: string;
fullName: FullNameEnum;
idMemberReferrer: null;
initials: Initials;
nonPublic: NonPublic;
nonPublicAvailable: boolean;
}
export enum AvatarHash {
Ea6D6D7Da6B79Dc0Cf31301Bc672487F = "ea6d6d7da6b79dc0cf31301bc672487f",
}
export enum Initials {
Cl = "CL",
}
export interface NonPublic {
fullName: FullNameEnum;
initials: Initials;
avatarHash: null;
}
export enum Username {
johnsmith = "johnsmith",
}
export interface CardElement {
id: string;
address: null;
checkItemStates: null;
closed: boolean;
coordinates: null;
creationMethod: null;
dateLastActivity: string;
desc: string;
descData: DescDataClass | null;
dueReminder: number | null;
idBoard: IDBoardEnum;
idLabels: string[];
idList: IDMemberCreator;
idMembersVoted: any[];
idShort: number;
idAttachmentCover: null;
locationName: null;
manualCoverAttachment: boolean;
name: string;
pos: number;
shortLink: string;
isTemplate: boolean;
cardRole: null;
badges: Badges;
dueComplete: boolean;
due: null | string;
email: string;
idChecklists: string[];
idMembers: IDMemberCreator[];
labels: Label[];
limits: CardLimits;
shortUrl: string;
start: null;
subscribed: boolean;
url: string;
cover: PurpleCover;
attachments: Attachment[];
pluginData: any[];
customFieldItems: CustomFieldItem[];
}
export interface Attachment {
bytes: number | null;
date: string;
edgeColor: null | string;
idMember: string;
isUpload: boolean;
mimeType: null | string;
name: string;
previews: Scaled[];
url: string;
pos: number;
id: string;
fileName?: string;
}
export interface Scaled {
_id: string;
id: string;
scaled: boolean;
url: string;
bytes: number;
height: number;
width: number;
}
export interface Badges {
attachmentsByType: AttachmentsByType;
location: boolean;
votes: number;
viewingMemberVoted: boolean;
subscribed: boolean;
fogbugz: string;
checkItems: number;
checkItemsChecked: number;
checkItemsEarliestDue: null;
comments: number;
attachments: number;
description: boolean;
due: null | string;
dueComplete: boolean;
start: null;
}
export interface AttachmentsByType {
trello: TrelloClass;
}
export interface TrelloClass {
board: number;
card: number;
}
export interface PurpleCover {
idAttachment: null;
color: null;
idUploadedBackground: IDUploadedBackground | null;
size: MemberType;
brightness: Brightness;
idPlugin: null;
scaled?: Scaled[];
edgeColor?: string;
sharedSourceUrl?: string;
}
export interface DescDataClass {
emoji: Emoji;
}
export interface Emoji {
}
export interface Label {
id: string;
idBoard: IDBoardEnum;
name: string;
color: string;
}
export interface CardLimits {
attachments: Stickers;
checklists: Stickers;
stickers: Stickers;
}
export interface Stickers {
perCard: PerBoard;
}
export interface ChecklistElement {
id: string;
name: FullNameEnum;
idCard: string;
pos: number;
creationMethod: null;
idBoard: IDBoardEnum;
limits: ChecklistLimits;
checkItems: CheckItemElement[];
}
export interface CheckItemElement {
idChecklist: string;
state: string;
id: string;
name: string;
nameData: DescDataClass | null;
pos: number;
due: null;
idMember: null | string;
}
export interface ChecklistLimits {
checkItems: CheckItems;
}
export interface CheckItems {
perChecklist: PerBoard;
}
export interface CustomFieldElement {
id: IDCustomFieldEnum;
idModel: IDBoardEnum;
modelType: string;
fieldGroup: string;
display: Display;
name: string;
pos: number;
type: string;
isSuggestedField: boolean;
}
export interface Display {
cardFront: boolean;
}
export interface LabelNames {
green: string;
yellow: string;
orange: string;
red: string;
purple: string;
blue: string;
sky: string;
lime: string;
pink: string;
black: string;
}
export interface TrelloLimits {
attachments: Attachments;
boards: Boards;
cards: PurpleCards;
checklists: Attachments;
checkItems: CheckItems;
customFields: CustomFields;
customFieldOptions: CustomFieldOptions;
labels: CustomFields;
lists: Lists;
stickers: Stickers;
reactions: Reactions;
}
export interface Attachments {
perBoard: PerBoard;
perCard: PerBoard;
}
export interface Boards {
totalMembersPerBoard: PerBoard;
}
export interface PurpleCards {
openPerBoard: PerBoard;
openPerList: PerBoard;
totalPerBoard: PerBoard;
totalPerList: PerBoard;
}
export interface CustomFieldOptions {
perField: PerBoard;
}
export interface CustomFields {
perBoard: PerBoard;
}
export interface Lists {
openPerBoard: PerBoard;
totalPerBoard: PerBoard;
}
export interface List {
id: IDMemberCreator;
name: FullNameEnum;
closed: boolean;
pos: number;
softLimit: null;
creationMethod: null;
idBoard: IDBoardEnum;
limits: ListLimits;
subscribed: boolean;
}
export interface ListLimits {
cards: FluffyCards;
}
export interface FluffyCards {
openPerList: PerBoard;
totalPerList: PerBoard;
}
export interface MemberElement {
id: IDMemberCreator;
bio: string;
bioData: null;
confirmed: boolean;
memberType: MemberType;
username: Username;
activityBlocked: boolean;
avatarHash: AvatarHash;
avatarUrl: string;
fullName: FullNameEnum;
idEnterprise: null;
idEnterprisesDeactivated: any[];
idMemberReferrer: null;
idPremOrgsAdmin: any[];
initials: Initials;
nonPublic: NonPublic;
nonPublicAvailable: boolean;
products: any[];
url: string;
status: string;
}
export interface Membership {
id: string;
idMember: IDMemberCreator;
memberType: string;
unconfirmed: boolean;
deactivated: boolean;
}
export interface PluginDatum {
id: string;
idPlugin: string;
scope: string;
idModel: IDBoardEnum;
value: string;
access: string;
}
export interface Prefs {
permissionLevel: string;
hideVotes: boolean;
voting: string;
comments: string;
invitations: string;
selfJoin: boolean;
cardCovers: boolean;
isTemplate: boolean;
cardAging: string;
calendarFeedEnabled: boolean;
background: string;
backgroundImage: string;
backgroundImageScaled: BackgroundImageScaled[];
backgroundTile: boolean;
backgroundBrightness: Brightness;
backgroundBottomColor: string;
backgroundTopColor: string;
canBePublic: boolean;
canBeEnterprise: boolean;
canBeOrg: boolean;
canBePrivate: boolean;
canInvite: boolean;
}
export interface BackgroundImageScaled {
width: number;
height: number;
url: string;
} | the_stack |
import $ from "jquery";
import { InputBinding } from "./inputBinding";
import {
formatDateUTC,
updateLabel,
$escape,
parseDate,
hasOwnProperty,
} from "../../utils";
declare global {
interface JQuery {
// Adjustment of https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1626e0bac175121ec2e9f766a770e03a91843c31/types/bootstrap-datepicker/index.d.ts#L113-L114
bsDatepicker(methodName: "getUTCDate"): Date;
// Infinity is not allowed as a literal return type. Using `1e9999` as a placeholder that resolves to Infinity
// https://github.com/microsoft/TypeScript/issues/32277
bsDatepicker(methodName: "getStartDate"): Date | -1e9999;
bsDatepicker(methodName: "getEndDate"): Date | 1e9999;
bsDatepicker(methodName: string): void;
bsDatepicker(methodName: string, params: Date | null): void;
}
}
type DateReceiveMessageData = {
label: string;
min?: Date | null;
max?: Date | null;
value?: Date | null;
};
class DateInputBindingBase extends InputBinding {
find(scope: HTMLElement): JQuery<HTMLElement> {
return $(scope).find(".shiny-date-input");
}
getType(el: HTMLElement): string {
return "shiny.date";
el;
}
subscribe(el: HTMLElement, callback: (x: boolean) => void): void {
$(el).on(
"keyup.dateInputBinding input.dateInputBinding",
// event: Event
function () {
// Use normal debouncing policy when typing
callback(true);
}
);
$(el).on(
"changeDate.dateInputBinding change.dateInputBinding",
// event: Event
function () {
// Send immediately when clicked
callback(false);
}
);
}
unsubscribe(el: HTMLElement): void {
$(el).off(".dateInputBinding");
}
getRatePolicy(): { policy: "debounce"; delay: 250 } {
return {
policy: "debounce",
delay: 250,
};
}
setValue(el: HTMLElement, data: unknown): void {
throw "not implemented";
el;
data;
}
initialize(el: HTMLElement): void {
const $input = $(el).find("input");
// The challenge with dates is that we want them to be at 00:00 in UTC so
// that we can do comparisons with them. However, the Date object itself
// does not carry timezone information, so we should call _floorDateTime()
// on Dates as soon as possible so that we know we're always working with
// consistent objects.
let date = $input.data("initial-date");
// If initial_date is null, set to current date
if (date === undefined || date === null) {
// Get local date, but normalized to beginning of day in UTC.
date = this._floorDateTime(this._dateAsUTC(new Date()));
}
this.setValue(el, date);
// Set the start and end dates, from min-date and max-date. These always
// use yyyy-mm-dd format, instead of bootstrap-datepicker's built-in
// support for date-startdate and data-enddate, which use the current
// date format.
if ($input.data("min-date") !== undefined) {
this._setMin($input[0], $input.data("min-date"));
}
if ($input.data("max-date") !== undefined) {
this._setMax($input[0], $input.data("max-date"));
}
}
protected _getLabelNode(el: HTMLElement): JQuery<HTMLElement> {
return $(el).find('label[for="' + $escape(el.id) + '"]');
}
// Given a format object from a date picker, return a string
protected _formatToString(format: {
parts: string[];
separators: string[];
}): string {
// Format object has structure like:
// { parts: ['mm', 'dd', 'yy'], separators: ['', '/', '/' ,''] }
let str = "";
let i;
for (i = 0; i < format.parts.length; i++) {
str += format.separators[i] + format.parts[i];
}
str += format.separators[i];
return str;
}
// Given an unambiguous date string or a Date object, set the min (start) date.
// null will unset. undefined will result in no change,
protected _setMin(el: HTMLElement, date: Date | null | undefined): void {
if (date === undefined) return;
if (date === null) {
$(el).bsDatepicker("setStartDate", null);
return;
}
const parsedDate = this._newDate(date);
// If date parsing fails, do nothing
if (parsedDate === null) return;
// (Assign back to date as a Date object)
date = parsedDate as Date;
if (isNaN(date.valueOf())) return;
// Workarounds for
// https://github.com/rstudio/shiny/issues/2335
const curValue = $(el).bsDatepicker("getUTCDate");
// Note that there's no `setUTCStartDate`, so we need to convert this Date.
// It starts at 00:00 UTC, and we convert it to 00:00 in local time, which
// is what's needed for `setStartDate`.
$(el).bsDatepicker("setStartDate", this._utcDateAsLocal(date));
// If the new min is greater than the current date, unset the current date.
if (date && curValue && date.getTime() > curValue.getTime()) {
$(el).bsDatepicker("clearDates");
} else {
// Setting the date needs to be done AFTER `setStartDate`, because the
// datepicker has a bug where calling `setStartDate` will clear the date
// internally (even though it will still be visible in the UI) when a
// 2-digit year format is used.
// https://github.com/eternicode/bootstrap-datepicker/issues/2010
$(el).bsDatepicker("setUTCDate", curValue);
}
}
// Given an unambiguous date string or a Date object, set the max (end) date
// null will unset.
protected _setMax(el: HTMLElement, date: Date): void {
if (date === undefined) return;
if (date === null) {
$(el).bsDatepicker("setEndDate", null);
return;
}
const parsedDate = this._newDate(date);
// If date parsing fails, do nothing
if (parsedDate === null) return;
date = parsedDate as Date;
if (isNaN(date.valueOf())) return;
// Workaround for same issue as in _setMin.
const curValue = $(el).bsDatepicker("getUTCDate");
$(el).bsDatepicker("setEndDate", this._utcDateAsLocal(date));
// If the new min is greater than the current date, unset the current date.
if (date && curValue && date.getTime() < curValue.getTime()) {
$(el).bsDatepicker("clearDates");
} else {
$(el).bsDatepicker("setUTCDate", curValue);
}
}
// Given a date string of format yyyy-mm-dd, return a Date object with
// that date at 12AM UTC.
// If date is a Date object, return it unchanged.
protected _newDate(date: Date | never | string): Date | null {
if (date instanceof Date) return date;
if (!date) return null;
// Get Date object - this will be at 12AM in UTC, but may print
// differently at the Javascript console.
const d = parseDate(date);
// If invalid date, return null
if (isNaN(d.valueOf())) return null;
return d;
}
// A Date can have any time during a day; this will return a new Date object
// set to 00:00 in UTC.
protected _floorDateTime(date: Date): Date {
date = new Date(date.getTime());
date.setUTCHours(0, 0, 0, 0);
return date;
}
// Given a Date object, return a Date object which has the same "clock time"
// in UTC. For example, if input date is 2013-02-01 23:00:00 GMT-0600 (CST),
// output will be 2013-02-01 23:00:00 UTC. Note that the JS console may
// print this in local time, as "Sat Feb 02 2013 05:00:00 GMT-0600 (CST)".
protected _dateAsUTC(date: Date): Date {
return new Date(date.getTime() - date.getTimezoneOffset() * 60000);
}
// The inverse of _dateAsUTC. This is needed to adjust time zones because
// some bootstrap-datepicker methods only take local dates as input, and not
// UTC.
protected _utcDateAsLocal(date: Date): Date {
return new Date(date.getTime() + date.getTimezoneOffset() * 60000);
}
}
class DateInputBinding extends DateInputBindingBase {
// Return the date in an unambiguous format, yyyy-mm-dd (as opposed to a
// format like mm/dd/yyyy)
getValue(el: HTMLElement): string {
const date = $(el).find("input").bsDatepicker("getUTCDate");
return formatDateUTC(date);
}
// value must be an unambiguous string like '2001-01-01', or a Date object.
setValue(el: HTMLElement, value: Date): void {
// R's NA, which is null here will remove current value
if (value === null) {
$(el).find("input").val("").bsDatepicker("update");
return;
}
const date = this._newDate(value);
if (date === null) {
return;
}
// If date is invalid, do nothing
if (isNaN((date as Date).valueOf())) return;
$(el).find("input").bsDatepicker("setUTCDate", date);
}
getState(el: HTMLElement): {
label: string;
value: string | null;
valueString: string[] | number | string;
min: string | null;
max: string | null;
language: string | null;
weekstart: number;
format: string;
startview: DatepickerViewModes;
} {
const $el = $(el);
const $input = $el.find("input");
let min = $input.data("datepicker").startDate;
let max = $input.data("datepicker").endDate;
// Stringify min and max. If min and max aren't set, they will be
// -Infinity and Infinity; replace these with null.
min = min === -Infinity ? null : formatDateUTC(min);
max = max === Infinity ? null : formatDateUTC(max);
// startViewMode is stored as a number; convert to string
let startview = $input.data("datepicker").startViewMode;
if (startview === 2) startview = "decade";
else if (startview === 1) startview = "year";
else if (startview === 0) startview = "month";
return {
label: this._getLabelNode(el).text(),
value: this.getValue(el),
valueString: $input.val(),
min: min,
max: max,
language: $input.data("datepicker").language,
weekstart: $input.data("datepicker").weekStart,
format: this._formatToString($input.data("datepicker").format),
startview: startview,
};
}
receiveMessage(el: HTMLElement, data: DateReceiveMessageData): void {
const $input = $(el).find("input");
updateLabel(data.label, this._getLabelNode(el));
if (hasOwnProperty(data, "min")) this._setMin($input[0], data.min);
if (hasOwnProperty(data, "max")) this._setMax($input[0], data.max);
// Must set value only after min and max have been set. If new value is
// outside the bounds of the previous min/max, then the result will be a
// blank input.
if (hasOwnProperty(data, "value")) this.setValue(el, data.value);
$(el).trigger("change");
}
}
export { DateInputBinding, DateInputBindingBase };
export type { DateReceiveMessageData }; | the_stack |
import {
Atom,
Branch,
isColRowBranch,
isNamedBranch,
ToLatexOptions,
} from '../core/atom-class';
import { Box } from '../core/box';
import { VBox, VBoxElementAndShift } from '../core/v-box';
import { makeLeftRightDelim } from '../core/delimiters';
import { MathstyleName } from '../core/mathstyle';
import { Context } from '../core/context';
import { joinLatex } from '../core/tokenizer';
import { PlaceholderAtom } from './placeholder';
import { AXIS_HEIGHT, BASELINE_SKIP } from '../core/font-metrics';
import { Dimension } from '../public/core';
import { convertDimensionToEm } from '../core/registers-utils';
export type ColumnFormat =
| {
// A regular content column, with the specified alignment.
// 'm' is a special alignement for multline: left on first row, right on last
// row, centered otherwise
align?: 'l' | 'c' | 'r' | 'm';
}
| {
// The width of a gap between columns, or a Latex expression between columns
gap?: number | Atom[];
}
| {
// A rule (line) separating columns
separator?: 'solid' | 'dashed';
};
export type ColSeparationType =
| 'align'
| 'alignat'
| 'gather'
| 'small'
| 'CD'
| undefined;
export type ArrayAtomConstructorOptions = {
// Params: FunctionArgumentDefiniton[];
// parser: ParseFunction;
mathstyleName?: MathstyleName;
columns?: ColumnFormat[];
colSeparationType?: ColSeparationType;
leftDelim?: string;
rightDelim?: string;
// Jot is an extra gap between lines of numbered equation.
// It's 3pt by default in LaTeX (ltmath.dtx:181)
jot?: number;
// A multiplication factor applied to the spacing between rows and columns
arraystretch?: number;
arraycolsep?: number;
};
type ArrayRow = {
cells: Box[];
height: number;
depth: number;
pos: number;
};
// function arrayToString(array: Atom[][][]): string {
// if (array || array.length === 0) return `0 ⨉ 0\n`;
// let result = `${array.length}r ⨉ ${array[0].length ?? 0}c\n`;
// for (const row of array) {
// result += ' ';
// for (const cell of row) {
// if (!cell || cell.length === 0) {
// result += '😱';
// } else if (cell[0].type === 'first') {
// if (cell[1]) {
// result += cell[1].command;
// } else {
// result += '∅';
// }
// } else {
// result += '👎' + cell[0].command;
// }
// result += ' ';
// }
// result += '\n';
// }
// return result;
// }
/**
* Normalize the array:
* - ensure it is dense (not sparse)
* - fold rows that overflow (longer than maximum number of columns)
* - ensure each cell begins with a `first` atom
* - remove last row if empty
*/
function normalizeArray(
atom: ArrayAtom,
array: Atom[][][],
colFormat: ColumnFormat[]
): Atom[][][] {
//
// 1/
// - Fold the array so that there are no more columns of content than
// there are columns prescribed by the column format.
// - Fill rows that have fewer cells than expected with empty cells
// - Ensure that all the cells have a `first` atom.
//
// The number of column is determined by the colFormat
let maxColCount = 0;
for (const colSpec of colFormat) {
if ('align' in colSpec) maxColCount += 1;
}
// Actual number of columns (at most `maxColCount`)
let colCount = 0;
const rows: Atom[][][] = [];
for (const row of array) {
let colIndex = 0;
colCount = Math.max(colCount, Math.min(row.length, maxColCount));
while (colIndex < row.length) {
const newRow: Atom[][] = [];
const lastCol = Math.min(row.length, colIndex + maxColCount);
while (colIndex < lastCol) {
if (row[colIndex].length > 0 && row[colIndex][0].type !== 'first') {
newRow.push([
new Atom('first', { mode: atom.mode }),
...row[colIndex],
]);
} else {
newRow.push(row[colIndex]);
}
colIndex += 1;
}
rows.push(newRow);
}
}
//
// 2/ If the last row is empty, ignore it (TeX behavior)
//
if (
rows[rows.length - 1].length === 1 &&
rows[rows.length - 1][0].length === 0
) {
rows.pop();
}
//
// 3/ Fill out any missing cells
//
const result: Atom[][][] = [];
for (const row of rows) {
if (row.length !== colCount) {
for (let i = row.length; i < colCount; i++) {
row.push([
new Atom('first', { mode: atom.mode }),
new PlaceholderAtom(),
]);
}
}
result.push(row);
}
//
// 4/ Set the `parent` and `treeBranch` for each cell
//
let rowIndex = 0;
let colIndex = 0;
for (const row of result) {
colIndex = 0;
for (const cell of row) {
for (const element of cell) {
element.parent = atom;
element.treeBranch = [rowIndex, colIndex];
}
colIndex += 1;
}
rowIndex += 1;
}
atom.isDirty = true;
return result;
}
// See http://ctan.math.utah.edu/ctan/tex-archive/macros/latex/base/lttab.dtx
export class ArrayAtom extends Atom {
array: (undefined | Atom[])[][];
environmentName: string;
rowGaps: Dimension[];
colFormat: ColumnFormat[];
arraystretch?: number;
arraycolsep?: number;
colSeparationType?: ColSeparationType;
jot?: number;
leftDelim?: string;
rightDelim?: string;
mathstyleName?: MathstyleName;
constructor(
envName: string,
array: Atom[][][],
rowGaps: Dimension[],
options: ArrayAtomConstructorOptions = {}
) {
super('array');
this.environmentName = envName;
this.rowGaps = rowGaps;
if (options.mathstyleName) this.mathstyleName = options.mathstyleName;
if (options.columns) {
if (options.columns.length === 0) {
this.colFormat = [{ align: 'l' }];
} else {
this.colFormat = options.columns;
}
}
// The TeX definition is that arrays by default have a maximum
// of 10, left-aligned, columns.
if (!this.colFormat) {
this.colFormat = [
{ align: 'l' },
{ align: 'l' },
{ align: 'l' },
{ align: 'l' },
{ align: 'l' },
{ align: 'l' },
{ align: 'l' },
{ align: 'l' },
{ align: 'l' },
{ align: 'l' },
];
}
this.array = normalizeArray(this, array, this.colFormat);
// console.log(arrayToString(this.array));
if (options.leftDelim) this.leftDelim = options.leftDelim;
if (options.rightDelim) this.rightDelim = options.rightDelim;
if (options.jot !== undefined) this.jot = options.jot;
if (options.arraycolsep) this.arraycolsep = options.arraycolsep;
this.colSeparationType = options.colSeparationType;
// Default \arraystretch from lttab.dtx
this.arraystretch = options.arraystretch ?? 1.0;
}
branch(cell: Branch): Atom[] | undefined {
if (!isColRowBranch(cell)) return undefined;
return this.array[cell[0]][cell[1]] ?? undefined;
}
get branches(): Branch[] {
const result = super.branches;
this.array.forEach((_, col) => {
this.array[col].forEach((_, row) => {
if (this.array[col][row]) {
result.push([col, row]);
}
});
});
return result;
}
createBranch(cell: Branch): Atom[] {
if (!isColRowBranch(cell)) return [];
return [];
}
get rowCount(): number {
return this.array.length;
}
get colCount(): number {
return this.array[0].length;
}
removeBranch(name: Branch): Atom[] {
if (isNamedBranch(name)) {
return super.removeBranch(name);
}
const children = this.branch(name)!;
this.array[name[0]][name[1]] = undefined;
children.forEach((x) => {
x.parent = undefined;
x.treeBranch = undefined;
});
// Drop the 'first' element
console.assert(children[0].type === 'first');
children.shift();
this.isDirty = true;
return children;
}
get hasChildren(): boolean {
return this.children.length > 0;
}
get children(): Atom[] {
const result: Atom[] = [];
for (const row of this.array) {
for (const cell of row) {
if (cell) {
for (const atom of cell) {
result.push(...atom.children);
result.push(atom);
}
}
}
}
return [...result, ...super.children];
}
render(context: Context): Box | null {
// See http://tug.ctan.org/macros/latex/base/ltfsstrc.dtx
// and http://tug.ctan.org/macros/latex/base/lttab.dtx
const innerContext = new Context(context, this.style, this.mathstyleName);
const arrayRuleWidth = innerContext.getRegisterAsEm('arrayrulewidth');
const arrayColSep = innerContext.getRegisterAsEm('arraycolsep');
const doubleRuleSep = innerContext.getRegisterAsEm('doublerulesep');
// Row spacing
const arraystretch = this.arraystretch ?? 1.0;
let arraycolsep =
typeof this.arraycolsep === 'number' ? this.arraycolsep : arrayColSep;
if (this.colSeparationType === 'small') {
// We're in a {smallmatrix}. Default column space is \thickspace,
// i.e. 5/18em = 0.2778em, per amsmath.dtx for {smallmatrix}.
// But that needs adjustment because LaTeX applies \scriptstyle to the
// entire array, including the colspace, but this function applies
// \scriptstyle only inside each element.
const localMultiplier = new Context(context, undefined, 'scriptstyle')
.scalingFactor;
arraycolsep = 0.2778 * (localMultiplier / context.scalingFactor);
}
const arrayskip = arraystretch * BASELINE_SKIP;
const arstrutHeight = 0.7 * arrayskip;
const arstrutDepth = 0.3 * arrayskip; // \@arstrutbox in lttab.dtx
let totalHeight = 0;
const body: ArrayRow[] = [];
let nc = 0;
const nr = this.array.length;
for (let r = 0; r < nr; ++r) {
const inrow = this.array[r];
nc = Math.max(nc, inrow.length);
// The "inner" is in mathstyleName. Create a **new** context for the
// cells, with the same mathstyleName, but this will prevent the
// style correction from being applied twice
const cellContext = new Context(
innerContext,
this.style,
this.mathstyleName
);
let height = arstrutHeight / cellContext.scalingFactor; // \@array adds an \@arstrut
let depth = arstrutDepth / cellContext.scalingFactor; // To each row (via the template)
const outrow: ArrayRow = { cells: [], height: 0, depth: 0, pos: 0 };
for (const element of inrow) {
const elt =
Atom.createBox(cellContext, element, { newList: true }) ??
new Box(null, { newList: true });
depth = Math.max(depth, elt.depth);
height = Math.max(height, elt.height);
outrow.cells.push(elt);
}
let gap: number = convertDimensionToEm(this.rowGaps[r]) ?? 0;
if (gap > 0) {
// \@argarraycr
gap += arstrutDepth;
depth = Math.max(depth, gap); // \@xargarraycr
gap = 0;
}
if (this.jot !== undefined) {
depth += this.jot;
}
outrow.height = height;
outrow.depth = depth;
totalHeight += height;
outrow.pos = totalHeight;
totalHeight += depth + gap; // \@yargarraycr
body.push(outrow);
}
const offset = totalHeight / 2 + AXIS_HEIGHT;
const contentCols: Box[] = [];
for (let colIndex = 0; colIndex < nc; colIndex++) {
const stack: VBoxElementAndShift[] = [];
for (const row of body) {
const element = row.cells[colIndex];
element.depth = row.depth;
element.height = row.height;
stack.push({ box: element, shift: row.pos - offset });
}
if (stack.length > 0) {
contentCols.push(new VBox({ individualShift: stack }));
}
}
// Iterate over each column description.
// Each `colDesc` will indicate whether to insert a gap, a rule or
// a column from 'contentCols'
const cols: Box[] = [];
let previousColContent = false;
let previousColRule = false;
let currentContentCol = 0;
let firstColumn = !this.leftDelim;
const { colFormat } = this;
for (const colDesc of colFormat) {
if ('align' in colDesc && currentContentCol >= contentCols.length) {
// If there are more column format than content, we're done
break;
}
if ('align' in colDesc) {
// If an alignment is specified, insert a column of content
if (previousColContent) {
// If no gap was provided, insert a default gap between
// consecutive columns of content
cols.push(makeColGap(2 * arraycolsep));
} else if (previousColRule || firstColumn) {
// If the previous column was a rule or this is the first column
// add a smaller gap
cols.push(makeColGap(arraycolsep));
}
cols.push(
new Box(contentCols[currentContentCol], {
classes: 'col-align-' + colDesc.align,
})
);
currentContentCol++;
previousColContent = true;
previousColRule = false;
firstColumn = false;
} else if ('gap' in colDesc) {
//
// Something to insert in between columns of content
//
if (typeof colDesc.gap === 'number') {
// It's a number, indicating how much space, in em,
// to leave in between columns
cols.push(makeColGap(colDesc.gap));
} else {
// It's a list of atoms.
// Create a column made up of the mathlist
// as many times as there are rows.
const col = makeColOfRepeatingElements(
context,
body,
offset,
colDesc.gap
);
if (col) cols.push(col);
}
previousColContent = false;
previousColRule = false;
firstColumn = false;
} else if ('separator' in colDesc) {
//
// It's a column separator.
//
const separator = new Box(null, { classes: 'vertical-separator' });
separator.setStyle('height', totalHeight, 'em');
separator.setStyle(
'border-right',
`${arrayRuleWidth}em ${colDesc.separator} currentColor`
);
// We have box-sizing border-box, no need to correct the margin
// separator.setStyle(
// 'margin',
// `0 -${context.metrics.arrayRuleWidth / 2}em`
// );
separator.setStyle('vertical-align', -(totalHeight - offset), 'em');
let gap = 0;
if (previousColRule) {
gap = doubleRuleSep - arrayRuleWidth;
} else if (previousColContent) {
gap = arraycolsep - arrayRuleWidth;
}
separator.left = gap;
cols.push(separator);
previousColContent = false;
previousColRule = true;
firstColumn = false;
}
}
if (previousColContent && !this.rightDelim) {
// If the last column was content, add a small gap
cols.push(makeColGap(arraycolsep));
}
const inner = new Box(cols, { classes: 'mtable' });
if (
(!this.leftDelim || this.leftDelim === '.') &&
(!this.rightDelim || this.rightDelim === '.')
) {
// There are no delimiters around the array, just return what
// we've built so far.
return inner;
}
// There is at least one delimiter. Wrap the inner of the array with
// appropriate left and right delimiters
const innerHeight = inner.height;
const innerDepth = inner.depth;
const result = this.bind(
context,
new Box(
[
this.bind(
context,
makeLeftRightDelim(
'mopen',
this.leftDelim ?? '.',
innerHeight,
innerDepth,
innerContext
)
),
inner,
this.bind(
context,
makeLeftRightDelim(
'mclose',
this.rightDelim ?? '.',
innerHeight,
innerDepth,
innerContext
)
),
],
{ type: 'mord' }
)
);
if (!result) return null;
if (this.caret) result.caret = this.caret;
return this.attachSupsub(context, { base: result });
}
serialize(options: ToLatexOptions): string {
let result = '\\begin{' + this.environmentName + '}';
if (this.environmentName === 'array') {
result += '{';
if (this.colFormat !== undefined) {
for (const format of this.colFormat) {
if ('align' in format) {
result += format.align;
} else if ('separator' in format && format.separator === 'solid') {
result += '|';
} else if ('separator' in format && format.separator === 'dashed') {
result += ':';
}
}
}
result += '}';
}
for (let row = 0; row < this.array.length; row++) {
for (let col = 0; col < this.array[row].length; col++) {
if (col > 0) result += ' & ';
result = joinLatex([
result,
Atom.serialize(this.array[row][col], options),
]);
}
// Adds a separator between rows (but not after the last row)
if (row < this.array.length - 1) {
result += ' \\\\ ';
}
}
result += '\\end{' + this.environmentName + '}';
return result;
}
getCell(row: number, col: number): Atom[] | undefined {
return this.array[row][col];
}
setCell(_row: number, _column: number, _value: Atom[]): void {
// @todo array
console.assert(this.type === 'array' && Array.isArray(this.array));
this.isDirty = true;
}
addRowBefore(_row: number): void {
console.assert(this.type === 'array' && Array.isArray(this.array));
// @todo array
this.isDirty = true;
}
addRowAfter(_row: number): void {
console.assert(this.type === 'array' && Array.isArray(this.array));
// @todo array
this.isDirty = true;
}
addColumnBefore(_col: number): void {
console.assert(this.type === 'array' && Array.isArray(this.array));
this.isDirty = true;
}
addColumnAfter(_col: number): void {
console.assert(this.type === 'array' && Array.isArray(this.array));
// @todo array
this.isDirty = true;
}
get cells(): Atom[][] {
const result: Atom[][] = [];
for (const row of this.array) {
for (const cell of row) {
if (cell) result.push(cell);
}
}
return result;
}
}
/**
* Create a column separator box.
*
*/
function makeColGap(width: number): Box {
const separator = new Box(null, { classes: 'arraycolsep' });
separator.width = width;
return separator;
}
/**
* Create a column of repeating elements.
*/
function makeColOfRepeatingElements(
context: Context,
rows: ArrayRow[],
offset: number,
element: Atom[] | undefined
): Box | null {
if (!element) return null;
const col: VBoxElementAndShift[] = [];
for (const row of rows) {
const cell = Atom.createBox(context, element, { newList: true });
if (cell) {
cell.depth = row.depth;
cell.height = row.height;
col.push({ box: cell, shift: row.pos - offset });
}
}
return new VBox({ individualShift: col }).wrap(context);
} | the_stack |
import * as vscode from "vscode";
import { executeCommand, ExpectedDocument, groupTestsByParentName } from "../utils";
suite("./test/suite/commands/seek-object-sentence.md", function () {
// Set up document.
let document: vscode.TextDocument,
editor: vscode.TextEditor;
this.beforeAll(async () => {
document = await vscode.workspace.openTextDocument();
editor = await vscode.window.showTextDocument(document);
editor.options.insertSpaces = true;
editor.options.tabSize = 2;
await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" });
});
this.afterAll(async () => {
await executeCommand("workbench.action.closeActiveEditor");
});
test("1 > to-end", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
A sentence starts with a non-blank character or a line break. <== It ends with a
| 0
punctuation mark like the previous one, or two consecutive line breaks like this
| 1
An outer sentence also contains the trailing blank characters (but never line
|^^^^^^^^^^^^^^^^ 2
breaks) like this. <== The white spaces before this sentence belongs to
^ 3
the outer previous sentence.
^ 4
<- White spaces here and the line break before them belongs to this sentence,
|^^^^^^^^^^^^^^^^^^^^^ 5
not the previous one, since the previous trailing cannot contain line breaks.
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "end" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:22:1", 6, String.raw`
A sentence starts with a non-blank character or a line break. <== It ends with a
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
punctuation mark like the previous one, or two consecutive line breaks like this
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1
An outer sentence also contains the trailing blank characters (but never line
^ 2
breaks) like this. <== The white spaces before this sentence belongs to
the outer previous sentence.
^ 2
<- White spaces here and the line break before them belongs to this sentence,
^ 3
not the previous one, since the previous trailing cannot contain line breaks.
^ 3
`);
});
test("1 > to-start", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
A sentence starts with a non-blank character or a line break. <== It ends with a
| 0
punctuation mark like the previous one, or two consecutive line breaks like this
| 1
An outer sentence also contains the trailing blank characters (but never line
|^^^^^^^^^^^^^^^^ 2
breaks) like this. <== The white spaces before this sentence belongs to
^ 3
the outer previous sentence.
^ 4
<- White spaces here and the line break before them belongs to this sentence,
|^^^^^^^^^^^^^^^^^^^^^ 5
not the previous one, since the previous trailing cannot contain line breaks.
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "start" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:44:1", 6, String.raw`
A sentence starts with a non-blank character or a line break. <== It ends with a
| 0 |^^^^^^^^^^^^^^^^^^ 1
punctuation mark like the previous one, or two consecutive line breaks like this
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1
An outer sentence also contains the trailing blank characters (but never line
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2
breaks) like this. <== The white spaces before this sentence belongs to
^^^^^^^^^^^^^^^^^^^^^^ 2 |^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3
the outer previous sentence.
^^^^^^^^^^^^^^^^^^ 3 | 4
<- White spaces here and the line break before them belongs to this sentence,
^^^^^^ 4
not the previous one, since the previous trailing cannot contain line breaks.
`);
});
test("1 > select-inner", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
A sentence starts with a non-blank character or a line break. <== It ends with a
| 0
punctuation mark like the previous one, or two consecutive line breaks like this
| 1
An outer sentence also contains the trailing blank characters (but never line
|^^^^^^^^^^^^^^^^ 2
breaks) like this. <== The white spaces before this sentence belongs to
^ 3
the outer previous sentence.
^ 4
<- White spaces here and the line break before them belongs to this sentence,
|^^^^^^^^^^^^^^^^^^^^^ 5
not the previous one, since the previous trailing cannot contain line breaks.
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", inner: true });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:66:1", 6, String.raw`
A sentence starts with a non-blank character or a line break. <== It ends with a
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
^^^^^^^^^^^^^^^^^^^ 1
punctuation mark like the previous one, or two consecutive line breaks like this
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1
An outer sentence also contains the trailing blank characters (but never line
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2
breaks) like this. <== The white spaces before this sentence belongs to
^^^^^^^^^^^^^^^^^ 2 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3
the outer previous sentence.
^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3
^ 4
<- White spaces here and the line break before them belongs to this sentence,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 4
not the previous one, since the previous trailing cannot contain line breaks.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 4
`);
});
test("2 > to-start", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence . I'm another sentence.
| 0 ^ 1 |^^^ 2
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "start" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:109:1", 6, String.raw`
I'm a sentence . I'm another sentence.
^^^^ 0
^^^^^^^^^ 1
`);
});
test("2 > to-end", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence . I'm another sentence.
| 0 ^ 1 |^^^ 2
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "end" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:120:1", 6, String.raw`
I'm a sentence . I'm another sentence.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
`);
});
test("2 > select", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence . I'm another sentence.
| 0 ^ 1 |^^^ 2
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:130:1", 6, String.raw`
I'm a sentence . I'm another sentence.
^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
`);
});
test("3 > select-inner", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a previous sentence.
|^^^ 3 ^ 4
^ 5
I'm a sentence . I'm another sentence.
^ 0 ^ 1 |^^^ 2
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", inner: true });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:161:1", 6, String.raw`
I'm a previous sentence.
^^^^^^^^^^^^^^^^^^^^^^^ 0 ^ 1
I'm a sentence . I'm another sentence.
^^^^^^^^^^^^^^^^^^^^^^^^^ 1
`);
});
test("3 > to-start", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a previous sentence.
|^^^ 3 ^ 4
^ 5
I'm a sentence . I'm another sentence.
^ 0 ^ 1 |^^^ 2
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "start" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:177:1", 6, String.raw`
I'm a previous sentence.
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
I'm a sentence . I'm another sentence.
^^^^^^^^^^^^^^^^^ 0
`);
});
test("3 > to-start-inner", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a previous sentence.
|^^^ 3 ^ 4
^ 5
I'm a sentence . I'm another sentence.
^ 0 ^ 1 |^^^ 2
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "start", inner: true });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:195:1", 6, String.raw`
I'm a previous sentence.
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
I'm a sentence . I'm another sentence.
^^^^^^^^^^^^^^^^^ 0
`);
});
test("3 > to-end", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a previous sentence.
|^^^ 3 ^ 4
^ 5
I'm a sentence . I'm another sentence.
^ 0 ^ 1 |^^^ 2
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "end" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:210:1", 6, String.raw`
I'm a previous sentence.
^^^^^^^^^^ 0
I'm a sentence . I'm another sentence.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
`);
});
test("4 > select", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence.I'm another sentence
^^^^ 0 ^ 1 ^ 3 | 4
^ 2
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:243:1", 6, String.raw`
I'm a sentence.I'm another sentence
^^^^^^^^^^^^^^^ 0
^^^^^^^^^^^^^^^^^^^^^ 1
`);
});
test("4 > to-start", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence.I'm another sentence
^^^^ 0 ^ 1 ^ 3 | 4
^ 2
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "start" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:258:1", 6, String.raw`
I'm a sentence.I'm another sentence
|^^^^^^^^^^^^^^ 0
|^^^^^^^^^^^^^^^^^^^ 1
`);
});
test("4 > to-end", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence.I'm another sentence
^^^^ 0 ^ 1 ^ 3 | 4
^ 2
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "end" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:274:1", 6, String.raw`
I'm a sentence.I'm another sentence
^^^^ 0
^^^^^^^^^^^^^^^^^^^^^ 1
`);
});
test("5 > select", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence terminated by two line breaks
|^^^^^ 0 ^ 1
^ 2
I'm another sentence
^ 3 |^^^^^ 4
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:308:1", 6, String.raw`
I'm a sentence terminated by two line breaks
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
I'm another sentence
^^^^^^^^^^^^^^^^^^^^ 1
`);
});
test("5 > to-start", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence terminated by two line breaks
|^^^^^ 0 ^ 1
^ 2
I'm another sentence
^ 3 |^^^^^ 4
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "start" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:321:1", 6, String.raw`
I'm a sentence terminated by two line breaks
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
I'm another sentence
^^^^ 1
^^^^^^^^^ 2
`);
});
test("5 > to-end", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence terminated by two line breaks
|^^^^^ 0 ^ 1
^ 2
I'm another sentence
^ 3 |^^^^^ 4
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "end" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:338:1", 6, String.raw`
I'm a sentence terminated by two line breaks
^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
^ 1
I'm another sentence
^^^^^^^^^^^^^^^^^^^^^^^^ 1
`);
});
test("6 > to-start", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence terminated by two line breaks plus one more
|^^^^^ 0 ^ 1
^ 2
| 3
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "start" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:373:1", 6, String.raw`
I'm a sentence terminated by two line breaks plus one more
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
| 1
`);
});
test("6 > to-end", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence terminated by two line breaks plus one more
|^^^^^ 0 ^ 1
^ 2
| 3
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "end" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:386:1", 6, String.raw`
I'm a sentence terminated by two line breaks plus one more
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
| 1
| 2
`);
});
test("6 > select", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence terminated by two line breaks plus one more
|^^^^^ 0 ^ 1
^ 2
| 3
`);
// Perform all operations.
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:400:1", 6, String.raw`
I'm a sentence terminated by two line breaks plus one more
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
| 1
`);
});
test("7 > to-start", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence at end of document
| 0
`);
// Perform all operations.
await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" });
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "start" });
await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:424:1", 6, String.raw`
I'm a sentence at end of document
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
`);
});
test("7 > to-end", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence at end of document
| 0
`);
// Perform all operations.
await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" });
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)", where: "end" });
await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:435:1", 6, String.raw`
I'm a sentence at end of document
^ 0
`);
});
test("7 > select", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
I'm a sentence at end of document
| 0
`);
// Perform all operations.
await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "character" });
await executeCommand("dance.seek.object", { input: "(?#predefined=sentence)" });
await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/seek-object-sentence.md:446:1", 6, String.raw`
I'm a sentence at end of document
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 0
`);
});
groupTestsByParentName(this);
}); | the_stack |
namespace pxt.tutorial {
export interface TutorialRuleStatus {
ruleName: string;
ruleTurnOn: boolean;
ruleStatus?: boolean;
ruleMessage?: string;
isStrict?: boolean;
blockIds?: string[];
}
/**
* Check the user's code to the map of tutorial validation rules from TutorialOptions and returns an array of TutorialRuleStatus
* @param tutorial the tutorial
* @param workspaceBlocks Blockly blocks used of workspace
* @param blockinfo Typescripts of the workspace
* @return A TutorialRuleStatus
*/
export async function validate(tutorial: TutorialOptions, workspaceBlocks: Blockly.Block[], blockinfo: pxtc.BlocksInfo): Promise<TutorialRuleStatus[]> {
const listOfRules = tutorial.tutorialValidationRules;
let TutorialRuleStatuses: TutorialRuleStatus[] = classifyRules(listOfRules);
// Check to if there are rules to valdiate and to see if there are blocks are in the workspace to compare to
if (TutorialRuleStatuses.length > 0 && workspaceBlocks.length > 0) {
// User blocks
const userBlockTypes = workspaceBlocks.map(b => b.type);
const usersBlockUsed = blockCount(userBlockTypes);
// Tutorial blocks
const { tutorialStepInfo, tutorialStep } = tutorial;
const step = tutorialStepInfo[tutorialStep];
const indexdb = await tutorialBlockList(tutorial, step);
const tutorialBlockUsed = extractBlockSnippet(tutorial, indexdb);
for (let i = 0; i < TutorialRuleStatuses.length; i++) {
let currRuleToValidate = TutorialRuleStatuses[i];
const ruleName = TutorialRuleStatuses[i].ruleName;
const isRuleEnabled = TutorialRuleStatuses[i].ruleTurnOn;
if (isRuleEnabled) {
switch (ruleName) {
case "exact":
currRuleToValidate = validateExactNumberOfBlocks(usersBlockUsed, tutorialBlockUsed, currRuleToValidate);
break;
case "atleast":
currRuleToValidate = validateAtleastOneBlocks(usersBlockUsed, tutorialBlockUsed, currRuleToValidate);
break;
case "required":
const requiredBlocksList = extractRequiredBlockSnippet(tutorial, indexdb);
currRuleToValidate = validateMeetRequiredBlocks(usersBlockUsed, requiredBlocksList, currRuleToValidate);
break;
}
}
}
}
return TutorialRuleStatuses;
}
/**
* Gives each rule from the markdown file a TutorialRuleStatus
* @param listOfRules a map of rules from makrdown file
* @return An array of TutorialRuleStatus
*/
function classifyRules(listOfRules: pxt.Map<boolean>): TutorialRuleStatus[] {
let listOfRuleStatuses: TutorialRuleStatus[] = [];
if (listOfRules != undefined) {
const ruleNames: string[] = Object.keys(listOfRules);
for (let i = 0; i < ruleNames.length; i++) {
const currRule: string = ruleNames[i];
const ruleVal: boolean = listOfRules[currRule];
const currRuleStatus: TutorialRuleStatus = { ruleName: currRule, ruleTurnOn: ruleVal };
listOfRuleStatuses.push(currRuleStatus);
}
}
return listOfRuleStatuses;
}
/**
* Loops through an array of blocks and returns a map of blocks and the count for that block
* @param arr a string array of blocks
* @return a map <Block type, frequency>
*/
function blockCount(arr: string[]): pxt.Map<number> {
let frequencyMap: pxt.Map<number> = {};
for (let i: number = 0; i < arr.length; i++) {
if (!frequencyMap[arr[i]]) {
frequencyMap[arr[i]] = 0;
}
frequencyMap[arr[i]] = frequencyMap[arr[i]] + 1;
}
return frequencyMap;
}
/**
* Returns information from index database
* @param tutorial Typescripts of the workspace
* @param step the current tutorial step
* @return indexdb's tutorial code snippets
*/
function tutorialBlockList(tutorial: TutorialOptions, step: TutorialStepInfo): Promise<pxt.Map<pxt.Map<number>> | undefined> {
return pxt.BrowserUtils.tutorialInfoDbAsync()
.then(db => db.getAsync(tutorial.tutorial, tutorial.tutorialCode)
.then(entry => {
if (entry?.snippets) {
return Promise.resolve(entry.snippets);
}
else {
return Promise.resolve(undefined);
}
})
);
}
/**
* Extract the tutorial blocks used from code snippet
* @param tutorial tutorial info
* @param indexdb database from index
* @return the tutorial blocks used for the current step
*/
function extractBlockSnippet(tutorial: TutorialOptions, indexdb: pxt.Map<pxt.Map<number>>) {
const { tutorialStepInfo, tutorialStep } = tutorial;
const body = tutorial.tutorialStepInfo[tutorialStep].hintContentMd;
let hintCode = "";
if (body != undefined) {
body.replace(/((?!.)\s)+/g, "\n").replace(/``` *(block|blocks)\s*\n([\s\S]*?)\n```/gmi, function (m0, m1, m2) {
hintCode = `{\n${m2}\n}`;
return "";
});
}
const snippetStepKey = pxt.BrowserUtils.getTutorialCodeHash([hintCode]);
let blockMap = {};
if (indexdb != undefined) {
blockMap = indexdb[snippetStepKey];
}
return blockMap;
}
/**
* Extract the required tutorial blocks from code snippet
* @param tutorial tutorial info
* @param indexdb database from index
* @return the tutorial blocks used for the current step
*/
function extractRequiredBlockSnippet(tutorial: TutorialOptions, indexdb: pxt.Map<pxt.Map<number>>) {
const { tutorialStep } = tutorial;
const body = tutorial.tutorialStepInfo[tutorialStep].requiredBlockMd;
const snippetStepKey = pxt.BrowserUtils.getTutorialCodeHash([body]);
let blockMap = {};
if (indexdb != undefined) {
blockMap = indexdb[snippetStepKey];
}
return blockMap;
}
/**
* Strict Rule: Checks if the all required number of blocks for a tutorial step is used, returns a TutorialRuleStatus
* @param usersBlockUsed an array of strings
* @param tutorialBlockUsed the next available index
* @param currRule the current rule with its TutorialRuleStatus
* @return a tutorial rule status for currRule
*/
function validateExactNumberOfBlocks(usersBlockUsed: pxt.Map<number>, tutorialBlockUsed: pxt.Map<number>, currRule: TutorialRuleStatus): TutorialRuleStatus {
currRule.isStrict = true;
const userBlockKeys = Object.keys(usersBlockUsed);
let tutorialBlockKeys: string[] = []
let blockIds = [];
if (tutorialBlockUsed != undefined) {
tutorialBlockKeys = Object.keys(tutorialBlockUsed);
}
let isValid = userBlockKeys.length >= tutorialBlockKeys.length; // user has enough blocks
const message = lf("These are the blocks you seem to be missing:");
for (let i: number = 0; i < tutorialBlockKeys.length; i++) {
let tutorialBlockKey = tutorialBlockKeys[i];
if (!usersBlockUsed[tutorialBlockKey] // user did not use a specific block or
|| usersBlockUsed[tutorialBlockKey] < tutorialBlockUsed[tutorialBlockKey]) { // user did not use enough of a certain block
blockIds.push(tutorialBlockKey);
isValid = false;
}
}
currRule.ruleMessage = message;
currRule.ruleStatus = isValid;
currRule.blockIds = blockIds;
return currRule;
}
/**
* Passive Rule: Checks if the users has at least one block type for each rule
* @param usersBlockUsed an array of strings
* @param tutorialBlockUsed the next available index
* @param currRule the current rule with its TutorialRuleStatus
* @return a tutorial rule status for currRule
*/
function validateAtleastOneBlocks(usersBlockUsed: pxt.Map<number>, tutorialBlockUsed: pxt.Map<number>, currRule: TutorialRuleStatus): TutorialRuleStatus {
const userBlockKeys = Object.keys(usersBlockUsed);
const tutorialBlockKeys = Object.keys(tutorialBlockUsed ?? {});
let isValid = userBlockKeys.length >= tutorialBlockKeys.length; // user has enough blocks
for (let i: number = 0; i < tutorialBlockKeys.length; i++) {
let tutorialBlockKey = tutorialBlockKeys[i];
if (!usersBlockUsed[tutorialBlockKey]) { // user did not use a specific block
isValid = false;
break;
}
}
currRule.ruleStatus = isValid;
return currRule;
}
/**
* Strict Rule: Checks if the all required number of blocks for a tutorial step is used, returns a TutorialRuleStatus
* @param usersBlockUsed an array of strings
* @param tutorialBlockUsed the next available index
* @param currRule the current rule with its TutorialRuleStatus
* @return a tutorial rule status for currRule
*/
function validateMeetRequiredBlocks(usersBlockUsed: pxt.Map<number>, requiredBlocks: pxt.Map<number>, currRule: TutorialRuleStatus): TutorialRuleStatus {
currRule.isStrict = true;
const userBlockKeys = Object.keys(usersBlockUsed);
let requiredBlockKeys: string[] = []
let blockIds = [];
if (requiredBlocks != undefined) {
requiredBlockKeys = Object.keys(requiredBlocks);
}
let isValid: boolean = true;
const message = lf("You are required to have the following block:");
for (let i: number = 0; i < requiredBlockKeys.length; i++) {
let requiredBlockKey = requiredBlockKeys[i];
if (!usersBlockUsed[requiredBlockKey]) {
blockIds.push(requiredBlockKey);
isValid = false;
}
}
currRule.ruleMessage = message;
currRule.ruleStatus = isValid;
currRule.blockIds = blockIds;
return currRule;
}
} | the_stack |
import type { queries } from '@testing-library/dom';
import {
jsHandleToArray,
printColorsInErrorMessages,
removeFuncFromStackTrace,
} from './utils';
import type { ElementHandle, JSHandle, Page } from 'puppeteer';
import { createClientRuntimeServer } from './module-server/client-runtime-server';
import type { AsyncHookTracker } from './async-hooks';
type ElementToElementHandle<Input> = Input extends Element
? ElementHandle<Input>
: Input extends (Element | ElementHandle)[]
? { [K in keyof Input]: ElementToElementHandle<Input[K]> }
: Input;
type Promisify<Input> = Input extends Promise<any> ? Input : Promise<Input>;
type ValueOf<Input> = Input extends any[] ? Input[number] : Input[keyof Input];
type UnArray<Input> = Input extends any[] ? Input[number] : Input;
type UnPromise<Input> = Input extends Promise<infer Inner> ? Inner : Input;
/**
* Changes type signature of an original testing library query function by:
* - Removing the `container` parameter
* - Returning a promise, always
* - Returning ElementHandles instead of Elements
*/
type ChangeDTLFn<DTLFn extends ValueOf<typeof queries>> = DTLFn extends (
container: HTMLElement,
...args: infer Args
) => infer DTLReturn
? <CustomizedReturn extends UnArray<UnPromise<DTLReturn>>>(
...args: Args
) => Promisify<
ElementToElementHandle<
UnPromise<DTLReturn> extends any[]
? CustomizedReturn[]
: CustomizedReturn
>
>
: never;
export type BoundQueries = {
[K in keyof typeof queries]: ChangeDTLFn<typeof queries[K]>;
};
const queryNames = [
'findAllByAltText',
'findAllByDisplayValue',
'findAllByLabelText',
'findAllByPlaceholderText',
'findAllByRole',
'findAllByTestId',
'findAllByText',
'findAllByTitle',
'findByAltText',
'findByDisplayValue',
'findByLabelText',
'findByPlaceholderText',
'findByRole',
'findByTestId',
'findByText',
'findByTitle',
'getAllByAltText',
'getAllByDisplayValue',
'getAllByLabelText',
'getAllByPlaceholderText',
'getAllByRole',
'getAllByTestId',
'getAllByText',
'getAllByTitle',
'getByAltText',
'getByDisplayValue',
'getByLabelText',
'getByPlaceholderText',
'getByRole',
'getByTestId',
'getByText',
'getByTitle',
'queryAllByAltText',
'queryAllByDisplayValue',
'queryAllByLabelText',
'queryAllByPlaceholderText',
'queryAllByRole',
'queryAllByTestId',
'queryAllByText',
'queryAllByTitle',
'queryByAltText',
'queryByDisplayValue',
'queryByLabelText',
'queryByPlaceholderText',
'queryByRole',
'queryByTestId',
'queryByText',
'queryByTitle',
] as const;
interface DTLError {
failed: true;
messageWithElementsRevived: unknown[];
messageWithElementsStringified: string;
}
export const getQueriesForElement = (
page: import('puppeteer').Page,
asyncHookTracker: AsyncHookTracker,
element?: import('puppeteer').ElementHandle,
) => {
const serverPromise = createClientRuntimeServer();
// @ts-expect-error TS doesn't understand the properties coming out of Object.fromEntries
const queries: BoundQueries = Object.fromEntries(
queryNames.map((queryName: typeof queryNames[number]) => {
const query = async (...args: any[]) => {
const serializedArgs = JSON.stringify(args, (_key, value) => {
if (value instanceof RegExp) {
return {
__serialized: 'RegExp',
source: value.source,
flags: value.flags,
};
}
return value;
});
const { port } = await serverPromise;
const result: JSHandle<Element | Element[] | DTLError | null> =
await page.evaluateHandle(
// Using new Function to avoid babel transpiling the import
// @ts-expect-error pptr's types don't like new Function
new Function(
'argsString',
'element',
`return import("http://localhost:${port}/@pleasantest/dom-testing-library")
.then(async ({ reviveElementsInString, printElement, addToElementCache, ...dtl }) => {
const deserializedArgs = JSON.parse(argsString, (key, value) => {
if (value.__serialized === 'RegExp')
return new RegExp(value.source, value.flags)
return value
})
try {
return await dtl.${queryName}(element, ...deserializedArgs)
} catch (error) {
const message =
error.message +
(error.container
? '\\n\\nWithin: ' + addToElementCache(error.container)
: '')
const messageWithElementsRevived = reviveElementsInString(message)
const messageWithElementsStringified = messageWithElementsRevived
.map(el => {
if (el instanceof Element || el instanceof Document)
return printElement(el, ${printColorsInErrorMessages})
return el
})
.join('')
return { failed: true, messageWithElementsRevived, messageWithElementsStringified }
}
})`,
),
serializedArgs,
element?.asElement() || (await page.evaluateHandle(() => document)),
);
const failed = await result.evaluate(
(r) => typeof r === 'object' && r !== null && (r as DTLError).failed,
);
if (failed) {
const resultProperties = Object.fromEntries(
await result.getProperties(),
);
const messageWithElementsStringified =
(await resultProperties.messageWithElementsStringified.jsonValue()) as any;
const messageWithElementsRevived = await jsHandleToArray(
resultProperties.messageWithElementsRevived,
);
const error = new Error(messageWithElementsStringified);
// @ts-expect-error messageForBrowser is a custom property that we add to Errors
error.messageForBrowser = messageWithElementsRevived;
throw removeFuncFromStackTrace(error, queries[queryName]);
}
// If it returns a JSHandle<Array>, make it into an array of JSHandles so that using [0] for getAllBy* queries works
if (await result.evaluate((r) => Array.isArray(r))) {
const array = Array.from({
length: await result.evaluate((r) => (r as Element[]).length),
});
const props = await result.getProperties();
for (const [key, value] of props.entries()) {
array[key as any as number] = value;
}
return array;
}
// If it is an element, return it
if (result.asElement() !== null) return result;
// Try to JSON-ify it (for example if it is null from queryBy*)
return result.jsonValue();
};
return [
queryName,
async (...args: any[]): Promise<any> =>
// await is needed for correct stack trace
// eslint-disable-next-line no-return-await
await asyncHookTracker.addHook(
() => query(...args),
queries[queryName],
),
];
}),
);
return queries;
};
let waitForCounter = 0;
export interface WaitForOptions {
/**
* The element watched by the MutationObserver which,
* when it or its descendants change,
* causes the callback to run again (regardless of the interval).
* Default: `document.documentElement` (root element)
*/
container?: ElementHandle;
/**
* The amount of time (milliseconds) that will pass before waitFor "gives up" and throws whatever the callback threw.
* Default: 1000ms
*/
timeout?: number;
/**
* The maximum amount of time (milliseconds) that will pass between each run of the callback.
* If the MutationObserver notices a DOM change before this interval triggers,
* the callback will run again immediately.
* Default: 50ms
*/
interval?: number;
/** Manipulate the error thrown when the timeout triggers. */
onTimeout?: (error: Error) => Error;
/** Options to pass to initialize the MutationObserver. */
mutationObserverOptions?: MutationObserverInit;
}
interface WaitFor {
<T>(
page: Page,
asyncHookTracker: AsyncHookTracker,
cb: () => T | Promise<T>,
{ onTimeout, container, ...opts }: WaitForOptions,
wrappedFunction: (...args: any) => any,
): Promise<T>;
}
export const waitFor: WaitFor = async (
page,
asyncHookTracker,
cb,
{ onTimeout, container, ...opts },
wrappedFunction,
) =>
asyncHookTracker.addHook(async () => {
const { port } = await createClientRuntimeServer();
waitForCounter++;
// Functions exposed via page.exposeFunction can't be removed,
// So we need a unique name for each variable
const browserFuncName = `pleasantest_waitFor_${waitForCounter}`;
await page.exposeFunction(browserFuncName, cb);
const evalResult = await page.evaluateHandle(
// Using new Function to avoid babel transpiling the import
// @ts-expect-error pptr's types don't like new Function
new Function(
'opts',
'container',
`return import("http://localhost:${port}/@pleasantest/dom-testing-library")
.then(async ({ waitFor }) => {
try {
const result = await waitFor(${browserFuncName}, { ...opts, container })
return { success: true, result }
} catch (error) {
if (/timed out in waitFor/i.test(error.message)) {
// Leave out stack trace so the stack trace is given from Node
return { success: false, result: { message: error.message } }
}
return { success: false, result: error }
}
})`,
),
opts,
// Container has to be passed separately because puppeteer won't unwrap nested JSHandles
container,
);
const wasSuccessful = await evalResult.evaluate((r) => r.success);
const result = await evalResult.evaluate((r) =>
r.success
? r.result
: { message: r.result.message, stack: r.result.stack },
);
if (wasSuccessful) return result;
const err = new Error(result.message);
if (result.stack) err.stack = result.stack;
else removeFuncFromStackTrace(err, asyncHookTracker.addHook);
throw onTimeout ? onTimeout(err) : err;
}, wrappedFunction); | the_stack |
module RongIMLib {
/**
* 把消息对象写入流中
* 发送消息时用到
*/
export class MessageOutputStream {
out: RongIMLib.RongIMStream;
constructor(_out: any) {
var binaryHelper = new RongIMLib.BinaryHelper();
this.out = binaryHelper.convertStream(_out);
}
writeMessage(msg: RongIMLib.BaseMessage) {
if (msg instanceof RongIMLib.BaseMessage) {
msg.write(this.out);
}
}
}
/**
* 流转换为消息对象
* 服务器返回消息时用到
*/
export class MessageInputStream {
msg: any;
flags: any;
header: Header;
isPolling: boolean;
In: any;
_in: any;
constructor(In: any, isPolling?: boolean) {
if (!isPolling) {
var _in = new RongIMLib.BinaryHelper().convertStream(In);
this.flags = _in.readByte();
this._in = _in;
} else {
this.flags = In["headerCode"];
}
this.header = new RongIMLib.Header(this.flags);
this.isPolling = isPolling;
this.In = In;
}
readMessage() {
switch (this.header.getType()) {
case 1:
this.msg = new ConnectMessage(this.header);
break;
case 2:
this.msg = new ConnAckMessage(this.header);
break;
case 3:
this.msg = new PublishMessage(this.header);
this.msg.setSyncMsg(this.header.getSyncMsg());
break;
case 4:
this.msg = new PubAckMessage(this.header);
break;
case 5:
this.msg = new QueryMessage(this.header);
break;
case 6:
this.msg = new QueryAckMessage(this.header);
break;
case 7:
this.msg = new QueryConMessage(this.header);
break;
case 9:
case 11:
case 13:
this.msg = new PingRespMessage(this.header);
break;
case 8:
case 10:
case 12:
this.msg = new PingReqMessage(this.header);
break;
case 14:
this.msg = new DisconnectMessage(this.header);
break;
default:
throw new Error("No support for deserializing " + this.header.getType() + " messages");
}
if (this.isPolling) {
this.msg.init(this.In);
} else {
this.msg.read(this._in, this.In.length - 1);
}
return this.msg;
}
}
export class Header {
type: number;
retain: boolean = false;
qos: any = Qos.AT_LEAST_ONCE;
dup: boolean = false;
syncMsg: boolean = false;
constructor(_type: any, _retain?: any, _qos?: any, _dup?: any) {
if (_type && +_type == _type && arguments.length == 1) {
this.retain = (_type & 1) > 0;
this.qos = (_type & 6) >> 1;
this.dup = (_type & 8) > 0;
this.type = (_type >> 4) & 15;
this.syncMsg = (_type & 8) == 8;
} else {
this.type = _type;
this.retain = _retain;
this.qos = _qos;
this.dup = _dup;
}
}
getSyncMsg():boolean {
return this.syncMsg;
}
getType(): number {
return this.type;
}
encode(): any {
var me = this;
switch (this.qos) {
case Qos[0]:
me.qos = Qos.AT_MOST_ONCE;
break;
case Qos[1]:
me.qos = Qos.AT_LEAST_ONCE;
break;
case Qos[2]:
me.qos = Qos.EXACTLY_ONCE;
break;
case Qos[3]:
me.qos = Qos.DEFAULT;
break;
}
var _byte = (this.type << 4);
_byte |= this.retain ? 1 : 0;
_byte |= this.qos << 1;
_byte |= this.dup ? 8 : 0;
return _byte;
}
toString(): string {
return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]";
}
}
/**
* 二进制帮助对象
*/
export class BinaryHelper {
writeUTF(str: string, isGetBytes?: any): any {
var back: any = [], byteSize = 0;
for (let i = 0, len = str.length; i < len; i++) {
var code = str.charCodeAt(i);
if (code >= 0 && code <= 127) {
byteSize += 1;
back.push(code);
} else if (code >= 128 && code <= 2047) {
byteSize += 2;
back.push((192 | (31 & (code >> 6))));
back.push((128 | (63 & code)));
} else if (code >= 2048 && code <= 65535) {
byteSize += 3;
back.push((224 | (15 & (code >> 12))));
back.push((128 | (63 & (code >> 6))));
back.push((128 | (63 & code)));
}
}
for (let i = 0, len = back.length; i < len; i++) {
if (back[i] > 255) {
back[i] &= 255;
}
}
if (isGetBytes) {
return back;
}
if (byteSize <= 255) {
return [0, byteSize].concat(back);
} else {
return [byteSize >> 8, byteSize & 255].concat(back);
}
}
readUTF(arr: any): string {
if (Object.prototype.toString.call(arr) == "[object String]") {
return arr;
}
var UTF = "", _arr = arr;
for (let i = 0, len = _arr.length; i < len; i++) {
if (_arr[i] < 0) { _arr[i] += 256; };
var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/);
if (v && one.length == 8) {
var bytesLength = v[0].length,
// store = _arr[i].toString(2).slice(7 - bytesLength);
store = '';
for (var st = 0; st < bytesLength; st++) {
store += _arr[st + i].toString(2).slice(2);
}
UTF += String.fromCharCode(parseInt(store, 2));
i += bytesLength - 1;
} else {
UTF += String.fromCharCode(_arr[i]);
}
}
return UTF;
}
/**
* [convertStream 将参数x转化为RongIMStream对象]
* @param {any} x [参数]
*/
convertStream(x: any): RongIMStream {
if (x instanceof RongIMStream) {
return x;
} else {
return new RongIMStream(x);
}
}
toMQttString(str: string): any {
return this.writeUTF(str);
}
}
export class RongIMStream {
pool: any;
//当前流执行的起始位置
position: number = 0;
//当前流写入的多少字节
writen: number = 0;
poolLen: number = 0;
binaryHelper: BinaryHelper = new BinaryHelper();
constructor(arr: any) {
this.pool = arr;
this.poolLen = arr.length;
}
check(): boolean {
return this.position >= this.pool.length;
}
readInt(): number {
if (this.check()) {
return -1;
}
var end = "";
for (var i = 0; i < 4; i++) {
var t = this.pool[this.position++].toString(16);
if (t.length == 1) {
t = "0" + t;
}
end += t.toString(16);
}
return parseInt(end, 16);
}
readLong(): number {
if (this.check()) {
return -1;
}
var end = "";
for (var i = 0; i < 8; i++) {
var t = this.pool[this.position++].toString(16);
if (t.length == 1) {
t = "0" + t;
}
end += t;
}
return parseInt(end, 16);
}
readTimestamp(): number {
if (this.check()) {
return -1;
}
var end = "";
for (var i = 0; i < 8; i++) {
end += this.pool[this.position++].toString(16);
}
end = end.substring(2, 8);
return parseInt(end, 16);
}
readUTF(): any {
if (this.check()) {
return -1;
}
var big = (this.readByte() << 8) | this.readByte();
return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big));
}
readByte(): any {
if (this.check()) {
return -1;
}
var val = this.pool[this.position++];
if (val > 255) {
val &= 255;
}
return val;
}
read(bytesArray?: any): any {
if (bytesArray) {
return this.pool.subarray(this.position, this.poolLen);
} else {
return this.readByte();
}
}
write(_byte: any) {
var b = _byte;
if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") {
[].push.apply(this.pool, b);
} else {
if (+b == b) {
if (b > 255) {
b &= 255;
}
this.pool.push(b);
this.writen++;
}
}
return b;
}
writeChar(v: any) {
if (+v != v) {
throw new Error("writeChar:arguments type is error");
}
this.write(v >> 8 & 255);
this.write(v & 255);
this.writen += 2;
}
writeUTF(str: string) {
var val = this.binaryHelper.writeUTF(str);
[].push.apply(this.pool, val);
this.writen += val.length;
}
toComplements(): any {
var _tPool = this.pool;
for (var i = 0; i < this.poolLen; i++) {
if (_tPool[i] > 128) {
_tPool[i] -= 256;
}
}
return _tPool;
}
getBytesArray(isCom: boolean): any {
if (isCom) {
return this.toComplements();
}
return this.pool;
}
}
} | the_stack |
import { Button, Col, Form, Row, Spin } from 'antd'
import _, { get, isArray, isFunction, omit, set } from 'lodash'
import { observer } from 'mobx-react'
import Qs from 'query-string'
import React, { Component } from 'react'
import { JsonSchema } from '~/types'
import { updateComponentAlias } from '~/utils'
import { resolveAction, _resolveAction } from '~/utils/actions'
import message from '~/utils/message'
import request from '~/utils/request'
import HtCard from '../Card'
import Field from '../Field'
import './index.less'
import {
Field as TypeField,
form,
FormButtonType,
HtFormProps,
HtFormState,
} from './interface'
const ComponentAlias = '$$HtForm'
const FormFetchDataAlias = '$$HtFormResponse'
updateComponentAlias(ComponentAlias, {})
updateComponentAlias(FormFetchDataAlias, null)
export class HtForm extends Component<HtFormProps, HtFormState> {
static displayName = 'HtForm'
static __isContainer__ = true
static defaultProps: Partial<HtFormProps> = {
isCard: false,
alias: ComponentAlias,
responseAlias: FormFetchDataAlias,
method: 'post',
fields: [],
cols: 1,
labelCol: { span: 6 },
wrapperCol: { span: 14 },
buttonGroupProps: {},
buttons: ['back', 'submit'],
submitButtonText: '保存',
backButtonText: '返回',
resetButtonText: '重置',
redirectToButtonText: '下一步',
downloadButtonText: '下载',
isAutoSubmit: false,
isShowSuccessMessage: true,
onSuccessAction: null,
transform: (v: any) => v,
isResetShouldSubmit: false,
'data-component-type': 'HtForm',
}
state: HtFormState = {
isPageLoading: false,
}
ignoreFields: JsonSchema.DynamicObject = {}
cols = 0
lastSubmitTime = new Date().getTime()
constructor(props: HtFormProps) {
super(props)
let getRef = props.getRef
if (isFunction(getRef)) {
getRef(this)
}
}
componentDidMount() {
const { isAutoSubmit } = this.props
if (isAutoSubmit) {
this.submit()
}
}
resolveURL = () => {
const { url, pagestate, alias } = this.props
if (_.isString(url)) return url
if (_.isFunction(url)) {
// @ts-ignore
const formData = _.get(pagestate, alias)
return url(formData)
}
console.error(url)
throw new Error(`url 格式错误`)
}
// 设置页面loading
setPageLoading = (isPageLoading: boolean) => {
return new Promise((resolve, reject) => {
try {
this.setState(
{
isPageLoading,
},
() => {
resolve()
}
)
} catch (e) {
reject(e)
}
})
}
// 跳转页面
openWindow = async () => {
const url = this.resolveURL()
const params = await this.validateFields()
_resolveAction('openWindow', `${url}?${Qs.stringify(params)}`)
}
redirectTo = async () => {
const { pagestate } = this.props
const url = this.resolveURL()
const params = await this.validateFields()
_resolveAction('redirectTo', `${url}?${Qs.stringify(params)}`, pagestate)
}
// 重置表单
reset = async () => {
const { form, alias, pagestate, isResetShouldSubmit } = this.props
const { setStoreState } = pagestate
form.resetFields()
const values = form.getFieldsValue()
setStoreState({ [alias as string]: values })
isResetShouldSubmit && this.resetAndSubmit()
this.restSort()
}
// 返回
back = () => {
const { history } = this.props.pagestate
history.goBack()
}
// 下载
download = async () => {
const { pagestate } = this.props
const url = this.resolveURL()
const params = await this.validateFields()
let downloadUrl = `${url}?${Qs.stringify(params)}`
_resolveAction('openWindow', downloadUrl, pagestate)
}
restSort = async () => {
const { pagestate } = this.props
const aliasTable = '$$HtList'
// @ts-ignore
const formData = pagestate[aliasTable]
_.set(formData, 'restSort', true)
pagestate.setStoreState({ [aliasTable]: formData })
}
/**
* 重置 && 提交
*/
resetAndSubmit = () => {
const { resetPagination } = this.props
if (isFunction(resetPagination)) {
resetPagination()
}
this.submit()
}
validateFields = (
e?: React.FormEvent<HTMLFormElement>
): Promise<JsonSchema.DynamicObject> => {
e && e.preventDefault()
if (e) {
let currentTime = new Date().getTime()
// 2s内重复点击无效
if (currentTime - this.lastSubmitTime < 2000) {
this.lastSubmitTime = currentTime
return Promise.reject(new Error('请不要重复提交'))
}
this.lastSubmitTime = currentTime
}
const { form, transform } = this.props
return new Promise((resolve, reject) => {
form.validateFieldsAndScroll((err, values) => {
if (err) {
return reject(err)
}
const params = this.filterFields(values)
if (isFunction(transform)) {
return resolve(transform(params))
} else {
return resolve(params)
}
})
})
}
// 提交表单
submit = async (e?: React.FormEvent<HTMLFormElement>) => {
const {
sendFormData,
onSuccess,
responseAlias = FormFetchDataAlias,
pagestate,
} = this.props
// 发送请求, 如果props中有,则使用; 否则, 则使用默认方法
let sendData = sendFormData || this.sendFormData
const params = await this.validateFields(e)
let res = await sendData(params)
// 将返回结果挂载到数据中心
pagestate.setStoreState({
[responseAlias]: res,
})
const { onSuccessAction, _onSuccessAction } = this.props
// 请求成功回调事件
if (isFunction(onSuccess)) {
onSuccess(res)
}
setTimeout(() => {
if (_.isArray(_onSuccessAction)) {
const [type, config] = _onSuccessAction
_resolveAction(type, config, pagestate)
return
}
if (onSuccessAction) {
resolveAction(onSuccessAction)
return
}
})
}
// 发送表单数据
sendFormData = async (values: JsonSchema.DynamicObject): Promise<any> => {
const {
method = 'get' as JsonSchema.Method,
isShowSuccessMessage,
} = this.props
const url = this.resolveURL()
if (!url) {
throw new Error('缺少url')
}
let res
try {
this.setPageLoading(true)
res = await request[method as 'get'](url, values)
if (isShowSuccessMessage) {
message.success(res.message || '请求成功')
}
this.setPageLoading(false)
return res
} catch (e) {
this.setPageLoading(false)
throw e
}
}
// 过滤表单提交字段
filterFields = (values: JsonSchema.DynamicObject) => {
let result: JsonSchema.DynamicObject = {}
Object.keys(values)
.filter(filed => !this.ignoreFields[filed])
.forEach(field => {
result[field] = values[field]
})
return result
}
/**
* 渲染Fields
*/
renderFields = (fileds: TypeField[], span: number, form: form) => {
const { pagestate } = this.props
if (isArray(fileds)) {
this.cols = 0
return fileds.map((item, i) => {
const {
'v-if': vIf,
ignore,
type = 'Input',
colProps = {},
field,
...rest
} = item
if (vIf !== undefined && !vIf) {
return null
}
this.cols += span
if (ignore && !this.ignoreFields[item.field]) {
this.ignoreFields[item.field] = 1
}
const dataPageconfigPath = `${this.props['data-pageconfig-path']}.props.fields[${i}]`
let reg = /^HtField\./
let _type = reg.test(type) ? type : `HtField.${type}`
return (
<Field
colProps={{
span: _.isNumber(colProps?.span) ? colProps?.span : span,
..._.omit(colProps, ['span']),
}}
key={i}
{...omit(rest, ['value'])}
field={field}
type={type}
form={form}
pagestate={pagestate}
data-pageconfig-path={dataPageconfigPath}
data-component-type={_type}
/>
)
})
}
return null
}
/**
* 渲染Form按钮
*/
renderButtons = (
buttons: FormButtonType[],
span: number,
labelCol: JsonSchema.ColComponentProps,
wrapperCol: JsonSchema.ColComponentProps
// eslint-disable-next-line max-params
) => {
const {
submitButtonText,
backButtonText,
resetButtonText,
redirectToButtonText,
downloadButtonText,
buttonGroupProps,
} = this.props
if (!isArray(buttons) || buttons.length === 0) {
return null
}
type ButtonMap = {
[key in FormButtonType]: React.ReactNode
}
const map: ButtonMap = {
submit: (
<Button
className="ht-btn-submit"
onClick={this.resetAndSubmit}
type="primary"
>
{submitButtonText}
</Button>
),
reset: (
<Button className="ht-btn-reset" onClick={this.reset}>
{resetButtonText}
</Button>
),
redirectTo: (
<Button
className="ht-btn-submit"
onClick={() => this.redirectTo()}
type="primary"
>
{redirectToButtonText}
</Button>
),
openWindow: (
<Button
className="ht-btn-submit"
onClick={() => this.openWindow()}
type="primary"
>
{redirectToButtonText}
</Button>
),
back: (
<Button className="ht-btn-back" onClick={this.back}>
{backButtonText}
</Button>
),
download: (
<Button
className="ht-btn-submit"
onClick={() => this.download()}
type="primary"
>
{downloadButtonText}
</Button>
),
}
if (isArray(buttons)) {
const Buttons = buttons.map((item, i) => {
let result: any = null
// @ts-ignore
if (map[item]) {
// @ts-ignore
result = map[item]
}
if (React.isValidElement(item)) {
result = item
}
if (!result) {
throw new TypeError(`${item} is not a valid button type`)
}
return (
result &&
React.cloneElement(result, {
key: i,
className: result.props.className + ' ht-form-btn',
})
)
})
let offset = labelCol.span
if (this.cols + span <= 24) {
offset = 0
}
if (wrapperCol.span + offset > 24) {
offset = 0
}
let _span = _.isNumber(buttonGroupProps?.span)
? buttonGroupProps?.span
: span
let _offset = _.isNumber(buttonGroupProps?.offset)
? buttonGroupProps?.offset
: offset
return (
<Col
style={{ whiteSpace: 'nowrap', paddingTop: '4px' }}
{..._.omit(buttonGroupProps, ['span', 'offset'])}
// @ts-ignore
span={_span + _offset > 24 ? 24 - _offset : _span}
offset={_offset}
>
{Buttons}
</Col>
)
}
return null
}
render() {
const { isPageLoading } = this.state
const {
// Card配置
isCard,
extra,
// description,
// form配置
fields,
cols,
labelCol,
wrapperCol,
buttons,
form,
'data-component-type': _dataComponentType,
title,
pagestate,
} = this.props
const span = 24 / (cols as number)
const formItemLayout = {
labelCol,
wrapperCol,
}
return (
<HtCard
isCard={isCard}
title={title}
extra={extra}
pagestate={pagestate}
data-pageconfig-path={`${this.props['data-pageconfig-path']}`}
data-component-type={_dataComponentType}
render={() => (
<div>
<Form
onSubmit={this.submit}
className="ht-form-container"
{...formItemLayout}
>
<Row>
{this.renderFields(fields as TypeField[], span, form)}
{this.renderButtons(
buttons as FormButtonType[],
span,
labelCol as JsonSchema.ColComponentProps,
wrapperCol as JsonSchema.ColComponentProps
)}
</Row>
</Form>
</div>
)}
>
{isPageLoading && <Spin size="large" className="g-spin" />}
</HtCard>
)
}
}
const WrapperForm = Form.create<HtFormProps>({
mapPropsToFields(props: HtFormProps) {
// @ts-ignore
const alias = props.alias || ComponentAlias
const fields = props.fields || []
const formData = get(props, ['pagestate', alias], {})
let result: JsonSchema.DynamicObject = {}
fields.forEach(v => {
const path = v.field
if (path) {
let value = get(formData, path, v.defaultValue)
// @ts-ignore
let otherProperties = _.get(WrapperForm.formMap, [alias, path], {})
set(result, path, Form.createFormField({ ...otherProperties, value }))
}
})
return result
},
onFieldsChange(props, _changedFields, allFields) {
// @ts-ignore
const alias = props.alias || ComponentAlias
// @ts-ignore
_.set(WrapperForm.formMap, [alias], allFields)
},
onValuesChange(props, _values, allValues) {
// @ts-ignore
const alias = props.alias || ComponentAlias
// @ts-ignore
const { setStoreState } = props.pagestate
if (!isFunction(setStoreState)) return
let oldData = _.get(props.pagestate, alias, {})
let formData = { ...oldData, ...allValues }
setStoreState({ [alias]: formData })
},
})(observer(HtForm))
// @ts-ignore
WrapperForm.formMap = {}
export default WrapperForm | the_stack |
import { Activity, ActivityTypes, BotAdapter, TurnContext, ConversationReference, ResourceResponse, WebRequest, WebResponse } from 'botbuilder';
import * as Twitter from 'twitter';
import { TwitterAdapterSettings, TwitterMessage, TwitterActivityAPIMessage, TwitterActivityAPIDirectMessage, TwitterActivityType, TwitterDirectMessage } from './schema';
import { TwitterDirectMessageManager } from './twitterDirectMessage';
import { retrieveBody as rb } from './util';
/**
* @module botbuildercommunity/adapter-twitter
*/
function createTwitterClient(settings: TwitterAdapterSettings): Twitter {
return new Twitter(settings);
}
/*
* The below functions are abstracted out so that they can be replaced by `rewire` during
* mock unit testing. The `rewire` package looks like it'll replace `require()` generated
* variables, but not `import` syntax. Need to update this in a future PR, but don't want to
* halt progress on the adapter.
*/
async function retrieveBody(req: WebRequest): Promise<TwitterActivityAPIMessage & TwitterActivityAPIDirectMessage> {
return await rb(req);
}
function getWebRequest(req: WebRequest): WebRequest {
return req;
}
function getWebResponse(resp: WebResponse): WebResponse {
return resp;
}
export class TwitterAdapter extends BotAdapter {
public client: Twitter;
protected readonly settings: TwitterAdapterSettings;
protected readonly channel: string = 'twitter';
public constructor(settings: TwitterAdapterSettings) {
super();
this.settings = settings;
try {
this.client = this.createTwitterClient(settings);
}
catch (e) {
throw new Error(`Error creating Twitter client: ${ e.message }.`);
}
}
public async sendActivities(context: TurnContext, activities: Partial<Activity>[]): Promise<ResourceResponse[]> {
const responses: ResourceResponse[] = [];
for (let i = 0; i < activities.length; i++) {
const activity: Partial<Activity> = activities[i];
switch (activity.type) {
case ActivityTypes.Message:
if (!activity.conversation || !activity.conversation.id) {
throw new Error(`Activity doesn't contain a conversation id.`);
}
try {
const message: TwitterMessage | TwitterDirectMessage = this.parseActivity(activity);
let res: Twitter.ResponseData;
if(activity.conversation.conversationType === TwitterActivityType.DIRECTMESSAGE) {
res = await TwitterDirectMessageManager.sendDirectMessage(
this.settings.consumer_key,
this.settings.consumer_secret,
this.settings.access_token_key,
this.settings.access_token_secret,
message as TwitterDirectMessage
);
}
else {
res = await this.client.post('statuses/update', message);
}
const id = (res as any).id_str || (res as any).id;
responses.push({ id: id });
}
catch (error) {
throw new Error(`Error parsing activity: ${ error.message }.`);
}
break;
default:
responses.push({} as ResourceResponse);
console.warn(`Unsupported activity type: '${ activity.type }'.`);
break;
}
}
return responses;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public async updateActivity(context: TurnContext, activity: Partial<Activity>): Promise<void> {
throw new Error('Method not supported by the Twitter API.');
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public async deleteActivity(context: TurnContext, reference: Partial<ConversationReference>): Promise<void> {
throw new Error('Method not supported by the Twitter API.');
}
public async continueConversation(reference: Partial<ConversationReference>, logic: (context: TurnContext) => Promise<void>): Promise<void> {
const request: Partial<Activity> = TurnContext.applyConversationReference(
{ type: 'event', name: 'continueConversation' },
reference,
true
);
const context: TurnContext = this.createContext(request);
return this.runMiddleware(context, logic);
}
public async processActivity(request: WebRequest, response: WebResponse, logic: (context: TurnContext) => Promise<any>): Promise<void> {
//If not a unit test, this just returns itself
const req = getWebRequest(request);
const res = getWebResponse(response);
const body = await retrieveBody(req);
let message: TwitterMessage = { } as any;
let directMessage: TwitterDirectMessage = { } as any;
let messageType: TwitterActivityType;
let selfMessage = false;
try {
if(body.tweet_create_events !== undefined && body.tweet_create_events.length > 0) {
message = body.tweet_create_events[0];
if(message.user.screen_name === this.settings.screen_name) {
selfMessage = true;
}
messageType = TwitterActivityType.TWEET;
}
else if(body.direct_message_events !== undefined && body.direct_message_events.length > 0) {
directMessage = body.direct_message_events[0];
message = body.direct_message_events[0].message_create.message_data;
const users: any[] = (body as any).users;
const keys: string[] = Object.keys((body as any).users);
for(const user of keys) {
const obj = users[user];
if(obj.screen_name === this.settings.screen_name) {
if(body.direct_message_events[0].message_create.sender_id === obj.id) {
selfMessage = true;
}
}
if(body.direct_message_events[0].message_create.sender_id === obj.id) {
(directMessage as any).sender_id = obj.id;
(directMessage as any).sender_name = obj.screen_name;
}
if(body.direct_message_events[0].message_create.target.recipient_id === obj.id) {
(directMessage as any).recipient_id = obj.id;
(directMessage as any).recipient_name = obj.screen_name;
}
}
messageType = TwitterActivityType.DIRECTMESSAGE;
}
else {
message = body as any;
selfMessage = true;
}
}
catch(e) {
res.status(500);
res.send(`Failed to retrieve message body: ${ e }`);
res.end();
}
if (message === null) {
res.status(400);
res.end();
}
const activity = this.getActivityFromTwitterMessage(message, directMessage, messageType);
if(selfMessage) {
activity.type = ActivityTypes.Trace;
}
const context: TurnContext = this.createContext(activity);
context.turnState.set('httpStatus', 200);
await this.runMiddleware(context, logic);
res.status(context.turnState.get('httpStatus'));
if (context.turnState.get('httpBody')) {
res.send(context.turnState.get('httpBody'));
}
else {
res.end();
}
}
protected createContext(request: Partial<Activity>): TurnContext {
return new TurnContext(this as any, request);
}
protected createTwitterClient(settings: TwitterAdapterSettings): Twitter {
return createTwitterClient(settings);
}
protected parseActivity(activity: Partial<Activity>): TwitterMessage | TwitterDirectMessage {
if(activity.conversation.conversationType === TwitterActivityType.DIRECTMESSAGE) {
return this.createDirectMessage(activity);
}
return this.createTweet(activity);
}
protected createDirectMessage(activity: Partial<Activity>): TwitterDirectMessage {
const message: TwitterDirectMessage = { } as any;
message.type = 'message_create';
message.message_create = {
target: {
recipient_id: activity.recipient.id
},
message_data: {
id: activity.id as any as number,
id_str: activity.id,
in_reply_to_status_id: activity.conversation.id,
in_reply_to_screen_name: activity.recipient.name,
text: activity.text
}
};
if (activity.attachments && activity.attachments.length > 0) {
const attachment = activity.attachments[0];
message.message_create.message_data.attachment_url = attachment.contentUrl;
}
return message;
}
protected createTweet(activity: Partial<Activity>): TwitterMessage {
const message: TwitterMessage = { } as any;
message.status = activity.text;
if(activity.conversation.id.indexOf('-') === -1) {
message.in_reply_to_status_id = activity.conversation.id;
}
const mention = activity.recipient.name;
if(mention !== null && !message.status.startsWith(mention)) {
message.status = `@${ mention } ${ message.status }`;
}
if (activity.attachments && activity.attachments.length > 0) {
const attachment = activity.attachments[0];
message.attachment_url = attachment.contentUrl;
}
return message;
}
protected getActivityFromTweet(message: TwitterMessage, messageType: TwitterActivityType): Partial<Activity> {
return {
id: (message.id_str !== undefined) ? message.id_str : message.id as any as string,
timestamp: new Date(),
channelId: this.channel,
conversation: {
id: (message.id_str !== undefined) ? message.id_str : message.id as any as string,
isGroup: false,
conversationType: messageType,
tenantId: null,
name: ''
},
from: {
id: (message.user !== undefined) ? message.user.id as any as string : null,
name: (message.user !== undefined) ? message.user.screen_name : null
},
recipient: {
id: message.in_reply_to_screen_name,
name: message.in_reply_to_screen_name
},
text: message.text,
channelData: message,
localTimezone: null,
callerId: null,
serviceUrl: null,
listenFor: null,
label: message.id as any as string,
valueType: null,
type: (messageType != null) ? ActivityTypes.Message : null
};
}
protected getActivityFromDirectMessage(message: TwitterMessage, directMessage: TwitterDirectMessage, messageType: TwitterActivityType): Partial<Activity> {
return {
id: directMessage.id as any as string,
timestamp: new Date(),
channelId: this.channel,
conversation: {
id: directMessage.id as any as string,
isGroup: false,
conversationType: messageType,
tenantId: null,
name: ''
},
from: {
id: (directMessage as any).sender_id,
name: (directMessage as any).sender_name,
},
recipient: {
id: (directMessage as any).recipient_id,
name: (directMessage as any).recipient_name
},
text: message.text,
channelData: message,
localTimezone: null,
callerId: null,
serviceUrl: null,
listenFor: null,
label: directMessage.id as any as string,
valueType: null,
type: (messageType != null) ? ActivityTypes.Message : null
};
}
protected getActivityFromTwitterMessage(message: TwitterMessage, directMessage: TwitterDirectMessage, messageType: TwitterActivityType): Partial<Activity> {
const activity = (messageType === TwitterActivityType.DIRECTMESSAGE)
? this.getActivityFromDirectMessage(message, directMessage, messageType)
: this.getActivityFromTweet(message, messageType);
if (activity.type === ActivityTypes.Message) {
if(message.entities !== undefined
&& message.entities.media !== undefined
&& message.entities.media.length > 0) {
const media = message.entities.media;
activity.attachments = [];
for (const medium of media) {
let contentType: string;
/*
* Likely need to do a little more parsing of the content/mime type.
*/
switch(medium.type) {
case 'photo':
contentType = 'image/png';
break;
case 'video':
contentType = 'video/mpeg';
break;
case 'animated_gif':
contentType = 'image/gif';
break;
default:
break;
}
const attachment = {
contentType: contentType,
contentUrl: medium.media_url_https
};
activity.attachments.push(attachment);
}
}
}
return activity;
}
} | the_stack |
// WARNING: Do not edit the *.js version of this file. Instead, always edit the
// corresponding *.ts source in the ts subfolder, and then invoke the
// compileTypescript.sh bash script to generate new *.js and *.js.map files.
module workbench {
export module paging {
var KT = 'know_total';
var OFFSET = 'offset';
export var LIMIT = 'limit';
export var LIM_ID = '#' + LIMIT;
var AMP = decodeURIComponent('%26');
function addCookieToUrlQueryIfPresent(url: string, name: string){
var value = workbench.getCookie(name);
if (value) {
url = url + AMP + name + '=' + value;
}
return url;
}
/**
* Invoked in graph.xsl and tuple.xsl for download functionality. Takes a
* document element by name, and creates a request with it as a parameter.
*/
export function addGraphParam(name: string) {
var value = encodeURIComponent($('#' + name).val());
var url = document.location.href;
var ref = workbench.getCookie('ref');
if (url.match(/query$/)) { // looking at POST query results?
if ('id' == ref) {
url = url + ';ref=id' + AMP + 'action=exec';
url = addCookieToUrlQueryIfPresent(url, 'query');
url = addCookieToUrlQueryIfPresent(url, 'queryLn');
url = addCookieToUrlQueryIfPresent(url, 'infer');
url = addCookieToUrlQueryIfPresent(url, 'limit_query');
} else {
alert("Can't put query in URL, since it might be too long for your browser.\n" +
"Save your query on the server, then execute it from the 'Saved Queries' page.");
return;
}
}
if (url.indexOf('?') + 1 || url.indexOf(';') + 1) {
document.location.href = url + AMP + name + '=' + value;
} else {
document.location.href = url + ';' + name + '=' + value;
}
}
class StringMap {
[key: string]: string;
}
/**
* Scans the given URI for duplicate query parameter names, and removes
* all but the last occurrence for any duplicate case.
*
* @param {String} href The URI to simplify.
* @returns {String} The URI with only the last occurrence of any
* given parameter name remaining.
*/
function simplifyParameters(href: string) {
var params:StringMap = {};
var rval = '';
var queryString = getQueryString(href);
var start = href.substring(0, href.indexOf(queryString));
var elements = queryString.split(decodeURIComponent('%26'));
for (var i = 0; elements.length - i; i++) {
var pair = elements[i].split('=');
params[pair[0]] = pair[1];
// Keep looping. We are interested in the last value.
}
for (var name in params) {
// use hasOwnProperty to filter out keys from the
// Object.prototype
if (params.hasOwnProperty(name)) {
rval += name + '=' + params[name] + AMP;
}
}
rval = start + rval.substring(0, rval.length - 1);
return rval;
}
/**
* First, adds the given parameter to the URL query string. Second,
* adds a 'know_total' parameter if its current value is 'false' or
* non-existent. Third, simplifies the URL. Fourth, sends the browser
* to the modified URL.
*
* @param {String} name The name of the query parameter.
* @param {number} value The value of the query parameter.
*/
export function addPagingParam(name: string, value: number) {
var url = document.location.href;
var hasParams = (url.indexOf('?') + 1 || url.indexOf(';') + 1);
var sep = hasParams ? AMP : ';';
url = url + sep + name + '=' + value;
if (!hasQueryParameter(KT) || 'false' == getQueryParameter(KT)) {
url += AMP + KT + '=' + getTotalResultCount();
}
if (!hasQueryParameter('query')) {
url += AMP + 'query=' + encodeURIComponent(workbench.getCookie('query'));
url += AMP + 'ref=' + encodeURIComponent(workbench.getCookie('ref'));
}
document.location.href = simplifyParameters(url);
}
/**
* Invoked in tuple.xsl and explore.xsl. Changes the limit query
* parameter and navigates to the new URL.
*/
export function addLimit(page: string) {
var suffix = '_' + page;
addPagingParam(LIMIT + suffix, $(LIM_ID + suffix).val());
}
/**
* Invoked in tuple.xsl and explore.xsl. Increments the offset query
* parameter, and navigates to the new URL.
*/
export function nextOffset(page: string) {
addPagingParam(OFFSET, getOffset() + getLimit(page));
}
/**
* Invoked in tuple.xsl and explore.xsl. Decrements the offset query
* parameter and navigates to the new URL.
*/
export function previousOffset(page: string) {
addPagingParam(OFFSET, Math.max(0, getOffset() - getLimit(page)));
}
/**
* @returns {number} The value of the offset query parameter.
*/
export function getOffset() {
var offset = getQueryParameter(OFFSET);
return ('' == offset) ? 0 : parseInt(offset, 10);
}
/**
* @returns {number} The value of the limit query parameter.
*/
export function getLimit(page: string): number {
return parseInt($(LIM_ID + '_' + page).val(), 10);
}
/**
* Retrieves the URL query parameter with the given name.
*
* @param {String} name The name of the parameter to retrieve.
* @returns {String} The value of the given parameter, or an empty
* string if it doesn't exist.
*/
export function getQueryParameter(name: string): string {
var rval = '';
var elements = getQueryString(document.location.href).split(decodeURIComponent('%26'));
for (var i = 0; elements.length - i; i++) {
var pair = elements[i].split('=');
if (name != pair[0]) {
continue;
}
rval = pair[1];
// Keep looping. We are interested in the last value.
}
return rval;
}
/**
* Gets whether a URL query parameter with the given name is present.
*
* @param {String} name The name of the parameter to retrieve.
* @returns {Boolean} True, if a parameter with the given name is in
* the URL. Otherwise, false.
*/
export function hasQueryParameter(name: string) {
var rval = false;
var elements = getQueryString(document.location.href).split(decodeURIComponent('%26'));
for (var i = 0; elements.length - i; i++) {
var pair = elements[i].split('=');
if (name == pair[0]) {
rval = true;
break;
}
}
return rval;
}
/**
* Convenience function for returning the tail of a string after a
* given character.
*
* @param {String} value The string to get the tail of.
* @param split
* character to give tail after
* @returns The substring after the 'split' character, or the original
* string if 'split' is not found.
*/
function tailAfter(value: string, split: string): string {
return value.substring(value.indexOf(split) + 1);
}
export function getQueryString(href: string) {
return tailAfter(tailAfter(href, '?'), ';');
}
/**
* Using the value of the 'limit' query parameter, correct the text of the
* Next and Previous buttons. Makes use of RegExp to preserve any
* localization.
*/
export function correctButtons(page: string) {
var buttonWordPattern = /^[A-z]+\s+/;
var nextButton = $('#nextX');
var oldNext = nextButton.val();
var count = parseInt(/\d+$/.exec(oldNext)[0], 10);
var limit = workbench.paging.getLimit(page);
nextButton.val(buttonWordPattern.exec(oldNext)[0] + limit);
var previousButton = $('#previousX');
previousButton
.val(buttonWordPattern.exec(previousButton.val())[0] + limit);
var offset = workbench.paging.getOffset();
previousButton.prop('disabled', (offset <= 0 || limit <= 0));
nextButton.prop('disabled',
(count < limit || limit <= 0 || (offset + count) >= getTotalResultCount()));
}
/**
* Gets the total result count, preferably from the 'know_total' query
* parameter. If the parameter doesn't exist, get it from the
* 'total_result_count' cookie.
*
* @returns {Number} The given total result count, or zero if it isn't
* given.
*/
export function getTotalResultCount() {
var total_result_count = 0;
var s_trc = workbench.paging.getQueryParameter(KT);
if (s_trc.length == 0) {
s_trc = workbench.getCookie('total_result_count');
}
if (s_trc.length > 0) {
total_result_count = parseInt(s_trc, 10);
}
return total_result_count;
}
module DataTypeVisibility {
function setCookie(c_name: string, value: boolean, exdays: number) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
document.cookie = c_name + "=" + value +
((exdays == null) ? "" :
"; expires=" + exdate.toUTCString());
}
export function setShow(show: boolean) {
setCookie('show-datatypes', show, 365);
var data = show ? 'data-longform' : 'data-shortform';
$('div.resource[' + data + ']').each(function() {
var me = $(this);
me.find('a:first').text(decodeURIComponent(me.attr(data)));
});
}
}
export function setShowDataTypesCheckboxAndSetChangeEvent() {
var hideDataTypes = (workbench.getCookie('show-datatypes') == 'false');
var showDTcb = $("input[name='show-datatypes']");
if (hideDataTypes) {
showDTcb.prop('checked', false);
DataTypeVisibility.setShow(false);
}
showDTcb.on('change', function() {
DataTypeVisibility.setShow(showDTcb.prop('checked'));
});
}
}
} | the_stack |
import drag from '@interactjs/actions/drag/plugin'
import drop from '@interactjs/actions/drop/plugin'
import autoStart from '@interactjs/auto-start/base'
import type { PointerType } from '@interactjs/types/index'
import extend from '@interactjs/utils/extend'
import * as pointerUtils from '@interactjs/utils/pointerUtils'
import type { EventPhase } from './InteractEvent'
import { InteractEvent } from './InteractEvent'
import { Interaction } from './Interaction'
import * as helpers from './tests/_helpers'
describe('core/Interaction', () => {
test('constructor', () => {
const testType = 'test'
const dummyScopeFire = () => {}
const interaction = new Interaction({
pointerType: testType,
scopeFire: dummyScopeFire,
})
const zeroCoords = {
page: { x: 0, y: 0 },
client: { x: 0, y: 0 },
timeStamp: 0,
}
// scopeFire option is set assigned to interaction._scopeFire
expect(interaction._scopeFire).toBe(dummyScopeFire)
expect(interaction.prepared).toEqual(expect.any(Object))
expect(interaction.downPointer).toEqual(expect.any(Object))
// `interaction.coords.${coordField} set to zero`
expect(interaction.coords).toEqual({
start: zeroCoords,
cur: zeroCoords,
prev: zeroCoords,
delta: zeroCoords,
velocity: zeroCoords,
})
// interaction.pointerType is set
expect(interaction.pointerType).toBe(testType)
// interaction.pointers is initially an empty array
expect(interaction.pointers).toEqual([])
// false properties
expect(interaction).toMatchObject({ pointerIsDown: false, pointerWasMoved: false, _interacting: false })
expect(interaction.pointerType).not.toBe('mouse')
})
test('Interaction destroy', () => {
const { interaction } = helpers.testEnv()
const pointer = { pointerId: 10 } as any
const event = {} as any
interaction.updatePointer(pointer, event, null)
interaction.destroy()
// interaction._latestPointer.pointer is null
expect(interaction._latestPointer.pointer).toBeNull()
// interaction._latestPointer.event is null
expect(interaction._latestPointer.event).toBeNull()
// interaction._latestPointer.eventTarget is null
expect(interaction._latestPointer.eventTarget).toBeNull()
})
test('Interaction.getPointerIndex', () => {
const { interaction } = helpers.testEnv()
interaction.pointers = [2, 4, 5, 0, -1].map((id) => ({ id })) as any
interaction.pointers.forEach(({ id }, index) => {
expect(interaction.getPointerIndex({ pointerId: id } as any)).toBe(index)
})
})
describe('Interaction.updatePointer', () => {
test('no existing pointers', () => {
const { interaction } = helpers.testEnv()
const pointer = { pointerId: 10 } as any
const event = {} as any
const ret = interaction.updatePointer(pointer, event, null)
// interaction.pointers == [{ pointer, ... }]
expect(interaction.pointers).toEqual([
{
id: pointer.pointerId,
pointer,
event,
downTime: null,
downTarget: null,
},
])
// new pointer index is returned
expect(ret).toBe(0)
})
test('new pointer with exisiting pointer', () => {
const { interaction } = helpers.testEnv()
const existing: any = { pointerId: 0 }
const event: any = {}
interaction.updatePointer(existing, event, null)
const newPointer: any = { pointerId: 10 }
const ret = interaction.updatePointer(newPointer, event, null)
// interaction.pointers == [{ pointer: existing, ... }, { pointer: newPointer, ... }]
expect(interaction.pointers).toEqual([
{
id: existing.pointerId,
pointer: existing,
event,
downTime: null,
downTarget: null,
},
{
id: newPointer.pointerId,
pointer: newPointer,
event,
downTime: null,
downTarget: null,
},
])
// second pointer index is 1
expect(ret).toBe(1)
})
test('update existing pointers', () => {
const { interaction } = helpers.testEnv()
const oldPointers = [-3, 10, 2].map((pointerId) => ({ pointerId }))
const newPointers = oldPointers.map((pointer) => ({ ...pointer, new: true }))
oldPointers.forEach((pointer: any) => interaction.updatePointer(pointer, pointer, null))
newPointers.forEach((pointer: any) => interaction.updatePointer(pointer, pointer, null))
// number of pointers is unchanged
expect(interaction.pointers).toHaveLength(oldPointers.length)
interaction.pointers.forEach((pointerInfo, i) => {
// `pointer[${i}].id is the same`
expect(pointerInfo.id).toBe(oldPointers[i].pointerId)
// `new pointer ${i} !== old pointer object`
expect(pointerInfo.pointer).not.toBe(oldPointers[i])
})
})
})
test('Interaction.removePointer', () => {
const { interaction } = helpers.testEnv()
const ids = [0, 1, 2, 3]
const removals = [
{ id: 0, remain: [1, 2, 3], message: 'first of 4' },
{ id: 2, remain: [1, 3], message: 'middle of 3' },
{ id: 3, remain: [1], message: 'last of 2' },
{ id: 1, remain: [], message: 'final' },
]
ids.forEach((pointerId) => interaction.updatePointer({ pointerId } as any, {} as any, null))
for (const removal of removals) {
interaction.removePointer({ pointerId: removal.id } as PointerType, null)
// `${removal.message} - remaining interaction.pointers is correct`
expect(interaction.pointers.map((p) => p.id)).toEqual(removal.remain)
}
})
test('Interaction.pointer{Down,Move,Up} updatePointer', () => {
const { scope, interaction } = helpers.testEnv()
const eventTarget: any = {}
const pointer: any = {
target: eventTarget,
pointerId: 0,
}
let info: any = {}
scope.addListeners({
'interactions:update-pointer': (arg) => {
info.updated = arg.pointerInfo
},
'interactions:remove-pointer': (arg) => {
info.removed = arg.pointerInfo
},
})
interaction.coords.cur.timeStamp = 0
const commonPointerInfo: any = {
id: 0,
pointer,
event: pointer,
downTime: null,
downTarget: null,
}
interaction.pointerDown(pointer, pointer, eventTarget)
// interaction.pointerDown updates pointer
expect(info.updated).toEqual({
...commonPointerInfo,
downTime: interaction.coords.cur.timeStamp,
downTarget: eventTarget,
})
// interaction.pointerDown doesn't remove pointer
expect(info.removed).toBeUndefined()
interaction.removePointer(pointer, null)
info = {}
interaction.pointerMove(pointer, pointer, eventTarget)
// interaction.pointerMove updates pointer
expect(info.updated).toEqual(commonPointerInfo)
// interaction.pointerMove doesn't remove pointer
expect(info.removed).toBeUndefined()
info = {}
interaction.pointerUp(pointer, pointer, eventTarget, null)
// interaction.pointerUp doesn't update existing pointer
expect(info.updated).toBeUndefined()
info = {}
interaction.pointerUp(pointer, pointer, eventTarget, null)
// interaction.pointerUp updates non existing pointer
expect(info.updated).toEqual(commonPointerInfo)
// interaction.pointerUp also removes pointer
expect(info.removed).toEqual(commonPointerInfo)
info = {}
})
test('Interaction.pointerDown', () => {
const { interaction, scope, coords, event, target } = helpers.testEnv()
let signalArg: any
const coordsSet = helpers.newCoordsSet()
scope.now = () => coords.timeStamp
extend(coords, {
target,
type: 'down',
})
const signalListener = (arg: any) => {
signalArg = arg
}
scope.addListeners({
'interactions:down': signalListener,
})
const pointerCoords: any = { page: {}, client: {} }
pointerUtils.setCoords(pointerCoords, [event], event.timeStamp)
for (const prop in coordsSet) {
pointerUtils.copyCoords(
interaction.coords[prop as keyof typeof coordsSet],
coordsSet[prop as keyof typeof coordsSet],
)
}
// downPointer is initially empty
expect(interaction.downPointer).toEqual({} as any)
// test while interacting
interaction._interacting = true
interaction.pointerDown(event, event, target)
// downEvent is not updated
expect(interaction.downEvent).toBeNull()
// pointer is added
expect(interaction.pointers).toEqual([
{
id: event.pointerId,
event,
pointer: event,
downTime: 0,
downTarget: target,
},
])
// downPointer is updated
expect(interaction.downPointer).not.toEqual({} as any)
// coords.start are not modified
expect(interaction.coords.start).toEqual(coordsSet.start)
// coords.prev are not modified
expect(interaction.coords.prev).toEqual(coordsSet.prev)
// coords.cur *are* modified
expect(interaction.coords.cur).toEqual(helpers.getProps(event, ['page', 'client', 'timeStamp']))
// pointerIsDown
expect(interaction.pointerIsDown).toBe(true)
// !pointerWasMoved
expect(interaction.pointerWasMoved).toBe(false)
// pointer in down signal arg
expect(signalArg.pointer).toBe(event)
// event in down signal arg
expect(signalArg.event).toBe(event)
// eventTarget in down signal arg
expect(signalArg.eventTarget).toBe(target)
// pointerIndex in down signal arg
expect(signalArg.pointerIndex).toBe(0)
// test while not interacting
interaction._interacting = false
// reset pointerIsDown
interaction.pointerIsDown = false
// pretend pointer was moved
interaction.pointerWasMoved = true
// reset signalArg object
signalArg = undefined
interaction.removePointer(event, null)
interaction.pointerDown(event, event, target)
// timeStamp is assigned with new Date.getTime()
// don't let it cause deepEaual to fail
pointerCoords.timeStamp = interaction.coords.start.timeStamp
// downEvent is updated
expect(interaction.downEvent).toBe(event)
// interaction.pointers is updated
expect(interaction.pointers).toEqual([
{
id: event.pointerId,
event,
pointer: event,
downTime: pointerCoords.timeStamp,
downTarget: target,
},
])
// coords.start are set to pointer
expect(interaction.coords.start).toEqual(pointerCoords)
// coords.cur are set to pointer
expect(interaction.coords.cur).toEqual(pointerCoords)
// coords.prev are set to pointer
expect(interaction.coords.prev).toEqual(pointerCoords)
// down signal was fired again
expect(signalArg).toBeInstanceOf(Object)
// pointerIsDown
expect(interaction.pointerIsDown).toBe(true)
// pointerWasMoved should always change to false
expect(interaction.pointerWasMoved).toBe(false)
})
test('Interaction.start', () => {
const { interaction, interactable, scope, event, target: element, down, stop } = helpers.testEnv({
plugins: [drag],
})
const action = { name: 'drag' } as const
interaction.start(action, interactable, element)
// do nothing if !pointerIsDown
expect(interaction.prepared.name).toBeNull()
// pointers is still empty
interaction.pointerIsDown = true
interaction.start(action, interactable, element)
// do nothing if too few pointers are down
expect(interaction.prepared.name).toBeNull()
down()
interaction._interacting = true
interaction.start(action, interactable, element)
// do nothing if already interacting
expect(interaction.prepared.name).toBeNull()
interaction._interacting = false
interactable.options[action.name] = { enabled: false }
interaction.start(action, interactable, element)
// do nothing if action is not enabled
expect(interaction.prepared.name).toBeNull()
interactable.options[action.name] = { enabled: true }
let signalArg: any
// let interactingInStartListener
const signalListener = (arg: any) => {
signalArg = arg
// interactingInStartListener = arg.interaction.interacting()
}
scope.addListeners({
'interactions:action-start': signalListener,
})
interaction.start(action, interactable, element)
// action is prepared
expect(interaction.prepared.name).toBe(action.name)
// interaction.interactable is updated
expect(interaction.interactable).toBe(interactable)
// interaction.element is updated
expect(interaction.element).toBe(element)
// t.assert(interactingInStartListener, 'interaction is interacting during action-start signal')
// interaction is interacting after start method
expect(interaction.interacting()).toBe(true)
// interaction in signal arg
expect(signalArg.interaction).toBe(interaction)
// event (interaction.downEvent) in signal arg
expect(signalArg.event).toBe(event)
stop()
})
test('interaction move() and stop() from start event', () => {
const { interaction, interactable, target, down } = helpers.testEnv({ plugins: [drag, drop, autoStart] })
let stoppedBeforeStartFired: boolean
interactable.draggable({
listeners: {
start (event) {
stoppedBeforeStartFired = interaction._stopped
// interaction.move() doesn't throw from start event
expect(() => event.interaction.move()).not.toThrow()
// interaction.stop() doesn't throw from start event
expect(() => event.interaction.stop()).not.toThrow()
},
},
})
down()
interaction.start({ name: 'drag' }, interactable, target as HTMLElement)
// !interaction._stopped in start listener
expect(stoppedBeforeStartFired).toBe(false)
// interaction can be stopped from start event listener
expect(interaction.interacting()).toBe(false)
// interaction._stopped after stop() in start listener
expect(interaction._stopped).toBe(true)
})
test('Interaction createPreparedEvent', () => {
const { interaction, interactable, target } = helpers.testEnv()
const action = { name: 'resize' } as const
const phase = 'TEST_PHASE' as EventPhase
interaction.prepared = action
interaction.interactable = interactable
interaction.element = target
interaction.prevEvent = { page: {}, client: {}, velocity: {} } as any
const iEvent = interaction._createPreparedEvent({} as any, phase)
expect(iEvent).toBeInstanceOf(InteractEvent)
expect(iEvent.type).toBe(action.name + phase)
expect(iEvent.interactable).toBe(interactable)
expect(iEvent.target).toBe(interactable.target)
})
test('Interaction fireEvent', () => {
const { interaction, interactable } = helpers.testEnv()
const iEvent = {} as InteractEvent
// this method should be called from actions.firePrepared
interactable.fire = jest.fn()
interaction.interactable = interactable
interaction._fireEvent(iEvent)
// target interactable's fire method is called
expect(interactable.fire).toHaveBeenCalledWith(iEvent)
// interaction.prevEvent is updated
expect(interaction.prevEvent).toBe(iEvent)
})
}) | the_stack |
import * as msRest from "@azure/ms-rest-js";
/**
* Filters to be applied when traversing a data source.
*/
export interface TrainSourceFilter {
/**
* A case-sensitive prefix string to filter content
* under the source location. For e.g., when using a Azure Blob
* Uri use the prefix to restrict subfolders for content.
*/
prefix?: string;
/**
* A flag to indicate if sub folders within the set of
* prefix folders will also need to be included when searching
* for content to be preprocessed.
*/
includeSubFolders?: boolean;
}
/**
* Contract to initiate a train request.
*/
export interface TrainRequest {
/**
* Get or set source path.
*/
source: string;
/**
* Get or set filter to further search the
* source path for content.
*/
sourceFilter?: TrainSourceFilter;
}
/**
* An interface representing FormDocumentReport.
*/
export interface FormDocumentReport {
/**
* Reference to the data that the report is for.
*/
documentName?: string;
/**
* Total number of pages trained on.
*/
pages?: number;
/**
* List of errors per page.
*/
errors?: string[];
/**
* Status of the training operation. Possible values include: 'success', 'partialSuccess',
* 'failure'
*/
status?: Status;
}
/**
* Error reported during an operation.
*/
export interface FormOperationError {
/**
* Message reported during the train operation.
*/
errorMessage?: string;
}
/**
* Response of the Train API call.
*/
export interface TrainResult {
/**
* Identifier of the model.
*/
modelId?: string;
/**
* List of documents used to train the model and the
* train operation error reported by each.
*/
trainingDocuments?: FormDocumentReport[];
/**
* Errors returned during the training operation.
*/
errors?: FormOperationError[];
}
/**
* Result of an operation to get
* the keys extracted by a model.
*/
export interface KeysResult {
/**
* Object mapping ClusterIds to Key lists.
*/
clusters?: { [propertyName: string]: string[] };
}
/**
* Result of a model status query operation.
*/
export interface ModelResult {
/**
* Get or set model identifier.
*/
modelId?: string;
/**
* Get or set the status of model. Possible values include: 'created', 'ready', 'invalid'
*/
status?: Status1;
/**
* Get or set the created date time of the model.
*/
createdDateTime?: Date;
/**
* Get or set the model last updated datetime.
*/
lastUpdatedDateTime?: Date;
}
/**
* Result of query operation to fetch multiple models.
*/
export interface ModelsResult {
/**
* Collection of models.
*/
modelsProperty?: ModelResult[];
}
/**
* An interface representing InnerError.
*/
export interface InnerError {
requestId?: string;
}
/**
* An interface representing ErrorInformation.
*/
export interface ErrorInformation {
code?: string;
innerError?: InnerError;
message?: string;
}
/**
* An interface representing ErrorResponse.
*/
export interface ErrorResponse {
error?: ErrorInformation;
}
/**
* Canonical representation of single extracted text.
*/
export interface ExtractedToken {
/**
* String value of the extracted text.
*/
text?: string;
/**
* Bounding box of the extracted text. Represents the
* location of the extracted text as a pair of
* cartesian co-ordinates. The co-ordinate pairs are arranged by
* top-left, top-right, bottom-right and bottom-left endpoints box
* with origin reference from the bottom-left of the page.
*/
boundingBox?: number[];
/**
* A measure of accuracy of the extracted text.
*/
confidence?: number;
}
/**
* Representation of a key-value pair as a list
* of key and value tokens.
*/
export interface ExtractedKeyValuePair {
/**
* List of tokens for the extracted key in a key-value pair.
*/
key?: ExtractedToken[];
/**
* List of tokens for the extracted value in a key-value pair.
*/
value?: ExtractedToken[];
}
/**
* Extraction information of a column in
* a table.
*/
export interface ExtractedTableColumn {
/**
* List of extracted tokens for the column header.
*/
header?: ExtractedToken[];
/**
* Extracted text for each cell of a column. Each cell
* in the column can have a list of one or more tokens.
*/
entries?: ExtractedToken[][];
}
/**
* Extraction information about a table
* contained in a page.
*/
export interface ExtractedTable {
/**
* Table identifier.
*/
id?: string;
/**
* List of columns contained in the table.
*/
columns?: ExtractedTableColumn[];
}
/**
* Extraction information of a single page in a
* with a document.
*/
export interface ExtractedPage {
/**
* Page number.
*/
number?: number;
/**
* Height of the page (in pixels).
*/
height?: number;
/**
* Width of the page (in pixels).
*/
width?: number;
/**
* Cluster identifier.
*/
clusterId?: number;
/**
* List of Key-Value pairs extracted from the page.
*/
keyValuePairs?: ExtractedKeyValuePair[];
/**
* List of Tables and their information extracted from the page.
*/
tables?: ExtractedTable[];
}
/**
* Analyze API call result.
*/
export interface AnalyzeResult {
/**
* Status of the analyze operation. Possible values include: 'success', 'partialSuccess',
* 'failure'
*/
status?: Status2;
/**
* Page level information extracted in the analyzed
* document.
*/
pages?: ExtractedPage[];
/**
* List of errors reported during the analyze
* operation.
*/
errors?: FormOperationError[];
}
/**
* An object representing a recognized word.
*/
export interface Word {
/**
* Bounding box of a recognized word.
*/
boundingBox: number[];
/**
* The text content of the word.
*/
text: string;
/**
* Qualitative confidence measure. Possible values include: 'High', 'Low'
*/
confidence?: TextRecognitionResultConfidenceClass;
}
/**
* An object representing a recognized text line.
*/
export interface Line {
/**
* Bounding box of a recognized line.
*/
boundingBox?: number[];
/**
* The text content of the line.
*/
text?: string;
/**
* List of words in the text line.
*/
words?: Word[];
}
/**
* An object representing a recognized text region
*/
export interface TextRecognitionResult {
/**
* The 1-based page number of the recognition result.
*/
page?: number;
/**
* The orientation of the image in degrees in the clockwise direction. Range between [0, 360).
*/
clockwiseOrientation?: number;
/**
* The width of the image in pixels or the PDF in inches.
*/
width?: number;
/**
* The height of the image in pixels or the PDF in inches.
*/
height?: number;
/**
* The unit used in the Width, Height and BoundingBox. For images, the unit is 'pixel'. For PDF,
* the unit is 'inch'. Possible values include: 'pixel', 'inch'
*/
unit?: TextRecognitionResultDimensionUnit;
/**
* A list of recognized text lines.
*/
lines: Line[];
}
/**
* Reference to an OCR word.
*/
export interface ElementReference {
ref?: string;
}
/**
* Contains the possible cases for FieldValue.
*/
export type FieldValueUnion = FieldValue | StringValue | NumberValue;
/**
* Base class representing a recognized field value.
*/
export interface FieldValue {
/**
* Polymorphic Discriminator
*/
valueType: "fieldValue";
/**
* OCR text content of the recognized field.
*/
text?: string;
/**
* List of references to OCR words comprising the recognized field value.
*/
elements?: ElementReference[];
}
/**
* A set of extracted fields corresponding to a semantic object, such as a receipt, in the input
* document.
*/
export interface UnderstandingResult {
/**
* List of pages where the document is found.
*/
pages?: number[];
/**
* Dictionary of recognized field values.
*/
fields?: { [propertyName: string]: FieldValueUnion };
}
/**
* Analysis result of the 'Batch Read Receipt' operation.
*/
export interface ReadReceiptResult {
/**
* Status of the read operation. Possible values include: 'Not Started', 'Running', 'Failed',
* 'Succeeded'
*/
status?: TextOperationStatusCodes;
/**
* Text recognition result of the 'Batch Read Receipt' operation.
*/
recognitionResults?: TextRecognitionResult[];
/**
* Semantic understanding result of the 'Batch Read Receipt' operation.
*/
understandingResults?: UnderstandingResult[];
}
/**
* Recognized string field value.
*/
export interface StringValue {
/**
* Polymorphic Discriminator
*/
valueType: "stringValue";
/**
* OCR text content of the recognized field.
*/
text?: string;
/**
* List of references to OCR words comprising the recognized field value.
*/
elements?: ElementReference[];
/**
* String value of the recognized field.
*/
value?: string;
}
/**
* Recognized numeric field value.
*/
export interface NumberValue {
/**
* Polymorphic Discriminator
*/
valueType: "numberValue";
/**
* OCR text content of the recognized field.
*/
text?: string;
/**
* List of references to OCR words comprising the recognized field value.
*/
elements?: ElementReference[];
/**
* Numeric value of the recognized field.
*/
value?: number;
}
/**
* Details about the API request error.
*/
export interface ComputerVisionError {
/**
* The error code.
*/
code: any;
/**
* A message explaining the error reported by the service.
*/
message: string;
/**
* A unique request identifier.
*/
requestId?: string;
}
/**
* An interface representing ImageUrl.
*/
export interface ImageUrl {
/**
* Publicly reachable URL of an image.
*/
url: string;
}
/**
* Optional Parameters.
*/
export interface FormRecognizerClientAnalyzeWithCustomModelOptionalParams extends msRest.RequestOptionsBase {
/**
* An optional list of known keys to extract the values for.
*/
keys?: string[];
}
/**
* Defines headers for BatchReadReceipt operation.
*/
export interface BatchReadReceiptHeaders {
/**
* URL to query for status of the operation. The URL will expire in 48 hours.
*/
operationLocation: string;
}
/**
* Defines headers for BatchReadReceiptInStream operation.
*/
export interface BatchReadReceiptInStreamHeaders {
/**
* URL to query for status of the operation. The URL will expire in 48 hours.
*/
operationLocation: string;
}
/**
* Defines values for TextOperationStatusCodes.
* Possible values include: 'Not Started', 'Running', 'Failed', 'Succeeded'
* @readonly
* @enum {string}
*/
export type TextOperationStatusCodes = 'Not Started' | 'Running' | 'Failed' | 'Succeeded';
/**
* Defines values for TextRecognitionResultDimensionUnit.
* Possible values include: 'pixel', 'inch'
* @readonly
* @enum {string}
*/
export type TextRecognitionResultDimensionUnit = 'pixel' | 'inch';
/**
* Defines values for TextRecognitionResultConfidenceClass.
* Possible values include: 'High', 'Low'
* @readonly
* @enum {string}
*/
export type TextRecognitionResultConfidenceClass = 'High' | 'Low';
/**
* Defines values for Status.
* Possible values include: 'success', 'partialSuccess', 'failure'
* @readonly
* @enum {string}
*/
export type Status = 'success' | 'partialSuccess' | 'failure';
/**
* Defines values for Status1.
* Possible values include: 'created', 'ready', 'invalid'
* @readonly
* @enum {string}
*/
export type Status1 = 'created' | 'ready' | 'invalid';
/**
* Defines values for Status2.
* Possible values include: 'success', 'partialSuccess', 'failure'
* @readonly
* @enum {string}
*/
export type Status2 = 'success' | 'partialSuccess' | 'failure';
/**
* Contains response data for the trainCustomModel operation.
*/
export type TrainCustomModelResponse = TrainResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: TrainResult;
};
};
/**
* Contains response data for the getExtractedKeys operation.
*/
export type GetExtractedKeysResponse = KeysResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: KeysResult;
};
};
/**
* Contains response data for the getCustomModels operation.
*/
export type GetCustomModelsResponse = ModelsResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ModelsResult;
};
};
/**
* Contains response data for the getCustomModel operation.
*/
export type GetCustomModelResponse = ModelResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ModelResult;
};
};
/**
* Contains response data for the analyzeWithCustomModel operation.
*/
export type AnalyzeWithCustomModelResponse = AnalyzeResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AnalyzeResult;
};
};
/**
* Contains response data for the batchReadReceipt operation.
*/
export type BatchReadReceiptResponse = BatchReadReceiptHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: BatchReadReceiptHeaders;
};
};
/**
* Contains response data for the getReadReceiptResult operation.
*/
export type GetReadReceiptResultResponse = ReadReceiptResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ReadReceiptResult;
};
};
/**
* Contains response data for the batchReadReceiptInStream operation.
*/
export type BatchReadReceiptInStreamResponse = BatchReadReceiptInStreamHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: BatchReadReceiptInStreamHeaders;
};
}; | the_stack |
import * as db from '../util/db';
export interface Row {
id : number;
primary_kind : string;
owner : number;
name : string;
description : string;
license : string;
license_gplcompatible : boolean;
website : string;
repository : string;
issue_tracker : string;
source_code : string;
colors_dominant : string;
colors_palette_default : string;
colors_palette_light : string;
category : 'physical' | 'online' | 'data' | 'system';
subcategory : string;
approved_version : number|null;
developer_version : number;
}
export type OptionalFields = 'category' | 'subcategory' | 'approved_version' | 'developer_version';
export interface DiscoveryServiceRow {
device_id : number;
discovery_type : 'bluetooth' | 'upnp';
service : string;
}
export interface VersionedRow {
device_id : number;
version : number;
code : string;
factory : string;
downloadable : boolean;
module_type : string;
mtime : Date;
}
export type VersionedOptionalFields = 'mtime';
export interface KindRow {
device_id : number;
kind : string;
is_child : boolean;
}
async function insertKinds(client : db.Client, deviceId : number, extraKinds : string[], extraChildKinds : string[]) {
const extraValues = [];
for (const k of extraKinds)
extraValues.push([deviceId, k, false]);
for (const k of extraChildKinds)
extraValues.push([deviceId, k, true]);
if (extraValues.length === 0)
return;
await db.query(client, 'insert into device_class_kind(device_id, kind, is_child) values ?',
[extraValues]);
}
async function insertDiscoveryServices(client : db.Client, deviceId : number, discoveryServices : Array<Omit<DiscoveryServiceRow, "device_id">>) {
if (discoveryServices.length === 0)
return;
await db.query(client, 'insert into device_discovery_services(device_id, discovery_type, service) values ?',
[discoveryServices.map((ds) => [deviceId, ds.discovery_type, ds.service])]);
}
async function create<T extends db.Optional<Row, OptionalFields>>(client : db.Client,
device : db.WithoutID<T>,
extraKinds : string[],
extraChildKinds : string[],
discoveryServices : Array<Omit<DiscoveryServiceRow, "device_id">>,
versionedInfo : db.Optional<VersionedRow, "device_id" | "version" | VersionedOptionalFields>) {
device.id = await db.insertOne(client, 'insert into device_class set ?', [device]);
versionedInfo.device_id = device.id;
versionedInfo.version = device.developer_version;
await Promise.all([
insertKinds(client, device.id!, extraKinds, extraChildKinds),
insertDiscoveryServices(client, device.id!, discoveryServices),
db.insertOne(client, `insert into device_code_version set ?`, [versionedInfo])
]);
return device;
}
async function update<T extends Partial<Row>>(client : db.Client, id : number, device : T,
extraKinds : string[], extraChildKinds : string[],
discoveryServices : Array<Omit<DiscoveryServiceRow, "device_id">>,
versionedInfo : db.Optional<VersionedRow, "device_id" | "version" | VersionedOptionalFields>) {
await Promise.all([
db.query(client, "update device_class set ? where id = ?", [device, id]),
db.query(client, "delete from device_class_kind where device_id = ?", [id]),
db.query(client, "delete from device_discovery_services where device_id = ?", [id])
]);
versionedInfo.device_id = id;
versionedInfo.version = device.developer_version;
await Promise.all([
insertKinds(client, id, extraKinds, extraChildKinds),
insertDiscoveryServices(client, id, discoveryServices),
db.insertOne(client, 'insert into device_code_version set ?', [versionedInfo])
]);
return device;
}
export async function get(client : db.Client, id : number) : Promise<Row & { owner_name : string, owner_id_hash : string }> {
return db.selectOne(client, `select d.*, o.name as owner_name, o.id_hash as owner_id_hash
from device_class d left join organizations o on o.id = d.owner where d.id = ?`, [id]);
}
export type ByPrimaryKindRow = Pick<Row, "id"|"name"|"description"|"primary_kind"|"category"
|"subcategory"|"developer_version"|"approved_version"|"website"|"repository"
|"issue_tracker"|"license"|"license_gplcompatible"|"owner">
& { owner_name : string, owner_id_hash : string };
export async function getByPrimaryKind(client : db.Client, kind : string, includeSourceCode : true) : Promise<ByPrimaryKindRow & { source_code : true }>;
export async function getByPrimaryKind(client : db.Client, kind : string, includeSourceCode ?: false) : Promise<ByPrimaryKindRow>;
export async function getByPrimaryKind(client : db.Client, kind : string, includeSourceCode ?: boolean) {
return db.selectOne(client, `select ${includeSourceCode ? 'd.source_code,' : ''}
d.id,d.name,d.description,d.primary_kind,d.category,
d.subcategory,d.developer_version,d.approved_version,
d.website,d.repository,d.issue_tracker,d.license,d.license_gplcompatible,
d.owner,o.name as owner_name, o.id_hash as owner_id_hash
from device_class d left join organizations o on o.id = d.owner where primary_kind = ?`, [kind]);
}
export async function getNamesByKinds(client : db.Client, kinds : string[]) : Promise<Record<string, Pick<Row, "id"|"name"|"primary_kind">>> {
if (kinds.length === 0)
return {};
const rows = await db.selectAll(client, `select id,name,primary_kind from device_class where primary_kind in (?)`, [kinds]);
const ret : Record<string, Pick<Row, "id"|"name"|"primary_kind">> = {};
for (const row of rows)
ret[row.primary_kind] = row;
return ret;
}
export async function getByOwner(client : db.Client, owner : number) : Promise<Array<Pick<Row, "id"|"name"|"primary_kind"|"owner">>> {
return db.selectAll(client, "select id,name,primary_kind,owner from device_class where owner = ? order by name asc", [owner]);
}
type BasicVersionedRow = Pick<Row & VersionedRow, "code" | "version" | "approved_version"
| "developer_version" | "primary_kind" | "name" | "description"
| "category" | "subcategory" | "website" | "repository" | "issue_tracker" | "license">;
export async function getFullCodeByPrimaryKind(client : db.Client, kind : string, orgId : number|null) : Promise<BasicVersionedRow[]> {
if (orgId === -1) {
return db.selectAll(client, "select code, version, approved_version, developer_version, primary_kind, name, description, "
+ "category, subcategory, website, repository, issue_tracker, license from device_code_version dcv, device_class d "
+ "where d.primary_kind = ? and dcv.device_id = d.id "
+ "and dcv.version = d.developer_version", [kind]);
} else if (orgId !== null) {
return db.selectAll(client, "select code, version, approved_version, developer_version, primary_kind, name, description, "
+ "category, subcategory, website, repository, issue_tracker, license from device_code_version dcv, device_class d "
+ "where d.primary_kind = ? and dcv.device_id = d.id "
+ "and ((dcv.version = d.developer_version and d.owner = ?) "
+ "or (dcv.version = d.approved_version and d.owner <> ?))",
[kind, orgId, orgId]);
} else {
return db.selectAll(client, "select code, version, approved_version, developer_version, primary_kind, name, description, "
+ "category, subcategory, website, repository, issue_tracker, license from device_code_version dcv, device_class d "
+ "where d.primary_kind = ? and dcv.device_id = d.id "
+ "and dcv.version = d.approved_version", [kind]);
}
}
export async function getFullCodeByPrimaryKinds(client : db.Client, kinds : string[], orgId : number|null) : Promise<BasicVersionedRow[]> {
if (orgId === -1) {
return db.selectAll(client, "select code, version, approved_version, developer_version, primary_kind, name, description, "
+ "category, subcategory, website, repository, issue_tracker, license from device_code_version dcv, device_class d "
+ "where d.primary_kind in (?) and dcv.device_id = d.id "
+ "and dcv.version = d.developer_version", [kinds]);
} else if (orgId !== null) {
return db.selectAll(client, "select code, version, approved_version, developer_version, primary_kind, name, description, "
+ "category, subcategory, website, repository, issue_tracker, license from device_code_version dcv, device_class d "
+ "where d.primary_kind in (?) and dcv.device_id = d.id "
+ "and ((dcv.version = d.developer_version and d.owner = ?) "
+ "or (dcv.version = d.approved_version and d.owner <> ?))",
[kinds, orgId, orgId]);
} else {
return db.selectAll(client, "select code, version, approved_version, developer_version, primary_kind, name, description, "
+ "category, subcategory, website, repository, issue_tracker, license from device_code_version dcv, device_class d "
+ "where d.primary_kind in (?) and dcv.device_id = d.id "
+ "and dcv.version = d.approved_version", [kinds]);
}
}
type BasicRow = Pick<Row & VersionedRow, "primary_kind" | "name" | "description"
| "category" | "subcategory" | "website" | "repository" | "issue_tracker" | "license">;
type BasicOrg = { id : number, is_admin : boolean };
export async function getByFuzzySearch(client : db.Client, tag : string, org : BasicOrg|null) : Promise<BasicRow[]> {
const pctag = '%' + tag + '%';
if (org !== null && org.is_admin) {
return db.selectAll(client,
`select
primary_kind, name, description, category,
website, repository, issue_tracker, license,
subcategory from device_class where primary_kind = ?
or name like ? or description like ?
or id in (select device_id from device_class_kind where kind = ?)
order by name asc limit 20`,
[tag, pctag, pctag, tag]);
} else if (org !== null) {
return db.selectAll(client,
`select primary_kind, name, description, category,
website, repository, issue_tracker, license,
subcategory from device_class where (primary_kind = ?
or name like ? or description like ?
or id in (select device_id from device_class_kind where kind = ?))
and (approved_version is not null or owner = ?)
order by name asc limit 20`,
[tag, pctag, pctag, tag, org.id]);
} else {
return db.selectAll(client,
`select primary_kind, name, description, category,
website, repository, issue_tracker, license,
subcategory from device_class where (primary_kind = ?
or name like ? or description like ?
or id in (select device_id from device_class_kind where kind = ?))
and approved_version is not null
order by name asc limit 20`,
[tag, pctag, pctag, tag]);
}
}
export async function getCodeByVersion(client : db.Client, id : number, version : number) : Promise<string> {
return db.selectOne(client, "select code from device_code_version where device_id = ? and version = ?",
[id, version]).then((row : { code : string }) => row.code);
}
export type DiscoveryRow = Pick<Row, "id"|"name"|"description"|"primary_kind"|"category"
|"subcategory"|"developer_version"|"approved_version"|"owner"> & { kinds ?: string[] };
export async function getByAnyKind(client : db.Client, kind : string) : Promise<DiscoveryRow[]> {
return db.selectAll(client, `
(select d.id,d.name,d.description,d.primary_kind,d.category,
d.subcategory,d.developer_version,d.approved_version,d.owner from device_class
where primary_kind = ?)
union
(select d.id,d.name,d.description,d.primary_kind,d.category,
d.subcategory,d.developer_version,d.approved_version,d.owner from device_class d,
device_class_kind dk where dk.device_id = d.id and dk.kind = ? and not dk.is_child)`,
[kind, kind]);
}
export async function getByDiscoveryService(client : db.Client, discoveryType : 'upnp'|'bluetooth', service : string) : Promise<DiscoveryRow[]> {
return db.selectAll(client, `select d.id,d.name,d.description,d.primary_kind,d.category,
d.subcategory,d.developer_version,d.approved_version,d.owner from device_class d,
device_discovery_services dds where dds.device_id = d.id and dds.discovery_type = ?
and dds.service = ?`,
[discoveryType, service]);
}
export type FactoryRow = Pick<Row & VersionedRow, "primary_kind"|"category"|"name"|"code"|"factory">;
export async function getByCategoryWithCode(client : db.Client, category : string, org : BasicOrg|null) : Promise<FactoryRow[]> {
if (org !== null && org.is_admin) {
return db.selectAll(client, "select d.primary_kind, d.category, d.name, dcv.code, dcv.factory from device_class d, "
+ "device_code_version dcv where d.id = dcv.device_id and category = ? "
+ "and d.developer_version = dcv.version order by name", [category]);
} else if (org !== null) {
return db.selectAll(client, "select d.primary_kind, d.category, d.name, dcv.code, dcv.factory from device_class d, "
+ "device_code_version dcv where d.id = dcv.device_id and "
+ "((dcv.version = d.developer_version and d.owner = ?) or "
+ " (dcv.version = d.approved_version and d.owner <> ?)) "
+ "and category = ? order by name", [org.id, org.id, category]);
} else {
return db.selectAll(client, "select d.primary_kind, d.category, d.name, dcv.code, dcv.factory from device_class d, "
+ "device_code_version dcv where d.id = dcv.device_id and "
+ "dcv.version = d.approved_version and category = ? order by name", [category]);
}
}
export async function getBySubcategoryWithCode(client : db.Client, category : string, org : BasicOrg|null) : Promise<FactoryRow[]> {
if (org !== null && org.is_admin) {
return db.selectAll(client, "select d.primary_kind, d.category, d.name, dcv.code, dcv.factory from device_class d, "
+ "device_code_version dcv where d.id = dcv.device_id and subcategory = ? "
+ "and d.developer_version = dcv.version order by name", [category]);
} else if (org !== null) {
return db.selectAll(client, "select d.primary_kind, d.category, d.name, dcv.code, dcv.factory from device_class d, "
+ "device_code_version dcv where d.id = dcv.device_id and "
+ "((dcv.version = d.developer_version and d.owner = ?) or "
+ " (dcv.version = d.approved_version and d.owner <> ?)) "
+ "and subcategory = ? order by name", [org.id, org.id, category]);
} else {
return db.selectAll(client, "select d.primary_kind, d.category, d.name, dcv.code, dcv.factory from device_class d, "
+ "device_code_version dcv where d.id = dcv.device_id and "
+ "dcv.version = d.approved_version and subcategory = ? order by name", [category]);
}
}
export async function getAllApprovedWithCode(client : db.Client, org : BasicOrg|null, start ?: number, end ?: number) : Promise<FactoryRow[]> {
if (org !== null && org.is_admin) {
const query = "select d.primary_kind, d.category, d.name, dcv.code, dcv.factory from device_class d, "
+ "device_code_version dcv where d.id = dcv.device_id and "
+ "dcv.version = d.developer_version order by d.name";
if (start !== undefined && end !== undefined) {
return db.selectAll(client, query + " limit ?,?",
[start, end]);
} else {
return db.selectAll(client, query, []);
}
} else if (org !== null) {
const query = "select d.primary_kind, d.category, d.name, dcv.code, dcv.factory from device_class d, "
+ "device_code_version dcv where d.id = dcv.device_id and "
+ "((dcv.version = d.developer_version and d.owner = ?) or "
+ " (dcv.version = d.approved_version and d.owner <> ?)) order by d.name";
if (start !== undefined && end !== undefined) {
return db.selectAll(client, query + " limit ?,?",
[org.id, org.id, start, end]);
} else {
return db.selectAll(client, query, [org.id, org.id]);
}
} else {
const query = "select d.primary_kind, d.category, d.name, dcv.code, dcv.factory from device_class d, "
+ "device_code_version dcv where d.id = dcv.device_id and "
+ "dcv.version = d.approved_version order by d.name";
if (start !== undefined && end !== undefined) {
return db.selectAll(client, query + " limit ?,?",
[start, end]);
} else {
return db.selectAll(client, query, []);
}
}
}
async function _getByField(client : db.Client, field : keyof Row, value : unknown, org : BasicOrg|null, start ?: number, end ?: number) : Promise<BasicRow[]> {
if (org !== null && org.is_admin) {
if (start !== undefined && end !== undefined) {
return db.selectAll(client, `select primary_kind, name, description,
website, repository, issue_tracker, license,
category, subcategory from device_class where ${field} = ? order by name limit ?,?`,
[value, start, end]);
} else {
return db.selectAll(client, `select primary_kind, name, description,
website, repository, issue_tracker, license,
category, subcategory from device_class where ${field} = ? order by name`,
[value]);
}
} else if (org !== null) {
if (start !== undefined && end !== undefined) {
return db.selectAll(client, `select primary_kind, name, description,
website, repository, issue_tracker, license,
category, subcategory from device_class
where (approved_version is not null or owner = ?) and ${field} = ?
order by name limit ?,?`,
[org.id, value, start, end]);
} else {
return db.selectAll(client, `select primary_kind, name, description,
website, repository, issue_tracker, license,
category, subcategory from device_class
where (approved_version is not null or owner = ?) and ${field} = ?
order by name`,
[org.id, value]);
}
} else {
if (start !== undefined && end !== undefined) {
return db.selectAll(client, `select primary_kind, name, description,
website, repository, issue_tracker, license,
category, subcategory from device_class
where approved_version is not null and ${field} = ?
order by name limit ?,?`,
[value, start, end]);
} else {
return db.selectAll(client, `select primary_kind, name, description,
website, repository, issue_tracker, license,
category, subcategory from device_class
where approved_version is not null and ${field} = ?
order by name`, [value]);
}
}
}
export async function getByCategory(client : db.Client, category : string, org : BasicOrg|null, start ?: number, end ?: number) {
return _getByField(client, 'category', category, org, start, end);
}
export async function getBySubcategory(client : db.Client, category : string, org : BasicOrg|null, start ?: number, end ?: number) {
return _getByField(client, 'subcategory', category, org, start, end);
}
type DownloadRow = Pick<Row & VersionedRow, "downloadable" | "owner" | "approved_version" | "version">;
export async function getDownloadVersion(client : db.Client, kind : string, org : BasicOrg|null) : Promise<DownloadRow> {
if (org !== null && org.is_admin) {
return db.selectOne(client, `select downloadable, owner, approved_version, version from
device_class, device_code_version where device_id = id and version = developer_version
and primary_kind = ?`, [kind]);
} else if (org !== null) {
return db.selectOne(client, `select downloadable, owner, approved_version, version from
device_class, device_code_version where device_id = id and
((version = developer_version and owner = ?) or
(version = approved_version and owner <> ?))
and primary_kind = ?`, [org.id, org.id, kind]);
} else {
return db.selectOne(client, `select downloadable, owner, approved_version, version from
device_class, device_code_version where device_id = id and version = approved_version
and primary_kind = ?`, [kind]);
}
}
export async function getAllApprovedByOwner(client : db.Client, owner : number) : Promise<BasicRow[]> {
return db.selectAll(client, `select primary_kind, name, description,
website, repository, issue_tracker, license,
category, subcategory from device_class
where approved_version is not null and owner = ? order by name`, [owner]);
}
export async function getAllApproved(client : db.Client, org : BasicOrg|null, start ?: number, end ?: number) : Promise<BasicRow[]> {
if (org !== null && org.is_admin) {
if (start !== undefined && end !== undefined) {
return db.selectAll(client, `select primary_kind, name, description,
website, repository, issue_tracker, license,
category, subcategory from device_class
order by name limit ?,?`,
[start, end]);
} else {
return db.selectAll(client, `select primary_kind, name, description,
website, repository, issue_tracker, license,
category, subcategory from device_class order by name`);
}
} else if (org !== null) {
if (start !== undefined && end !== undefined) {
return db.selectAll(client, `select primary_kind, name, description,
website, repository, issue_tracker, license,
category, subcategory from device_class
where (approved_version is not null or owner = ?)
order by name limit ?,?`,
[org.id, start, end]);
} else {
return db.selectAll(client, `select primary_kind, name, description,
website, repository, issue_tracker, license,
category, subcategory from device_class
where (approved_version is not null or owner = ?)
order by name`, [org.id]);
}
} else {
if (start !== undefined && end !== undefined) {
return db.selectAll(client, `select primary_kind, name, description,
website, repository, issue_tracker, license,
category, subcategory from device_class
where approved_version is not null
order by name limit ?,?`,
[start, end]);
} else {
return db.selectAll(client, `select primary_kind, name, description,
website, repository, issue_tracker, license,
category, subcategory from device_class
where approved_version is not null order by name`);
}
}
}
export async function getAllKinds(client : db.Client, id : number) : Promise<KindRow[]> {
return db.selectAll(client, "select * from device_class_kind where device_id = ? "
+ "order by kind", [id]);
}
export async function getAllDiscoveryServices(client : db.Client, id : number, discoveryType : 'upnp' | 'bluetooth') : Promise<DiscoveryServiceRow[]> {
return db.selectAll(client, "select * from device_discovery_services where device_id = ? and discovery_type = ?", [id, discoveryType]);
}
export {
create,
update,
};
async function _delete(client : db.Client, id : number) {
await db.query(client, "delete from device_class where id = ?", [id]);
}
export { _delete as delete };
export async function approve(client : db.Client, kind : string) {
await db.query(client, "update device_class set approved_version = developer_version where primary_kind = ?", [kind]);
}
export async function unapprove(client : db.Client, kind : string) {
await db.query(client, "update device_class set approved_version = null where primary_kind = ?", [kind]);
}
export async function getFeatured(client : db.Client, count = 6) : Promise<Array<Pick<Row, "id"|"name"|"primary_kind">>> {
return db.selectAll(client, `select d.id,d.name,d.primary_kind from device_class d, device_class_tag dt, device_code_version dcv
where dt.device_id = d.id and dt.tag = 'featured' and d.approved_version = dcv.version and dcv.device_id = d.id
order by mtime desc limit ?`,
[count]);
}
type ReviewRow = Pick<Row, "id"|"primary_kind"|"name"|"approved_version"|"developer_version"|"owner"> & {
owner_name : string;
approval_time : VersionedRow['mtime']|null,
last_modified : VersionedRow['mtime']
};
export async function getReviewQueue(client : db.Client, start ?: number, end ?: number) : Promise<ReviewRow[]> {
if (start !== undefined && end !== undefined) {
return db.selectAll(client, `select d.id,d.primary_kind,d.name,d.approved_version,d.developer_version,
d.owner,org.name as owner_name, app_dcv.mtime as approval_time, dev_dcv.mtime as last_modified from
(device_class d, organizations org, device_code_version dev_dcv) left join
device_code_version app_dcv on d.id = app_dcv.device_id and d.approved_version = app_dcv.version
where org.id = d.owner and (d.approved_version is null or d.approved_version != d.developer_version)
and dev_dcv.version = d.developer_version and dev_dcv.device_id = d.id order by last_modified desc
limit ?,?`,
[start, end]);
} else {
return db.selectAll(client, `select d.id,d.primary_kind,d.name,d.approved_version,d.developer_version,
d.owner,org.name as owner_name, app_dcv.mtime as approval_time, dev_dcv.mtime as last_modified from
(device_class d, organizations org, device_code_version dev_dcv) left join
device_code_version app_dcv on d.id = app_dcv.device_id and d.approved_version = app_dcv.version
where org.id = d.owner and (d.approved_version is null or d.approved_version != d.developer_version)
and dev_dcv.version = d.developer_version and dev_dcv.device_id = d.id order by last_modified desc`);
}
}
type SetupRow = Pick<Row & VersionedRow, "primary_kind"|"name"|"category"|"code"|"factory"> & { for_kind : string };
export async function getDevicesForSetup(client : db.Client, names : string[], org : BasicOrg|null) : Promise<SetupRow[]> {
if (org !== null && org.is_admin) {
const query = `
(select d.primary_kind, d.name, d.category, d.primary_kind as for_kind, dcv.code, dcv.factory
from device_class d, device_code_version dcv where d.id = dcv.device_id and
dcv.version = d.developer_version
and d.primary_kind in (?))
union distinct
(select d.primary_kind, d.name, d.category, dck.kind as for_kind, dcv.code, dcv.factory from device_class d,
device_code_version dcv, device_class_kind dck where dck.device_id = d.id and
d.id = dcv.device_id and
dcv.version = d.developer_version
and dck.kind in (?))
union distinct
(select d.primary_kind, d.name, d.category, dck2.kind as for_kind, dcv.code, dcv.factory from device_class d,
device_class d2, device_class_kind dck2, device_code_version dcv, device_class_kind dck
where dck.device_id = d.id and d.id = dcv.device_id and
dcv.version = d.developer_version
and dck.kind = d2.primary_kind and dck2.device_id = d2.id and dck2.kind in (?))`;
return db.selectAll(client, query, [names, names, names]);
} else if (org !== null) {
const query = `
(select d.primary_kind, d.name, d.category, d.primary_kind as for_kind, dcv.code, dcv.factory
from device_class d, device_code_version dcv where d.id = dcv.device_id and
((dcv.version = d.developer_version and d.owner = ?) or
(dcv.version = d.approved_version and d.owner <> ?))
and d.primary_kind in (?))
union distinct
(select d.primary_kind, d.name, d.category, dck.kind as for_kind, dcv.code, dcv.factory from device_class d,
device_code_version dcv, device_class_kind dck where dck.device_id = d.id and
d.id = dcv.device_id and
((dcv.version = d.developer_version and d.owner = ?) or
(dcv.version = d.approved_version and d.owner <> ?))
and dck.kind in (?))
union distinct
(select d.primary_kind, d.name, d.category, dck2.kind as for_kind, dcv.code, dcv.factory from device_class d,
device_class d2, device_class_kind dck2, device_code_version dcv, device_class_kind dck
where dck.device_id = d.id and d.id = dcv.device_id and
((dcv.version = d.developer_version and d.owner = ?) or
(dcv.version = d.approved_version and d.owner <> ?))
and dck.kind = d2.primary_kind and dck2.device_id = d2.id and dck2.kind in (?))`;
return db.selectAll(client, query, [org.id, org.id, names, org.id, org.id, names, org.id, org.id, names]);
} else {
const query = `
(select d.primary_kind, d.name, d.category, d.primary_kind as for_kind, dcv.code, dcv.factory
from device_class d, device_code_version dcv where d.id = dcv.device_id and
dcv.version = d.approved_version
and d.primary_kind in (?))
union distinct
(select d.primary_kind, d.name, d.category, dck.kind as for_kind, dcv.code, dcv.factory from device_class d,
device_code_version dcv, device_class_kind dck where dck.device_id = d.id and
d.id = dcv.device_id and
dcv.version = d.approved_version
and dck.kind in (?))
union distinct
(select d.primary_kind, d.name, d.category, dck2.kind as for_kind, dcv.code, dcv.factory from device_class d,
device_class d2, device_class_kind dck2, device_code_version dcv, device_class_kind dck
where dck.device_id = d.id and d.id = dcv.device_id and
dcv.version = d.approved_version
and dck.kind = d2.primary_kind and dck2.device_id = d2.id and dck2.kind in (?))`;
return db.selectAll(client, query, [names, names, names]);
}
} | the_stack |
import * as angular from 'angular';
import {moduleName} from './module-name';
import AccessConstants from '../constants/AccessConstants';
import 'kylo-services-module';
import * as _ from "underscore";
import CommonRestUrlService from "./CommonRestUrlService";
import {UserGroupService} from "./UserGroupService";
import {EntityAccessControlService} from "../feed-mgr/shared/entity-access-control/EntityAccessControlService";
export class AccessControlService extends AccessConstants {
/**
* Interacts with the Access Control REST API.
* @constructor
*/
DEFAULT_MODULE: any = "services";
currentUser: any = null;
entityAccessControlled: any;
cacheUserAllowedActionsTime: any = 3000*60;
lastUserAllowedCacheAccess: any = {};
userAllowedActionsNeedsRefresh: any;
//AccessControlService(){}
static readonly $inject = ["$http","$q","$timeout","CommonRestUrlService","UserGroupService"];
constructor(private $http: angular.IHttpService,
private $q: angular.IQService,
private $timeout: angular.ITimeoutService,
private CommonRestUrlService: CommonRestUrlService,
private UserGroupService: UserGroupService){
/**
* Time allowed before the getAllowedActions refreshes from the server
* Default to refresh the cache every 3 minutes
*/
super();
this.userAllowedActionsNeedsRefresh = (module: any)=>{
if(angular.isUndefined(this.lastUserAllowedCacheAccess[module])) {
return true;
}
else {
var diff = new Date().getTime() - this.lastUserAllowedCacheAccess[module];
if(diff > this.cacheUserAllowedActionsTime){
return true;
}
else {
return false;
}
}
}
/**
* Key: Entity Type, Value: [{systemName:'ROLE1',permissions:['perm1','perm2']},...]
* @type {{}}
*/
//return new AccessControlService(); // constructor returning two things;
}
ROLE_CACHE: any = {};
// svc: any= angular.extend(AccessControlService.prototype, AccessConstants.default); //
// return angular.extend(svc, {
/**
* List of available actions
* @private
* @type {Promise|null}
*/
AVAILABLE_ACTIONS_: any= null;
executingAllowedActions: any= {};
cachedUserAllowedActions: any= {};
initialized: boolean= false;
ACCESS_MODULES:any={
SERVICES:"services"
};
/**
* Initialize the service
*/
init=()=>{
//build the user access and role/permission cache// roles:this.getRoles()
var requests: any = {userActions:this.getUserAllowedActions(this.DEFAULT_MODULE,true),
roles:this.getRoles(),
currentUser:this.getCurrentUser(),
entityAccessControlled:this.checkEntityAccessControlled()};
var defer: any = this.$q.defer();
this.$q.all(requests).then((response: any)=>{
this.initialized = true;
this.currentUser= response.currentUser;
defer.resolve(true);
});
return defer.promise;
}
hasEntityAccess=(requiredPermissions: any,entity: any,entityType?: any)=>{
//all entities should have the object .allowedActions and .owner
if(entity == undefined){
return false;
}
//short circuit if the owner matches
if(entity.owner && entity.owner.systemName == this.currentUser.systemName){
return true;
}
if(!angular.isArray(requiredPermissions)){
requiredPermissions = [requiredPermissions];
}
return this.hasAnyAction(requiredPermissions, entity.allowedActions);
}
isFutureState=(state: any)=>{
return state.endsWith(".**");
}
/**
* Check to see if we are using entity access control or not
* @returns {*}
*/
isEntityAccessControlled=()=>{
return this.entityAccessControlled;
}
checkEntityAccessControlled=()=>{
if(angular.isDefined(this.entityAccessControlled)){
return this.entityAccessControlled;
}
else {
return this.$http.get(this.CommonRestUrlService.ENTITY_ACCESS_CONTROLLED_CHECK).then((response: any)=>{
this.entityAccessControlled = response.data;
});
}
}
/**
* Determines if a user has access to a give ui-router state transition
* This is accessed via the 'routes.js' ui-router listener
* @param transition a ui-router state transition.
* @returns {boolean} true if has access, false if access deined
*/
hasAccess= (transition: any)=>{
var valid: boolean = false;
if (transition) {
var toState = transition.to();
var toStateName = toState.name;
var data = toState.data;
if(data == undefined){
//if there is nothing there, treat it as valid
return true;
}
var requiredPermissions = data.permissions || null;
if(requiredPermissions == null && data.permissionsKey) {
requiredPermissions = AccessControlService.getStatePermissions(data.permissionsKey);
}
//if its a future lazy loaded state, allow it
if (this.isFutureState(toStateName)) {
valid = true;
}else {
//check to see if the user has the required permission(s) in the String or [array] from the data.permissions object
if (this.initialized) {
var allowedActions = this.cachedUserAllowedActions[this.DEFAULT_MODULE];
if(angular.isArray(requiredPermissions)){
//find the first match
valid = requiredPermissions.length ==0 || this.hasAllActions(requiredPermissions,allowedActions)
}
else {
valid = this.hasAction(requiredPermissions,allowedActions);
}
}
}
}
return valid;
};
/**
* Find the missing actions required for a given transition
* @param transition
*/
findMissingPermissions = (requiredPermissions: string[])=>{
let missingPermissions = [];
var allowedActions = this.cachedUserAllowedActions[this.DEFAULT_MODULE];
if(requiredPermissions != null) {
missingPermissions = this.findMissingActions(requiredPermissions, allowedActions)
}
return missingPermissions
};
/**
* Gets the current user from the server
* @returns {*}
*/
getCurrentUser= ()=> {
return this.UserGroupService.getCurrentUser();
}
/**
* Gets the list of allowed actions for the specified users or groups. If no users or groups are specified, then gets the allowed actions for the current user.
*
* @param {string|null} [opt_module] name of the access module, or {@code null}
* @param {string|Array.<string>|null} [opt_users] user name or list of user names or {@code null}
* @param {string|Array.<string>|null} [opt_groups] group name or list of group names or {@code null}
* @returns {Promise} containing an {@link ActionSet} with the allowed actions
*/
getAllowedActions= (opt_module: any, opt_users: any, opt_groups: any)=> {
// Prepare query parameters
var params: any = {};
if (angular.isArray(opt_users) || angular.isString(opt_users)) {
params.user = opt_users;
}
if (angular.isArray(opt_groups) || angular.isString(opt_groups)) {
params.group = opt_groups;
}
// Send request
var safeModule = angular.isString(opt_module) ? encodeURIComponent(opt_module) : this.DEFAULT_MODULE;
return this.$http({
method: "GET",
params: params,
url: this.CommonRestUrlService.SECURITY_BASE_URL + "/actions/" + safeModule + "/allowed"
}).then((response: any)=>{
if (angular.isUndefined(response.data.actions)) {
response.data.actions = [];
}
return response.data;
});
}
/**
* Gets the list of allowed actions for the current user.
*
* @param {string|null} [opt_module] name of the access module, or {@code null}
* @param {boolean|null} true to save the data in a cache, false or underfined to not. default is false
* @returns {Promise} containing an {@link ActionSet} with the allowed actions
*/
getUserAllowedActions(opt_module?: any, cache?: any):Promise<any> {
var defer: any = null;
var safeModule = angular.isString(opt_module) ? encodeURIComponent(opt_module) : this.DEFAULT_MODULE;
if(angular.isUndefined(cache)){
cache = true;
}
var isExecuting = this.executingAllowedActions[safeModule] != undefined;
if(cache == true && !isExecuting && this.cachedUserAllowedActions[safeModule] != undefined && !this.userAllowedActionsNeedsRefresh(safeModule)) {
defer = this.$q.defer();
defer.resolve(this.cachedUserAllowedActions[safeModule]);
}
else if (!isExecuting) {
defer = this.$q.defer();
this.executingAllowedActions[safeModule] = defer;
var promise = this.$http.get(this.CommonRestUrlService.SECURITY_BASE_URL + "/actions/" + safeModule + "/allowed")
.then((response: any)=>{
if (angular.isUndefined(response.data.actions)) {
response.data.actions = [];
}
defer.resolve(response.data);
//add it to the cache
this.lastUserAllowedCacheAccess[safeModule] = new Date().getTime();
this.cachedUserAllowedActions[safeModule] = response.data;
//remove the executing request
delete this.executingAllowedActions[safeModule];
return response.data;
});
}
else {
defer = this.executingAllowedActions[safeModule];
}
return defer.promise;
}
/**
* Gets all available actions.
*
* @param {string|null} [opt_module] name of the access module, or {@code null}
* @returns {Promise} containing an {@link ActionSet} with the allowed actions
*/
getAvailableActions= (opt_module?: any)=> {
// Send request
if (this.AVAILABLE_ACTIONS_ === null) {
var safeModule = angular.isString(opt_module) ? encodeURIComponent(opt_module) : this.DEFAULT_MODULE;
this.AVAILABLE_ACTIONS_ = this.$http.get(this.CommonRestUrlService.SECURITY_BASE_URL + "/actions/" + safeModule + "/available")
.then((response: any)=>{
return response.data;
});
}
return this.AVAILABLE_ACTIONS_;
}
findMissingActions= (names: any, actions: any)=>{
if (names == "" || names == null || names == undefined || (angular.isArray(names) && names.length == 0)) {
return [];
}
var missing = _.filter(names,(name: any)=>{
return !this.hasAction(name.trim(), actions);
});
return missing;
}
/**
* Determines if any name in array of names is included in the allowed actions it will return true, otherwise false
*
* @param names an array of names
* @param actions An array of allowed actions
* @returns {boolean}
*/
hasAllActions= (names: any, actions: any)=>{
if (names == "" || names == null || names == undefined || (angular.isArray(names) && names.length == 0)) {
return true;
}
var valid = _.every(names,(name: any)=>{
return this.hasAction(name.trim(), actions);
});
return valid;
}
/**
* Determines if any name in array of names is included in the allowed actions it will return true, otherwise false
*
* @param names an array of names
* @param actions An array of allowed actions
* @returns {boolean}
*/
hasAnyAction= (names: any, actions: any)=>{
if (names == "" || names == null || names == undefined || (angular.isArray(names) && names.length == 0)) {
return true;
}
var valid = _.some(names,(name: any)=>{
return this.hasAction(name.trim(), actions);
});
return valid;
}
/**
* returns a promise with a value of true/false if the user has any of the required permissions
* @param requiredPermissions array of required permission strings
*/
doesUserHavePermission= (requiredPermissions: any)=>{
var d = this.$q.defer();
if (requiredPermissions == null || requiredPermissions == undefined || (angular.isArray(requiredPermissions) && requiredPermissions.length == 0)) {
d.resolve(true);
}
else {
this.getUserAllowedActions()
.then((actionSet: any)=> {
var allowed = this.hasAnyAction(requiredPermissions, actionSet.actions);
d.resolve(allowed);
});
}
return d.promise;
}
/**
* Determines if the specified action is allowed.
*
* @param {string} name the name of the action
* @param {Array.<Action>} actions the list of allowed actions
* @returns {boolean} {@code true} if the action is allowed, or {@code false} if denied
*/
hasAction=(name: any, actions: any): boolean=>{
if(name == null){
return true;
}
return _.some(actions,(action: any)=>{
if (action.systemName === name) {
return true;
} else if (angular.isArray(action)) {
return this.hasAction(name, action);
}else if (angular.isArray(action.actions)) {
return this.hasAction(name, action.actions);
}
return false;
});
}
/**
* Sets the allowed actions for the specified users and groups.
*
* @param {string|null} module name of the access module, or {@code null}
* @param {string|Array.<string>|null} users user name or list of user names or {@code null}
* @param {string|Array.<string>|null} groups group name or list of group names or {@code null}
* @param {Array.<Action>} actions list of actions to allow
* @returns {Promise} containing an {@link ActionSet} with the saved actions
*/
setAllowedActions= (module: any, users: any, groups: any, actions: any)=> {
// Build the request body
var safeModule: any = angular.isString(module) ? module : this.DEFAULT_MODULE;
var data: any = {actionSet: {name: safeModule, actions: actions}, change: "REPLACE"};
if (angular.isArray(users)) {
data.users = users;
} else if (angular.isString(users)) {
data.users = [users];
}
if (angular.isArray(groups)) {
data.groups = groups;
} else if (angular.isString(groups)) {
data.groups = [groups];
}
// Send the request
return this.$http({
data: angular.toJson(data),
method: "POST",
url: this.CommonRestUrlService.SECURITY_BASE_URL + "/actions/" + encodeURIComponent(safeModule) + "/allowed"
}).then((response: any)=>{
if (angular.isUndefined(response.data.actions)) {
response.data.actions = [];
}
return response.data;
});
}
/**
* Gets all roles abd populates the ROLE_CACHE
* @returns {*|Request}
*/
getRoles=()=>{
return this.$http.get(this.CommonRestUrlService.SECURITY_ROLES_URL).then((response: any)=>{
_.each(response.data,(roles: any,entityType: any)=>{
this.ROLE_CACHE[entityType] = roles;
});
});
}
/**
* For a given entity type (i.e. FEED) return the roles/permissions
* @param entityType the type of entity
*/
getEntityRoles=(entityType: any)=>{
var df = this.$q.defer();
var useCache = false; // disable the cache for now
if(useCache && this.ROLE_CACHE[entityType] != undefined) {
df.resolve(angular.copy(this.ROLE_CACHE[entityType]));
}
else {
var rolesArr: any = [];
this.$http.get(this.CommonRestUrlService.SECURITY_ENTITY_ROLES_URL(entityType)).then((response: any)=>{
_.each(response.data,(role: any)=>{
role.name = role.title;
rolesArr.push(role);
});
this.ROLE_CACHE[entityType] = rolesArr;
df.resolve(rolesArr);
});
}
return df.promise;
}
/**
* Check if the user has access checking both the functional page/section access as well as entity access permission.
* If Entity access is not enabled for the app it will bypass the entity access check.
* This will return a promise with a boolean as the response/resolved value.
* Callers need to wrap this in $q.when.
*
* Example:
*
* $q.when(AccessControlService.hasPermission(...)).then(function(hasAccess){
* if(hasAccess){
*
* }
* ...
* }
*
* @param functionalPermission a permission string to check
* @param entity the entity to check
* @param entityPermissions a string or an array of entity permissions to check against the user and supplied entity
* @return a promise with a boolean value as the response
*/
hasPermission=(functionalPermission: any,entity?: any,entityPermissions?: any)=> {
var entityAccessControlled = entity != null && entityPermissions != null && this.isEntityAccessControlled();
var defer = this.$q.defer();
var requests = {
entityAccess: entityAccessControlled == true ? this.hasEntityAccess(entityPermissions, entity) : true,
functionalAccess: this.getUserAllowedActions()
}
this.$q.all(requests).then((response: any)=>{
defer.resolve(response.entityAccess && this.hasAction(functionalPermission, response.functionalAccess.actions));
});
return defer.promise;
}
//});
}
angular.module(moduleName).service("AccessControlService",AccessControlService ); | the_stack |
export const directorySeparator = "/";
export const altDirectorySeparator = "\\";
const urlSchemeSeparator = "://";
const backslashRegExp = /\\/g;
const relativePathSegmentRegExp = /(?:\/\/)|(?:^|\/)\.\.?(?:$|\/)/;
//#region Path Tests
/**
* Determines whether a charCode corresponds to `/` or `\`.
*/
export function isAnyDirectorySeparator(charCode: number): boolean {
return charCode === CharacterCodes.slash || charCode === CharacterCodes.backslash;
}
/**
* Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
*/
export function isUrl(path: string) {
return getEncodedRootLength(path) < 0;
}
/*
* Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
*
* ```ts
* // POSIX
* isPathAbsolute("/path/to/file.ext") === true
* // DOS
* isPathAbsolute("c:/path/to/file.ext") === true
* // URL
* isPathAbsolute("file:///path/to/file.ext") === true
* // Non-absolute
* isPathAbsolute("path/to/file.ext") === false
* isPathAbsolute("./path/to/file.ext") === false
* ```
*/
export function isPathAbsolute(path: string): boolean {
return getEncodedRootLength(path) !== 0;
}
//#endregion
//#region Path Parsing
function isVolumeCharacter(charCode: number) {
return (
(charCode >= CharacterCodes.a && charCode <= CharacterCodes.z) ||
(charCode >= CharacterCodes.A && charCode <= CharacterCodes.Z)
);
}
function getFileUrlVolumeSeparatorEnd(url: string, start: number) {
const ch0 = url.charCodeAt(start);
if (ch0 === CharacterCodes.colon) return start + 1;
if (ch0 === CharacterCodes.percent && url.charCodeAt(start + 1) === CharacterCodes._3) {
const ch2 = url.charCodeAt(start + 2);
if (ch2 === CharacterCodes.a || ch2 === CharacterCodes.A) return start + 3;
}
return -1;
}
/**
* Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
*
* For example:
* ```ts
* getRootLength("a") === 0 // ""
* getRootLength("/") === 1 // "/"
* getRootLength("c:") === 2 // "c:"
* getRootLength("c:d") === 0 // ""
* getRootLength("c:/") === 3 // "c:/"
* getRootLength("c:\\") === 3 // "c:\\"
* getRootLength("//server") === 7 // "//server"
* getRootLength("//server/share") === 8 // "//server/"
* getRootLength("\\\\server") === 7 // "\\\\server"
* getRootLength("\\\\server\\share") === 8 // "\\\\server\\"
* getRootLength("file:///path") === 8 // "file:///"
* getRootLength("file:///c:") === 10 // "file:///c:"
* getRootLength("file:///c:d") === 8 // "file:///"
* getRootLength("file:///c:/path") === 11 // "file:///c:/"
* getRootLength("file://server") === 13 // "file://server"
* getRootLength("file://server/path") === 14 // "file://server/"
* getRootLength("http://server") === 13 // "http://server"
* getRootLength("http://server/path") === 14 // "http://server/"
* ```
*/
export function getRootLength(path: string) {
const rootLength = getEncodedRootLength(path);
return rootLength < 0 ? ~rootLength : rootLength;
}
/**
* Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
* If the root is part of a URL, the twos-complement of the root length is returned.
*/
function getEncodedRootLength(path: string): number {
if (!path) return 0;
const ch0 = path.charCodeAt(0);
// POSIX or UNC
if (ch0 === CharacterCodes.slash || ch0 === CharacterCodes.backslash) {
if (path.charCodeAt(1) !== ch0) return 1; // POSIX: "/" (or non-normalized "\")
const p1 = path.indexOf(
ch0 === CharacterCodes.slash ? directorySeparator : altDirectorySeparator,
2
);
if (p1 < 0) return path.length; // UNC: "//server" or "\\server"
return p1 + 1; // UNC: "//server/" or "\\server\"
}
// DOS
if (isVolumeCharacter(ch0) && path.charCodeAt(1) === CharacterCodes.colon) {
const ch2 = path.charCodeAt(2);
if (ch2 === CharacterCodes.slash || ch2 === CharacterCodes.backslash) return 3; // DOS: "c:/" or "c:\"
if (path.length === 2) return 2; // DOS: "c:" (but not "c:d")
}
// URL
const schemeEnd = path.indexOf(urlSchemeSeparator);
if (schemeEnd !== -1) {
const authorityStart = schemeEnd + urlSchemeSeparator.length;
const authorityEnd = path.indexOf(directorySeparator, authorityStart);
if (authorityEnd !== -1) {
// URL: "file:///", "file://server/", "file://server/path"
// For local "file" URLs, include the leading DOS volume (if present).
// Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
// special case interpreted as "the machine from which the URL is being interpreted".
const scheme = path.slice(0, schemeEnd);
const authority = path.slice(authorityStart, authorityEnd);
if (
scheme === "file" &&
(authority === "" || authority === "localhost") &&
isVolumeCharacter(path.charCodeAt(authorityEnd + 1))
) {
const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
if (volumeSeparatorEnd !== -1) {
if (path.charCodeAt(volumeSeparatorEnd) === CharacterCodes.slash) {
// URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
return ~(volumeSeparatorEnd + 1);
}
if (volumeSeparatorEnd === path.length) {
// URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
// but not "file:///c:d" or "file:///c%3ad"
return ~volumeSeparatorEnd;
}
}
}
return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
}
return ~path.length; // URL: "file://server", "http://server"
}
// relative
return 0;
}
export function getDirectoryPath(path: string): string {
path = normalizeSlashes(path);
// If the path provided is itself the root, then return it.
const rootLength = getRootLength(path);
if (rootLength === path.length) return path;
// return the leading portion of the path up to the last (non-terminal) directory separator
// but not including any trailing directory separator.
path = removeTrailingDirectorySeparator(path);
return path.slice(0, Math.max(rootLength, path.lastIndexOf(directorySeparator)));
}
/**
* Returns the path except for its containing directory name.
* Semantics align with NodeJS's `path.basename` except that we support URL's as well.
*
* ```ts
* // POSIX
* getBaseFileName("/path/to/file.ext") === "file.ext"
* getBaseFileName("/path/to/") === "to"
* getBaseFileName("/") === ""
* // DOS
* getBaseFileName("c:/path/to/file.ext") === "file.ext"
* getBaseFileName("c:/path/to/") === "to"
* getBaseFileName("c:/") === ""
* getBaseFileName("c:") === ""
* // URL
* getBaseFileName("http://typescriptlang.org/path/to/file.ext") === "file.ext"
* getBaseFileName("http://typescriptlang.org/path/to/") === "to"
* getBaseFileName("http://typescriptlang.org/") === ""
* getBaseFileName("http://typescriptlang.org") === ""
* getBaseFileName("file://server/path/to/file.ext") === "file.ext"
* getBaseFileName("file://server/path/to/") === "to"
* getBaseFileName("file://server/") === ""
* getBaseFileName("file://server") === ""
* getBaseFileName("file:///path/to/file.ext") === "file.ext"
* getBaseFileName("file:///path/to/") === "to"
* getBaseFileName("file:///") === ""
* getBaseFileName("file://") === ""
* ```
*/
export function getBaseFileName(path: string): string;
/**
* Gets the portion of a path following the last (non-terminal) separator (`/`).
* Semantics align with NodeJS's `path.basename` except that we support URL's as well.
* If the base name has any one of the provided extensions, it is removed.
*
* ```ts
* getBaseFileName("/path/to/file.ext", ".ext", true) === "file"
* getBaseFileName("/path/to/file.js", ".ext", true) === "file.js"
* getBaseFileName("/path/to/file.js", [".ext", ".js"], true) === "file"
* getBaseFileName("/path/to/file.ext", ".EXT", false) === "file.ext"
* ```
*/
export function getBaseFileName(
path: string,
extensions: string | readonly string[],
ignoreCase: boolean
): string;
export function getBaseFileName(
path: string,
extensions?: string | readonly string[],
ignoreCase?: boolean
) {
path = normalizeSlashes(path);
// if the path provided is itself the root, then it has not file name.
const rootLength = getRootLength(path);
if (rootLength === path.length) return "";
// return the trailing portion of the path starting after the last (non-terminal) directory
// separator but not including any trailing directory separator.
path = removeTrailingDirectorySeparator(path);
const name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(directorySeparator) + 1));
const extension =
extensions !== undefined && ignoreCase !== undefined
? getAnyExtensionFromPath(name, extensions, ignoreCase)
: undefined;
return extension ? name.slice(0, name.length - extension.length) : name;
}
function tryGetExtensionFromPath(
path: string,
extension: string,
stringEqualityComparer: (a: string, b: string) => boolean
): string | undefined {
if (!extension.startsWith(".")) extension = "." + extension;
if (
path.length >= extension.length &&
path.charCodeAt(path.length - extension.length) === CharacterCodes.dot
) {
const pathExtension = path.slice(path.length - extension.length);
if (stringEqualityComparer(pathExtension, extension)) {
return pathExtension;
}
}
return undefined;
}
function getAnyExtensionFromPathWorker(
path: string,
extensions: string | readonly string[],
stringEqualityComparer: (a: string, b: string) => boolean
) {
if (typeof extensions === "string") {
return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
}
for (const extension of extensions) {
const result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
if (result) return result;
}
return "";
}
/**
* Gets the file extension for a path.
*
* ```ts
* getAnyExtensionFromPath("/path/to/file.ext") === ".ext"
* getAnyExtensionFromPath("/path/to/file.ext/") === ".ext"
* getAnyExtensionFromPath("/path/to/file") === ""
* getAnyExtensionFromPath("/path/to.ext/file") === ""
* ```
*/
export function getAnyExtensionFromPath(path: string): string;
/**
* Gets the file extension for a path, provided it is one of the provided extensions.
*
* ```ts
* getAnyExtensionFromPath("/path/to/file.ext", ".ext", true) === ".ext"
* getAnyExtensionFromPath("/path/to/file.js", ".ext", true) === ""
* getAnyExtensionFromPath("/path/to/file.js", [".ext", ".js"], true) === ".js"
* getAnyExtensionFromPath("/path/to/file.ext", ".EXT", false) === ""
*/
export function getAnyExtensionFromPath(
path: string,
extensions: string | readonly string[],
ignoreCase: boolean
): string;
export function getAnyExtensionFromPath(
path: string,
extensions?: string | readonly string[],
ignoreCase?: boolean
): string {
// Retrieves any string from the final "." onwards from a base file name.
// Unlike extensionFromPath, which throws an exception on unrecognized extensions.
if (extensions) {
return getAnyExtensionFromPathWorker(
removeTrailingDirectorySeparator(path),
extensions,
ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive
);
}
const baseFileName = getBaseFileName(path);
const extensionIndex = baseFileName.lastIndexOf(".");
if (extensionIndex >= 0) {
return baseFileName.substring(extensionIndex);
}
return "";
}
function pathComponents(path: string, rootLength: number) {
const root = path.substring(0, rootLength);
const rest = path.substring(rootLength).split(directorySeparator);
if (rest.length && !rest[rest.length - 1]) rest.pop();
return [root, ...rest];
}
/**
* Parse a path into an array containing a root component (at index 0) and zero or more path
* components (at indices > 0). The result is not normalized.
* If the path is relative, the root component is `""`.
* If the path is absolute, the root component includes the first path separator (`/`).
*
* ```ts
* // POSIX
* getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
* getPathComponents("/path/to/") === ["/", "path", "to"]
* getPathComponents("/") === ["/"]
* // DOS
* getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
* getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
* getPathComponents("c:/") === ["c:/"]
* getPathComponents("c:") === ["c:"]
* // URL
* getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
* getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
* getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
* getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
* getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
* getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
* getPathComponents("file://server/") === ["file://server/"]
* getPathComponents("file://server") === ["file://server"]
* getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
* getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
* getPathComponents("file:///") === ["file:///"]
* getPathComponents("file://") === ["file://"]
*/
export function getPathComponents(path: string, currentDirectory = "") {
path = joinPaths(currentDirectory, path);
return pathComponents(path, getRootLength(path));
}
//#endregion
//#region Path Formatting
/**
* Reduce an array of path components to a more simplified path by navigating any
* `"."` or `".."` entries in the path.
*/
export function reducePathComponents(components: readonly string[]) {
if (!components.some((x) => x !== undefined)) return [];
const reduced = [components[0]];
for (let i = 1; i < components.length; i++) {
const component = components[i];
if (!component) continue;
if (component === ".") continue;
if (component === "..") {
if (reduced.length > 1) {
if (reduced[reduced.length - 1] !== "..") {
reduced.pop();
continue;
}
} else if (reduced[0]) continue;
}
reduced.push(component);
}
return reduced;
}
/**
* Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
*
* ```ts
* // Non-rooted
* joinPaths("path", "to", "file.ext") === "path/to/file.ext"
* joinPaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
* // POSIX
* joinPaths("/path", "to", "file.ext") === "/path/to/file.ext"
* joinPaths("/path", "/to", "file.ext") === "/to/file.ext"
* // DOS
* joinPaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
* joinPaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
* // URL
* joinPaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
* joinPaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
* ```
*/
export function joinPaths(path: string, ...paths: (string | undefined)[]): string {
if (path) path = normalizeSlashes(path);
for (let relativePath of paths) {
if (!relativePath) continue;
relativePath = normalizeSlashes(relativePath);
if (!path || getRootLength(relativePath) !== 0) {
path = relativePath;
} else {
path = ensureTrailingDirectorySeparator(path) + relativePath;
}
}
return path;
}
/**
* Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
* `.` and `..` path components are resolved. Trailing directory separators are preserved.
*
* ```ts
* resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
* resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
* resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
* ```
*/
export function resolvePath(path: string, ...paths: (string | undefined)[]): string {
return normalizePath(
paths.some((x) => x !== undefined) ? joinPaths(path, ...paths) : normalizeSlashes(path)
);
}
/**
* Parse a path into an array containing a root component (at index 0) and zero or more path
* components (at indices > 0). The result is normalized.
* If the path is relative, the root component is `""`.
* If the path is absolute, the root component includes the first path separator (`/`).
*
* ```ts
* getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
* ```
*/
export function getNormalizedPathComponents(path: string, currentDirectory: string | undefined) {
return reducePathComponents(getPathComponents(path, currentDirectory));
}
export function getNormalizedAbsolutePath(fileName: string, currentDirectory: string | undefined) {
return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
}
export function normalizePath(path: string): string {
path = normalizeSlashes(path);
// Most paths don't require normalization
if (!relativePathSegmentRegExp.test(path)) {
return path;
}
// Some paths only require cleanup of `/./` or leading `./`
const simplified = path.replace(/\/\.\//g, "/").replace(/^\.\//, "");
if (simplified !== path) {
path = simplified;
if (!relativePathSegmentRegExp.test(path)) {
return path;
}
}
// Other paths require full normalization
const normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
return normalized && hasTrailingDirectorySeparator(path)
? ensureTrailingDirectorySeparator(normalized)
: normalized;
}
//#endregion
function getPathWithoutRoot(pathComponents: readonly string[]) {
if (pathComponents.length === 0) return "";
return pathComponents.slice(1).join(directorySeparator);
}
export function getNormalizedAbsolutePathWithoutRoot(
fileName: string,
currentDirectory: string | undefined
) {
return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
}
/**
* Formats a parsed path consisting of a root component (at index 0) and zero or more path
* segments (at indices > 0).
*
* ```ts
* getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
* ```
*/
export function getPathFromPathComponents(pathComponents: readonly string[]) {
if (pathComponents.length === 0) return "";
const root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
return root + pathComponents.slice(1).join(directorySeparator);
}
//#region Path mutation
/**
* Removes a trailing directory separator from a path, if it does not already have one.
*
* ```ts
* removeTrailingDirectorySeparator("/path/to/file.ext") === "/path/to/file.ext"
* removeTrailingDirectorySeparator("/path/to/file.ext/") === "/path/to/file.ext"
* ```
*/
export function removeTrailingDirectorySeparator(path: string): string;
export function removeTrailingDirectorySeparator(path: string) {
if (hasTrailingDirectorySeparator(path)) {
return path.substr(0, path.length - 1);
}
return path;
}
export function ensureTrailingDirectorySeparator(path: string): string {
if (!hasTrailingDirectorySeparator(path)) {
return path + directorySeparator;
}
return path;
}
/**
* Determines whether a path has a trailing separator (`/` or `\\`).
*/
export function hasTrailingDirectorySeparator(path: string) {
return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
}
/**
* Normalize path separators, converting `\` into `/`.
*/
export function normalizeSlashes(path: string): string {
const index = path.indexOf("\\");
if (index === -1) {
return path;
}
backslashRegExp.lastIndex = index; // prime regex with known position
return path.replace(backslashRegExp, directorySeparator);
}
//#endregion
/**
* Compare the equality of two strings using a case-sensitive ordinal comparison.
*
* Case-sensitive comparisons compare both strings one code-point at a time using the integer
* value of each code-point after applying `toUpperCase` to each string. We always map both
* strings to their upper-case form as some unicode characters do not properly round-trip to
* lowercase (such as `ẞ` (German sharp capital s)).
*/
function equateStringsCaseInsensitive(a: string, b: string) {
return a === b || (a !== undefined && b !== undefined && a.toUpperCase() === b.toUpperCase());
}
/**
* Compare the equality of two strings using a case-sensitive ordinal comparison.
*
* Case-sensitive comparisons compare both strings one code-point at a time using the
* integer value of each code-point.
*/
function equateStringsCaseSensitive(a: string, b: string) {
return a === b;
}
const enum CharacterCodes {
nullCharacter = 0,
maxAsciiCharacter = 0x7f,
lineFeed = 0x0a, // \n
carriageReturn = 0x0d, // \r
lineSeparator = 0x2028,
paragraphSeparator = 0x2029,
nextLine = 0x0085,
// Unicode 3.0 space characters
space = 0x0020, // " "
nonBreakingSpace = 0x00a0, //
enQuad = 0x2000,
emQuad = 0x2001,
enSpace = 0x2002,
emSpace = 0x2003,
threePerEmSpace = 0x2004,
fourPerEmSpace = 0x2005,
sixPerEmSpace = 0x2006,
figureSpace = 0x2007,
punctuationSpace = 0x2008,
thinSpace = 0x2009,
hairSpace = 0x200a,
zeroWidthSpace = 0x200b,
narrowNoBreakSpace = 0x202f,
ideographicSpace = 0x3000,
mathematicalSpace = 0x205f,
ogham = 0x1680,
_ = 0x5f,
$ = 0x24,
_0 = 0x30,
_1 = 0x31,
_2 = 0x32,
_3 = 0x33,
_4 = 0x34,
_5 = 0x35,
_6 = 0x36,
_7 = 0x37,
_8 = 0x38,
_9 = 0x39,
a = 0x61,
b = 0x62,
c = 0x63,
d = 0x64,
e = 0x65,
f = 0x66,
g = 0x67,
h = 0x68,
i = 0x69,
j = 0x6a,
k = 0x6b,
l = 0x6c,
m = 0x6d,
n = 0x6e,
o = 0x6f,
p = 0x70,
q = 0x71,
r = 0x72,
s = 0x73,
t = 0x74,
u = 0x75,
v = 0x76,
w = 0x77,
x = 0x78,
y = 0x79,
z = 0x7a,
A = 0x41,
B = 0x42,
C = 0x43,
D = 0x44,
E = 0x45,
F = 0x46,
G = 0x47,
H = 0x48,
I = 0x49,
J = 0x4a,
K = 0x4b,
L = 0x4c,
M = 0x4d,
N = 0x4e,
O = 0x4f,
P = 0x50,
Q = 0x51,
R = 0x52,
S = 0x53,
T = 0x54,
U = 0x55,
V = 0x56,
W = 0x57,
X = 0x58,
Y = 0x59,
Z = 0x5a,
ampersand = 0x26, // &
asterisk = 0x2a, // *
at = 0x40, // @
backslash = 0x5c, // \
backtick = 0x60, // `
bar = 0x7c, // |
caret = 0x5e, // ^
closeBrace = 0x7d, // }
closeBracket = 0x5d, // ]
closeParen = 0x29, // )
colon = 0x3a, // :
comma = 0x2c, // ,
dot = 0x2e, // .
doubleQuote = 0x22, // "
equals = 0x3d, // =
exclamation = 0x21, // !
greaterThan = 0x3e, // >
hash = 0x23, // #
lessThan = 0x3c, // <
minus = 0x2d, // -
openBrace = 0x7b, // {
openBracket = 0x5b, // [
openParen = 0x28, // (
percent = 0x25, // %
plus = 0x2b, // +
question = 0x3f, // ?
semicolon = 0x3b, // ;
singleQuote = 0x27, // '
slash = 0x2f, // /
tilde = 0x7e, // ~
backspace = 0x08, // \b
formFeed = 0x0c, // \f
byteOrderMark = 0xfeff,
tab = 0x09, // \t
verticalTab = 0x0b, // \v
} | the_stack |
/// <reference path='metricsPlugin.ts'/>
/// <reference path='services/alertsManager.ts'/>
/// <reference path='services/paginationService.ts'/>
/// <reference path='services/errorsManager.ts'/>
/// <reference path='services/notificationsService.ts'/>
module HawkularMetrics {
// work around https://github.com/Microsoft/TypeScript/issues/2583
// re-declare the URL from lib.d.ts to conform to what's actually available from javascript runtime
interface URLConstructor {
hash: string;
search: string;
pathname: string;
port: string;
hostname: string;
host: string;
password: string;
username: string;
protocol: string;
origin: string;
href: string;
}
export class UrlChartDataPoint implements IChartDataPoint {
public date: Date;
public min: number;
public max: number;
public percentiles: IPercentile[];
public median: number;
public timestamp: number;
public value: number;
public avg: number;
public empty: boolean;
public start: number;
constructor(value, timestamp) {
this.start = timestamp;
this.timestamp = timestamp;
this.min = value;
this.max = value;
this.percentiles = []; // FIXME: this should be revisited
this.median = value;
this.date = new Date(timestamp);
this.value = value;
this.avg = value;
this.empty = false;
}
}
interface URL {
revokeObjectURL(url: string): void;
createObjectURL(object: any, options?: ObjectURLOptions): string;
new (url: string, base?: string): URLConstructor;
}
declare var URL: URL;
export class UrlListController {
/// this is for minification purposes
public static $inject = ['$location', '$scope', '$rootScope', '$interval', '$log', '$filter', '$modal',
'HawkularInventory', 'HawkularMetric', 'HawkularAlertsManager', 'ErrorsManager', '$q', 'MetricsService',
'md5', 'HkHeaderParser', 'NotificationsService', '$routeParams'];
private autoRefreshPromise: ng.IPromise<number>;
private static NUM_OF_POINTS = 30;
private httpUriPart = 'http://';
private resourceList;
private resPerPage = 12;
public filteredResourceList: any[] = [];
public activeFilters: any[] = [];
public resCurPage = 0;
public headerLinks: any = {};
private updatingList: boolean = false;
public loadingMoreItems: boolean = false;
public addProgress: boolean = false;
public sorting: any;
public currentSortIndex: number = 0;
public startTimeStamp: TimestampInMillis;
private defaultAction: any;
constructor(private $location: ng.ILocationService,
private $scope: any,
private $rootScope: any,
private $interval: ng.IIntervalService,
private $log: ng.ILogService,
private $filter: ng.IFilterService,
private $modal: any,
private HawkularInventory: any,
private HawkularMetric: any,
private HawkularAlertsManager: IHawkularAlertsManager,
private ErrorsManager: IErrorsManager,
private $q: ng.IQService,
private MetricsService: any,
private md5: any,
private HkHeaderParser: IHkHeaderParser,
private NotificationsService: INotificationsService,
private $routeParams: any,
public resourceUrl: string) {
$scope.vm = this;
this.resourceUrl = this.httpUriPart;
this.startTimeStamp = +moment().subtract((this.$routeParams.timeOffset || 3600000), 'milliseconds');
this.createDefaultActions();
if ($rootScope.currentPersona) {
this.getResourceList(this.$rootScope.currentPersona.id);
} else {
// currentPersona hasn't been injected to the rootScope yet, wait for it..
$rootScope.$watch('currentPersona', (currentPersona) =>
currentPersona && this.getResourceList(currentPersona.id));
}
$scope.$on('SwitchedPersona', () => this.getResourceList());
this.sorting = ['Sort A-Z', 'Sort Z-A'];
this.setConfigForDataTable();
this.autoRefresh(20);
}
private autoRefresh(intervalInSeconds: number): void {
this.autoRefreshPromise = this.$interval(() => {
this.getResourceList();
}, intervalInSeconds * 1000);
this.$scope.$on('$destroy', () => {
this.$interval.cancel(this.autoRefreshPromise);
});
}
public changeSortByIndex(index) {
this.currentSortIndex = index;
this.sortUrls();
}
public sortUrls() {
switch (this.currentSortIndex) {
case 1:
this.filteredResourceList = this.sortFilteredResourceList().reverse();
break;
default:
this.filteredResourceList = this.sortFilteredResourceList();
break;
}
}
private sortFilteredResourceList() {
return _.sortBy(this.filteredResourceList, (a) => {
return a.properties['hwk-gui-domainSort'];
});
}
private createDefaultActions(): void {
//TODO: There are no properties set up! After moving to alerts 0.9.x enable properties
//const defaultEmail = this.$rootScope.userDetails.email || 'myemail@company.com';
this.defaultAction = new AlertActionsBuilder()
.withActionId('email-to-admin')
.withActionPlugin('email')
.build();
}
public addUrl(url: string): void {
if (this.$scope.addUrlForm.$invalid) {
return;
}
this.addProgress = true;
// prepare data for custom sorting of URLs.
// We sort first by second and first levels and then by the rest of the levels in the order as they
// lexicographically appear in the URL.
// E.g. a.b.c.com will become c.com.a.b and we use this to sort the URLs instead of the URL strings
// themselves.
// Also, www is translated to a single space, so that it sorts before any other subdomain.
let parsedUrl = new URL(url);
let hostname = parsedUrl.hostname;
let levels = hostname.split('.');
if (levels.length > 1) {
//doing this twice on a.b.redhat.com will produce redhat.com.a.b
levels.unshift(levels.pop());
levels.unshift(levels.pop());
//replace all the www's with a space so that they sort before any other name
levels = levels.map(function(s) {
return s === 'www' ? ' ' : s;
});
}
let domainSort = levels.join('.');
let resourceId = this.md5.createHash(url || '');
let resource = {
resourceTypePath: '/URL',
id: resourceId,
properties: {
created: new Date().getTime(),
url: url,
'hwk-gui-domainSort': domainSort
}
};
this.$log.info('Adding new Resource Url to Hawkular-inventory: ' + url);
let metricId: string;
let err = (error: any, msg: string): void => this.ErrorsManager.errorHandler(error, msg);
let currentTenantId: TenantId = this.$rootScope.currentPersona.id;
// let resourcePath: string;
/// Add the Resource and its metrics
this.HawkularInventory.Resource.save({ environmentId: globalEnvironmentId }, resource).$promise
.then((newResource) => {
this.getResourceList(currentTenantId);
metricId = resourceId;
this.$log.info('New Resource ID: ' + metricId + ' created.');
let metricsIds: string[] = [metricId + '.status.duration', metricId + '.status.code'];
let metrics = [{
id: metricsIds[0],
metricTypePath: '/status.duration.type',
properties: {
description: 'Response Time in ms.'
}
}, {
id: metricsIds[1],
metricTypePath: '/status.code.type',
properties: {
description: 'Status Code'
}
}];
let errMetric = (error: any) => err(error, 'Error saving metric.');
let createMetric = (metric: any) =>
this.HawkularInventory.Metric.save({
environmentId: globalEnvironmentId
}, metric).$promise;
let associateResourceWithMetrics = () =>
this.HawkularInventory.MetricOfResource.save({
environmentId: globalEnvironmentId,
resourcePath: resourceId
}, ['/e;' + globalEnvironmentId + '/m;' + metricsIds[0], '/e;' + globalEnvironmentId + '/m;' +
metricsIds[1]]).$promise;
/// For right now we will just Register a couple of metrics automatically
return this.$q.all([createMetric(metrics[0]), createMetric(metrics[1])])
.then(associateResourceWithMetrics, errMetric)
.catch((e) => err(e, 'Error associating metrics with resource.'));
})
.finally(() => {
this.resourceUrl = this.httpUriPart;
this.$scope.addUrlForm.$setPristine();
this.addProgress = false;
});
}
public getResourceList(currentTenantId?: TenantId): any {
this.updatingList = true;
let tenantId: TenantId = currentTenantId || this.$rootScope.currentPersona.id;
let sort = 'hwk-gui-domainSort';
let order = 'asc';
this.HawkularInventory.ResourceOfType.query(
{ resourceTypeId: 'URL', per_page: this.resPerPage, page: this.resCurPage, sort: sort, order: order },
(aResourceList, getResponseHeaders) => {
// FIXME: hack.. make expanded out of list
this.headerLinks = this.HkHeaderParser.parse(getResponseHeaders());
aResourceList.expanded = this.resourceList ? this.resourceList.expanded : [];
let promises = [];
angular.forEach(aResourceList, function(res) {
let traitsArray: string[] = [];
if (res.properties['trait-remote-address']) {
traitsArray.push('IP: ' + res.properties['trait-remote-address']);
}
if (res.properties['trait-powered-by']) {
traitsArray.push('Powered by: ' + res.properties['trait-powered-by']);
}
res['traits'] = traitsArray.join(' | ');
promises.push(this.HawkularMetric.GaugeMetricData(tenantId).queryMetrics({
resourcePath: res.id, gaugeId: (res.id + '.status.duration'),
start: moment().subtract(1, 'hours').valueOf(), end: moment().valueOf()
}, (resource) => {
res['responseTime'] = resource;
let chartData = [];
_.forEach(resource.slice(0, UrlListController.NUM_OF_POINTS), (item) => {
if (item.hasOwnProperty('value') && item.hasOwnProperty('timestamp')) {
chartData.push(new UrlChartDataPoint(item['value'], item['timestamp']));
}
});
res['graphResponseTime'] = MetricsService.formatResponseTimeData(chartData);
}).$promise);
promises.push(this.HawkularMetric.AvailabilityMetricData(tenantId).query({
availabilityId: res.id, distinct: true,
start: 1, end: moment().valueOf()
}, (resource) => {
res['isUp'] = (resource[0] && resource[0].value === 'up');
}).$promise);
let availPromise = this.MetricsService.retrieveAvailabilityMetrics(this.$rootScope.currentPersona.id,
res.id, 1, moment().valueOf(), 1);
promises.push(availPromise);
availPromise.then((resource) => {
res['availability'] = resource[0].uptimeRatio * 100;
res['downtimeDuration'] = Math.round(resource[0].downtimeDuration / 1000 / 60);
res['lastDowntime'] = resource[0].lastDowntime;
});
}, this);
this.$q.all(promises).then(() => {
this.resourceList = aResourceList;
this.updatingList = this.loadingMoreItems = false;
this.$scope.$emit('list:updated');
});
});
this.$rootScope.lastUpdateTimestamp = new Date();
}
public deleteResource(resource: any): any {
this.$modal.open({
templateUrl: 'plugins/metrics/html/modals/delete-resource.html',
controller: DeleteResourceModalController,
resolve: {
resource: () => resource
}
}).result.then(result => this.getResourceList());
}
public setPage(page: number): void {
this.resCurPage = page;
this.getResourceList();
}
public loadMoreItems() {
if (!this.updatingList && this.resourceList && this.resourceList.length > 0 &&
this.resourceList.length < parseInt(this.headerLinks.total, 10)) {
this.loadingMoreItems = true;
this.resPerPage += 5;
this.getResourceList();
}
}
private arrayWithAll(orginalArray: string[]): string[] {
let arrayWithAll = orginalArray;
arrayWithAll.unshift('All');
return arrayWithAll;
}
private setConfigForDataTable(): void {
this.activeFilters = [{
id: 'byText',
title: 'Name',
placeholder: 'Containts text',
filterType: 'text'
},
{
id: 'state',
title: 'State',
placeholder: 'Filter by State',
filterType: 'select',
filterValues: this.arrayWithAll(
Object.keys(DatasourceStatus).map(
type => DatasourceStatus[type].value
)
)
}];
}
public filterBy(filters: any): void {
let filterObj = this.resourceList;
this['search'] = '';
filters.forEach((filter) => {
filterObj = filterObj.filter((item: any) => {
if (filter.value === 'All') {
return true;
}
switch (filter.id) {
case 'state':
return item.isUp && filter.value === 'Up' || !item.isUp && filter.value === 'Down';
case 'byText':
return (item.properties.url.indexOf(filter.value)) !== -1;
}
});
});
this.filteredResourceList = filterObj;
this.sortUrls();
}
}
class DeleteResourceModalController {
public static $inject = ['$scope', '$rootScope', '$modalInstance', '$q', 'HawkularInventory',
'HawkularAlertsManager', 'NotificationsService', 'resource'];
constructor(private $scope: any,
private $rootScope: any,
private $modalInstance: any,
private $q: ng.IQService,
private HawkularInventory,
private HawkularAlertsManager: HawkularMetrics.IHawkularAlertsManager,
private NotificationsService: INotificationsService,
public resource) {
$scope.vm = this;
}
public deleteResource() {
let metricsIds: string[] = [this.resource.id + '.status.duration', this.resource.id + '.status.code'];
let triggerIds: string[] = [this.resource.id + '_trigger_thres', this.resource.id + '_trigger_avail'];
let deleteMetric = (metricId: string) =>
this.HawkularInventory.Metric.delete({
environmentId: globalEnvironmentId,
metricId: metricId
}).$promise;
let removeResource = () =>
this.HawkularInventory.Resource.delete({
environmentId: globalEnvironmentId,
resourcePath: this.resource.id
}).$promise;
this.$q.all([deleteMetric(metricsIds[0]),
deleteMetric(metricsIds[1]),
this.HawkularAlertsManager.deleteTrigger(triggerIds[0]),
this.HawkularAlertsManager.deleteTrigger(triggerIds[1])])
.then(removeResource)
.then((res) => {
this.$modalInstance.close(res);
});
}
public cancel() {
this.$modalInstance.dismiss('cancel');
}
}
_module.controller('UrlListController', UrlListController);
} | the_stack |
import { lexer } from './lexer.js';
import { Lexer, Token as LexerToken } from 'moo';
/** @internal */
export type Token = Content | PlainArg | FunctionArg | Select | Octothorpe;
/**
* Text content of the message
*
* @public
*/
export interface Content {
type: 'content';
value: string;
ctx: Context;
}
/**
* A simple placeholder
*
* @public
* @remarks
* `arg` identifies an input variable, the value of which is used directly in the output.
*/
export interface PlainArg {
type: 'argument';
arg: string;
ctx: Context;
}
/**
* A placeholder for a mapped argument
*
* @public
* @remarks
* `arg` identifies an input variable, the value of which is passed to the function identified by `key`, with `param` as an optional argument.
* The output of the function is used in the output.
*
* In strict mode, `param` (if defined) may only be an array containing one {@link Content} token.
*/
export interface FunctionArg {
type: 'function';
arg: string;
key: string;
param?: Array<Content | PlainArg | FunctionArg | Select | Octothorpe>;
ctx: Context;
}
/**
* A selector between multiple variants
*
* @public
* @remarks
* The value of the `arg` input variable determines which of the `cases` is used as the output value of this placeholder.
*
* For `plural` and `selectordinal`, the value of `arg` is expected to be numeric, and will be matched either to an exact case with a key like `=3`,
* or to a case with a key that has a matching plural category as the input number.
*/
export interface Select {
type: 'plural' | 'select' | 'selectordinal';
arg: string;
cases: SelectCase[];
pluralOffset?: number;
ctx: Context;
}
/**
* A case within a {@link Select}
*
* @public
*/
export interface SelectCase {
key: string;
tokens: Array<Content | PlainArg | FunctionArg | Select | Octothorpe>;
ctx: Context;
}
/**
* Represents the `#` character
*
* @public
* @remarks
* Within a `plural` or `selectordinal` {@link Select}, the `#` character should be replaced with a formatted representation of the Select's input value.
*/
export interface Octothorpe {
type: 'octothorpe';
ctx: Context;
}
/**
* The parsing context for a token
*
* @public
*/
export interface Context {
/** Token start index from the beginning of the input string */
offset: number;
/** Token start line number, starting from 1 */
line: number;
/** Token start column, starting from 1 */
col: number;
/** The raw input source for the token */
text: string;
/** The number of line breaks consumed while parsing the token */
lineBreaks: number;
}
const getContext = (lt: LexerToken): Context => ({
offset: lt.offset,
line: lt.line,
col: lt.col,
text: lt.text,
lineBreaks: lt.lineBreaks
});
const isSelectType = (type: string): type is Select['type'] =>
type === 'plural' || type === 'select' || type === 'selectordinal';
function strictArgStyleParam(lt: LexerToken, param: Token[]) {
let value = '';
let text = '';
for (const p of param) {
const pText = p.ctx.text;
text += pText;
switch (p.type) {
case 'content':
value += p.value;
break;
case 'argument':
case 'function':
case 'octothorpe':
value += pText;
break;
default:
throw new ParseError(
lt,
`Unsupported part in strict mode function arg style: ${pText}`
);
}
}
const c: Content = {
type: 'content',
value: value.trim(),
ctx: Object.assign({}, param[0].ctx, { text })
};
return [c];
}
const strictArgTypes = [
'number',
'date',
'time',
'spellout',
'ordinal',
'duration'
];
const defaultPluralKeys = ['zero', 'one', 'two', 'few', 'many', 'other'];
/**
* Thrown by {@link parse} on error
*
* @public
*/
export class ParseError extends Error {
/** @internal */
constructor(lt: LexerToken | null, msg: string) {
super(lexer.formatError(lt as LexerToken, msg));
}
}
class Parser {
lexer: Lexer;
strict: boolean;
cardinalKeys: string[];
ordinalKeys: string[];
constructor(src: string, opt: ParseOptions) {
this.lexer = lexer.reset(src);
this.cardinalKeys = (opt && opt.cardinal) || defaultPluralKeys;
this.ordinalKeys = (opt && opt.ordinal) || defaultPluralKeys;
this.strict = (opt && opt.strict) || false;
}
parse() {
return this.parseBody(false, true);
}
checkSelectKey(lt: LexerToken, type: Select['type'], key: string) {
if (key[0] === '=') {
if (type === 'select')
throw new ParseError(lt, `The case ${key} is not valid with select`);
} else if (type !== 'select') {
const keys = type === 'plural' ? this.cardinalKeys : this.ordinalKeys;
if (keys.length > 0 && !keys.includes(key)) {
const msg = `The ${type} case ${key} is not valid in this locale`;
throw new ParseError(lt, msg);
}
}
}
parseSelect(
{ value: arg }: LexerToken,
inPlural: boolean,
ctx: Context,
type: Select['type']
): Select {
const sel: Select = { type, arg, cases: [], ctx };
if (type === 'plural' || type === 'selectordinal') inPlural = true;
else if (this.strict) inPlural = false;
for (const lt of this.lexer) {
switch (lt.type) {
case 'offset':
if (type === 'select')
throw new ParseError(lt, 'Unexpected plural offset for select');
if (sel.cases.length > 0)
throw new ParseError(lt, 'Plural offset must be set before cases');
sel.pluralOffset = Number(lt.value);
ctx.text += lt.text;
ctx.lineBreaks += lt.lineBreaks;
break;
case 'case': {
this.checkSelectKey(lt, type, lt.value);
sel.cases.push({
key: lt.value,
tokens: this.parseBody(inPlural),
ctx: getContext(lt)
});
break;
}
case 'end':
return sel;
/* istanbul ignore next: never happens */
default:
throw new ParseError(lt, `Unexpected lexer token: ${lt.type}`);
}
}
throw new ParseError(null, 'Unexpected message end');
}
parseArgToken(
lt: LexerToken,
inPlural: boolean
): PlainArg | FunctionArg | Select {
const ctx = getContext(lt);
const argType = this.lexer.next();
if (!argType) throw new ParseError(null, 'Unexpected message end');
ctx.text += argType.text;
ctx.lineBreaks += argType.lineBreaks;
if (
this.strict &&
(argType.type === 'func-simple' || argType.type === 'func-args') &&
!strictArgTypes.includes(argType.value)
) {
const msg = `Invalid strict mode function arg type: ${argType.value}`;
throw new ParseError(lt, msg);
}
switch (argType.type) {
case 'end':
return { type: 'argument', arg: lt.value, ctx };
case 'func-simple': {
const end = this.lexer.next();
if (!end) throw new ParseError(null, 'Unexpected message end');
/* istanbul ignore if: never happens */
if (end.type !== 'end')
throw new ParseError(end, `Unexpected lexer token: ${end.type}`);
ctx.text += end.text;
if (isSelectType(argType.value.toLowerCase()))
throw new ParseError(
argType,
`Invalid type identifier: ${argType.value}`
);
return {
type: 'function',
arg: lt.value,
key: argType.value,
ctx
};
}
case 'func-args': {
if (isSelectType(argType.value.toLowerCase())) {
const msg = `Invalid type identifier: ${argType.value}`;
throw new ParseError(argType, msg);
}
let param = this.parseBody(this.strict ? false : inPlural);
if (this.strict && param.length > 0)
param = strictArgStyleParam(lt, param);
return {
type: 'function',
arg: lt.value,
key: argType.value,
param,
ctx
};
}
case 'select':
/* istanbul ignore else: never happens */
if (isSelectType(argType.value))
return this.parseSelect(lt, inPlural, ctx, argType.value);
else
throw new ParseError(
argType,
`Unexpected select type ${argType.value}`
);
/* istanbul ignore next: never happens */
default:
throw new ParseError(
argType,
`Unexpected lexer token: ${argType.type}`
);
}
}
parseBody(
inPlural: false,
atRoot: true
): Array<Content | PlainArg | FunctionArg | Select>;
parseBody(inPlural: boolean): Token[];
parseBody(inPlural: boolean, atRoot?: boolean): Token[] {
const tokens: Token[] = [];
let content: Content | null = null;
for (const lt of this.lexer) {
if (lt.type === 'argument') {
if (content) content = null;
tokens.push(this.parseArgToken(lt, inPlural));
} else if (lt.type === 'octothorpe' && inPlural) {
if (content) content = null;
tokens.push({ type: 'octothorpe', ctx: getContext(lt) });
} else if (lt.type === 'end' && !atRoot) {
return tokens;
} else {
let value = lt.value;
if (!inPlural && lt.type === 'quoted' && value[0] === '#') {
if (value.includes('{')) {
const errMsg = `Unsupported escape pattern: ${value}`;
throw new ParseError(lt, errMsg);
}
value = lt.text;
}
if (content) {
content.value += value;
content.ctx.text += lt.text;
content.ctx.lineBreaks += lt.lineBreaks;
} else {
content = { type: 'content', value, ctx: getContext(lt) };
tokens.push(content);
}
}
}
if (atRoot) return tokens;
throw new ParseError(null, 'Unexpected message end');
}
}
/**
* One of the valid {@link http://cldr.unicode.org/index/cldr-spec/plural-rules | Unicode CLDR} plural category keys
*
* @public
*/
export type PluralCategory = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';
/**
* Options for the parser
*
* @public
*/
export interface ParseOptions {
/**
* Array of valid plural categories for the current locale, used to validate `plural` keys.
*
* If undefined, the full set of valid {@link PluralCategory} keys is used.
* To disable this check, pass in an empty array.
*/
cardinal?: PluralCategory[];
/**
* Array of valid plural categories for the current locale, used to validate `selectordinal` keys.
*
* If undefined, the full set of valid {@link PluralCategory} keys is used.
* To disable this check, pass in an empty array.
*/
ordinal?: PluralCategory[];
/**
* By default, the parsing applies a few relaxations to the ICU MessageFormat spec.
* Setting `strict: true` will disable these relaxations.
*
* @remarks
* - The `argType` of `simpleArg` formatting functions will be restricted to the set of
* `number`, `date`, `time`, `spellout`, `ordinal`, and `duration`,
* rather than accepting any lower-case identifier that does not start with a number.
*
* - The optional `argStyle` of `simpleArg` formatting functions will not be parsed as any other text, but instead as the spec requires:
* "In argStyleText, every single ASCII apostrophe begins and ends quoted literal text, and unquoted \{curly braces\} must occur in matched pairs."
*
* - Inside a `plural` or `selectordinal` statement, a pound symbol (`#`) is replaced with the input number.
* By default, `#` is also parsed as a special character in nested statements too, and can be escaped using apostrophes (`'#'`).
* In strict mode `#` will be parsed as a special character only directly inside a `plural` or `selectordinal` statement.
* Outside those, `#` and `'#'` will be parsed as literal text.
*/
strict?: boolean;
}
/**
* Parse an input string into an array of tokens
*
* @public
* @remarks
* The parser only supports the default `DOUBLE_OPTIONAL`
* {@link http://www.icu-project.org/apiref/icu4c/messagepattern_8h.html#af6e0757e0eb81c980b01ee5d68a9978b | apostrophe mode}.
*/
export function parse(
src: string,
options: ParseOptions = {}
): Array<Content | PlainArg | FunctionArg | Select> {
const parser = new Parser(src, options);
return parser.parse();
} | the_stack |
import GoldenLayout = require("@glue42/golden-layout");
import registryFactory from "callback-registry";
const ResizeObserver = require("resize-observer-polyfill").default;
import { idAsString, getAllWindowsFromConfig, createWaitFor, getElementBounds } from "../utils";
import { Workspace, Window, FrameLayoutConfig, StartupConfig, ComponentState, LayoutWithMaximizedItem } from "../types/internal";
import { LayoutEventEmitter } from "./eventEmitter";
import store from "../store";
import configFactory from "../config/factory";
import { LayoutStateResolver } from "./stateResolver";
import { EmptyVisibleWindowName } from "../constants";
import factory from "../config/factory";
import { TabObserver } from "./tabObserver";
export class LayoutController {
private readonly _maximizedId = "__glMaximised";
private readonly _workspaceLayoutElementId: string = "#outter-layout-container";
private readonly _registry = registryFactory();
private readonly _emitter: LayoutEventEmitter;
private _frameId: string;
private readonly _emptyVisibleWindowName: string = EmptyVisibleWindowName;
private readonly _stateResolver: LayoutStateResolver;
private readonly _options: StartupConfig;
private readonly _stackMaximizeLabel = "maximize";
private readonly _stackRestoreLabel = "restore";
constructor(emitter: LayoutEventEmitter, stateResolver: LayoutStateResolver, options: StartupConfig) {
this._options = options;
this._emitter = emitter;
this._stateResolver = stateResolver;
}
public get emitter() {
return this._emitter;
}
public async init(config: FrameLayoutConfig) {
this._frameId = config.frameId;
const tabObserver = new TabObserver();
tabObserver.init(this._workspaceLayoutElementId);
await this.initWorkspaceConfig(config.workspaceLayout);
this.refreshLayoutSize();
await Promise.all(config.workspaceConfigs.map(async (c) => {
await this.initWorkspaceContents(c.id, c.config);
this.emitter.raiseEvent("workspace-added", { workspace: store.getById(c.id) });
}));
this.setupOuterLayout();
store.workspaceIds.forEach((id) => {
this.setupContentLayouts(id);
});
}
public async addWindow(config: GoldenLayout.ItemConfig, parentId: string) {
parentId = parentId || idAsString(store.workspaceLayout.root.contentItems[0].getActiveContentItem().config.id);
const workspace = store.getByContainerId(parentId);
if (!workspace.layout) {
this.hideAddButton(workspace.id);
await this.initWorkspaceContents(workspace.id, config);
return;
}
const maximizedItem = (workspace.layout as LayoutWithMaximizedItem)._maximizedItem as GoldenLayout.ContentItem;
if (maximizedItem) {
maximizedItem.toggleMaximise();
}
let contentItem = workspace.layout.root.getItemsByFilter((ci) => ci.isColumn || ci.isRow)[0];
if (parentId && parentId !== workspace.id) {
contentItem = workspace.layout.root.getItemsById(parentId)[0];
}
if (!contentItem) {
contentItem = workspace.layout.root.getItemsByFilter((ci) => ci.isStack)[0];
}
const { placementId, windowId, url, appName } = this.getWindowInfoFromConfig(config);
this.registerWindowComponent(workspace.layout, idAsString(placementId));
const emptyVisibleWindow = contentItem.getComponentsByName(this._emptyVisibleWindowName)[0];
// store.addWindow({
// id: idAsString(placementId),
// appName,
// url,
// windowId
// }, workspace.id);
return new Promise<void>((res) => {
const unsub = this.emitter.onContentComponentCreated((component) => {
if (component.config.id === placementId) {
unsub();
res();
}
});
// if the root element is a stack you must add the window to the stack
if (workspace.layout.root.contentItems[0].type === "stack" && config.type !== "component") {
config = getAllWindowsFromConfig([config])[0];
}
if (emptyVisibleWindow && !emptyVisibleWindow.parent.config.workspacesConfig?.wrapper) {
// Triggered when the API level parent is an empty group
const group = factory.wrapInGroup([config as GoldenLayout.ComponentConfig]);
group.workspacesConfig.wrapper = false;
// Replacing the whole stack in order to trigger the header logic and the properly update the title
emptyVisibleWindow.parent.parent.replaceChild(emptyVisibleWindow.parent, group);
return;
} else if (emptyVisibleWindow) {
// Triggered when the API level parent is an empty group/column
emptyVisibleWindow.parent.replaceChild(emptyVisibleWindow, config);
return;
}
contentItem.addChild(config);
});
}
public async addContainer(config: GoldenLayout.RowConfig | GoldenLayout.ColumnConfig | GoldenLayout.StackConfig, parentId: string): Promise<string> {
const workspace = store.getByContainerId(parentId);
if (!workspace.layout) {
const containerId = config.id || factory.getId();
if (config) {
config.id = containerId;
}
this.hideAddButton(workspace.id);
await this.initWorkspaceContents(workspace.id, config);
return idAsString(containerId);
}
const maximizedItem = (workspace.layout as LayoutWithMaximizedItem)._maximizedItem as GoldenLayout.ContentItem;
if (maximizedItem) {
maximizedItem.toggleMaximise();
}
let contentItem = workspace.layout.root.getItemsByFilter((ci) => ci.isColumn || ci.isRow)[0];
if (parentId) {
contentItem = workspace.layout.root.getItemsById(parentId)[0];
}
if (!contentItem) {
contentItem = workspace.layout.root.getItemsByFilter((ci) => ci.isStack)[0];
}
if (workspace.id === parentId) {
if (config.type === "column" || config.type === "stack") {
this.bundleWorkspace(workspace.id, "row");
}
else if (config.type === "row") {
this.bundleWorkspace(workspace.id, "column");
}
contentItem = workspace.layout.root.contentItems[0];
}
if (config.content) {
getAllWindowsFromConfig(config.content).forEach((w: GoldenLayout.ComponentConfig) => {
this.registerWindowComponent(workspace.layout, idAsString(w.id));
// store.addWindow({
// id: idAsString(w.id),
// appName: w.componentState.appName,
// url: w.componentState.url,
// windowId: w.componentState.windowId,
// }, workspace.id);
});
}
if (contentItem.type === "component") {
throw new Error("The target item for add container can't be a component");
}
const groupWrapperChild = contentItem.contentItems
.find((ci) => ci.type === "stack" && ci.config.workspacesConfig.wrapper === true) as GoldenLayout.Stack;
const hasGroupWrapperAPlaceholder = (groupWrapperChild?.contentItems[0] as GoldenLayout.Component)?.config.componentName === this._emptyVisibleWindowName;
return new Promise((res, rej) => {
let unsub: () => void = () => {
// safety
};
const timeout = setTimeout(() => {
unsub();
rej(`Component with id ${config.id} could not be created in 10000ms`);
}, 10000);
unsub = this.emitter.onContentItemCreated((wId, item) => {
if (wId === workspace.id && item.type === config.type) {
res(idAsString(item.config.id));
unsub();
clearTimeout(timeout);
}
});
if (groupWrapperChild?.contentItems.length === 1 && hasGroupWrapperAPlaceholder) {
const emptyVisibleWindow = contentItem.getComponentsByName(this._emptyVisibleWindowName)[0];
emptyVisibleWindow.parent.replaceChild(emptyVisibleWindow, config);
} else {
contentItem.addChild(config);
}
});
}
public closeContainer(itemId: string) {
const workspace = store.getByContainerId(itemId) || store.getByWindowId(itemId);
const contentItem = workspace.layout.root.getItemsById(itemId)[0];
contentItem.remove();
}
public bundleWorkspace(workspaceId: string, type: "row" | "column") {
const workspace = store.getById(workspaceId);
const contentConfigs = workspace.layout.root.contentItems.map((ci) => {
return this._stateResolver.getContainerConfig(ci.config.id);
});
const oldChild = workspace.layout.root.contentItems[0];
const newChild: GoldenLayout.ItemConfig = { type, content: contentConfigs, workspacesConfig: {} };
workspace.layout.root.replaceChild(oldChild, newChild);
}
public hideAddButton(workspaceId: string) {
$(`#nestHere${workspaceId}`).children(".add-button").hide();
}
public showAddButton(workspaceId: string) {
$(`#nestHere${workspaceId}`).children(".add-button").show();
}
public async addWorkspace(id: string, config: GoldenLayout.Config) {
const stack = store.workspaceLayout.root.getItemsByFilter((ci) => ci.isStack)[0];
const componentConfig: GoldenLayout.ComponentConfig = {
componentName: configFactory.getWorkspaceLayoutComponentName(id),
type: "component",
workspacesConfig: {},
id,
title: (config?.workspacesOptions as any)?.title || configFactory.getWorkspaceTitle(store.workspaceTitles)
};
this.registerWorkspaceComponent(id);
stack.addChild(componentConfig);
await this.initWorkspaceContents(id, config);
this.setupContentLayouts(id);
this.emitter.raiseEvent("workspace-added", { workspace: store.getById(id) });
}
public removeWorkspace(workspaceId: string) {
const workspaceToBeRemoved = store.getWorkspaceLayoutItemById(workspaceId);
if (!workspaceToBeRemoved) {
throw new Error(`Could find workspace to remove with id ${workspaceId}`);
}
store.removeById(workspaceId);
workspaceToBeRemoved.remove();
}
public changeTheme(themeName: string) {
const htmlElement = document.getElementsByTagName("html")[0];
if (themeName === "light") {
if (!htmlElement.classList.contains(themeName)) {
htmlElement.classList.remove("dark");
htmlElement.classList.add(themeName);
}
} else {
if (!htmlElement.classList.contains(themeName)) {
htmlElement.classList.remove("light");
htmlElement.classList.add(themeName);
}
}
const lightLink = $("link[href='./dist/glue42-light-theme.css']");
const link = lightLink.length === 0 ? $("link[href='./dist/glue42-dark-theme.css']") : lightLink;
link.attr("href", `./dist/glue42-${themeName}-theme.css`);
}
public getDragElement(): Element {
const dragElement = $(".lm_dragProxy");
return dragElement[0];
}
public setDragElementSize(contentWidth: number, contentHeight: number) {
const dragElement = this.getDragElement();
if (!dragElement) {
const observer = new MutationObserver((mutations) => {
let targetElement: JQuery;
Array.from(mutations).forEach((m) => {
const newItems = $(m.addedNodes);
if (!targetElement) {
targetElement = newItems.find(".lm_dragProxy");
}
});
if (targetElement) {
observer.disconnect();
this.setDragElementSize(contentWidth, contentHeight);
}
});
observer.observe($("body")[0], { childList: true, subtree: true });
} else {
dragElement.setAttribute("width", `${contentWidth}px`);
dragElement.setAttribute("height", `${contentHeight}px`);
const dragProxyContent = $(dragElement).children(".lm_content").children(".lm_item_container")[0];
dragProxyContent.setAttribute("width", `${contentWidth}px`);
dragProxyContent.setAttribute("height", `${contentHeight}px`);
dragProxyContent.setAttribute("style", "");
}
}
public removeLayoutElement(windowId: string): Workspace {
let resultLayout: Workspace;
store.layouts.filter((l) => l.layout).forEach((l) => {
const elementToRemove = l.layout.root.getItemsById(windowId)[0];
if (elementToRemove && l.windows.find((w) => w.id === windowId)) {
l.windows = l.windows.filter((w) => w.id !== windowId);
elementToRemove.remove();
resultLayout = l;
}
});
return resultLayout;
}
public setWindowTitle(windowId: string, title: string) {
const item = store.getWindowContentItem(windowId);
item.setTitle(title);
item.config.componentState.title = title;
}
public setWorkspaceTitle(workspaceId: string, title: string) {
const item = store.getWorkspaceLayoutItemById(workspaceId);
item.setTitle(title);
}
public focusWindow(windowId: string) {
const layoutWithWindow = store.layouts.find((l) => l.windows.some((w) => w.id === windowId));
const item = layoutWithWindow.layout.root.getItemsById(windowId)[0];
item.parent.setActiveContentItem(item);
}
public focusWorkspace(workspaceId: string) {
const item = store.getWorkspaceLayoutItemById(workspaceId);
item.parent.setActiveContentItem(item);
}
public maximizeWindow(windowId: string) {
const layoutWithWindow = store.layouts.find((l) => l.windows.some((w) => w.id === windowId));
const item = layoutWithWindow.layout.root.getItemsById(windowId)[0];
if (item.parent.hasId(this._maximizedId)) {
return;
}
item.parent.toggleMaximise();
}
public restoreWindow(windowId: string) {
const layoutWithWindow = store.layouts.find((l) => l.windows.some((w) => w.id === windowId));
const item = layoutWithWindow.layout.root.getItemsById(windowId)[0];
if (item.parent.hasId(this._maximizedId)) {
item.parent.toggleMaximise();
}
}
public async showLoadedWindow(placementId: string, windowId: string) {
await this.waitForWindowContainer(placementId);
const winContainer: GoldenLayout.Component = store.getWindowContentItem(placementId);
const workspace = store.getByWindowId(placementId);
const winContainerConfig = winContainer.config;
winContainerConfig.componentState.windowId = windowId;
workspace.windows.find((w) => w.id === placementId).windowId = windowId;
winContainer.parent.replaceChild(winContainer, winContainerConfig);
}
public isWindowVisible(placementId: string | string[]) {
placementId = idAsString(placementId);
const contentItem = store.getWindowContentItem(placementId);
const parentStack = contentItem.parent;
return parentStack.getActiveContentItem().config.id === placementId;
}
private initWorkspaceContents(id: string, config: GoldenLayout.Config | GoldenLayout.ItemConfig) {
if (!config || (config.type !== "component" && !config.content.length)) {
store.addOrUpdate(id, []);
this.showAddButton(id);
return Promise.resolve();
}
const waitFor = createWaitFor(2);
if (!(config as GoldenLayout.Config).settings) {
(config as GoldenLayout.Config).settings = configFactory.getDefaultWorkspaceSettings();
}
if (config.type && config.type !== "workspace") {
// Wrap the component in a column when you don't have a workspace;
config = {
settings: configFactory.getDefaultWorkspaceSettings(),
content: [
{
type: "column",
content: [
config
],
workspacesConfig: {}
}
]
};
}
if (config.type !== "component" && config.content[0].type === "stack") {
// Wrap the component in a column when your top element is stack;
config = {
...config,
content: [
{
type: "column",
content: config.content,
workspacesConfig: {}
}
]
};
}
const layout = new GoldenLayout(config as GoldenLayout.Config, $(`#nestHere${id}`));
store.addOrUpdate(id, []);
this.registerEmptyWindowComponent(layout, id);
getAllWindowsFromConfig((config as GoldenLayout.Config).content).forEach((element: GoldenLayout.ComponentConfig) => {
this.registerWindowComponent(layout, idAsString(element.id));
});
const layoutContainer = $(`#nestHere${id}`);
layout.on("initialised", () => {
const allWindows = getAllWindowsFromConfig(layout.toConfig().content);
store.addOrUpdate(id, allWindows.map((w) => {
const winContentItem: GoldenLayout.ContentItem = layout.root.getItemsById(idAsString(w.id))[0];
const winElement = winContentItem.element;
return {
id: idAsString(w.id),
bounds: getElementBounds(winElement),
windowId: w.componentState.windowId,
};
}), layout);
this.emitter.raiseEventWithDynamicName(`content-layout-initialised-${id}`);
this.emitter.raiseEvent("content-layout-init", { layout });
const containerWidth = layoutContainer.width();
const containerHeight = layoutContainer.height();
layout.updateSize(containerWidth, containerHeight);
waitFor.signal();
});
layout.on("stateChanged", () => {
this.emitter.raiseEvent("content-layout-state-changed", { layoutId: id });
});
layout.on("itemCreated", (item: GoldenLayout.ContentItem) => {
if (!item.isComponent) {
if (item.isRoot) {
if (!item.id || !item.id.length) {
item.addId(id);
}
return;
}
if (!item.config.id || !item.config.id.length) {
item.addId(factory.getId());
}
} else {
item.on("size-changed", () => {
const windowWithChangedSize = store.getById(id).windows.find((w) => w.id === item.config.id);
if (windowWithChangedSize) {
windowWithChangedSize.bounds = getElementBounds(item.element);
}
const itemId = item.config.id;
this.emitter.raiseEvent("content-item-resized", { target: (item.element as any)[0], id: idAsString(itemId) });
});
if (item.config.componentName === this._emptyVisibleWindowName || item.parent?.config.workspacesConfig.wrapper) {
item.tab.header.position(false);
}
}
this.emitter.raiseEvent("content-item-created", { workspaceId: id, item });
});
layout.on("stackCreated", (stack: GoldenLayout.Stack) => {
const button = document.createElement("li");
button.classList.add("lm_add_button");
button.onclick = (e) => {
e.stopPropagation();
this.emitter.raiseEvent("add-button-clicked", {
args: {
laneId: idAsString(stack.config.id),
workspaceId: id,
bounds: getElementBounds(button),
}
});
};
const maximizeButton = $(stack.element)
.children(".lm_header")
.children(".lm_controls")
.children(".lm_maximise");
maximizeButton.addClass("workspace_content");
stack.on("maximized", () => {
maximizeButton.addClass("lm_restore");
maximizeButton.attr("title", this._stackRestoreLabel);
this.emitter.raiseEvent("stack-maximized", { stack });
});
stack.on("minimized", () => {
maximizeButton.removeClass("lm_restore");
maximizeButton.attr("title", this._stackMaximizeLabel);
this.emitter.raiseEvent("stack-restored", { stack });
});
if (!this._options.disableCustomButtons) {
stack.header.controlsContainer.prepend($(button));
}
stack.on("activeContentItemChanged", () => {
const activeItem = stack.getActiveContentItem();
if (!activeItem.isComponent) {
return;
}
const clickedTabId = activeItem.config.id;
const toFront: Window[] = [{
id: idAsString(activeItem.config.id),
bounds: getElementBounds(activeItem.element),
windowId: activeItem.config.componentState.windowId,
appName: activeItem.config.componentState.appName,
url: activeItem.config.componentState.url,
}];
const allTabsInTabGroup = stack.header.tabs.reduce((acc: Window[], t: GoldenLayout.Tab) => {
const contentItemConfig = t.contentItem.config;
if (contentItemConfig.type === "component") {
const win: Window = {
id: idAsString(contentItemConfig.id),
bounds: getElementBounds(t.contentItem.element),
windowId: contentItemConfig.componentState.windowId,
appName: contentItemConfig.componentState.appName,
url: contentItemConfig.componentState.url,
};
acc.push(win);
}
return acc;
}, []);
const toBack = allTabsInTabGroup
.filter((t: Window) => t.id !== clickedTabId);
this.emitter.raiseEvent("selection-changed", { toBack, toFront });
});
stack.on("popoutRequested", () => {
const activeItem = stack.getActiveContentItem();
this.emitter.raiseEvent("eject-requested", { item: activeItem });
});
});
layout.on("tabCreated", (tab: GoldenLayout.Tab) => {
tab._dragListener.on("drag", () => {
this.emitter.raiseEvent("tab-drag", { tab });
});
tab._dragListener.on("dragStart", () => {
this.emitter.raiseEvent("tab-drag-start", { tab });
});
tab._dragListener.on("dragEnd", () => {
this.emitter.raiseEvent("tab-drag-end", { tab });
});
tab.element.mousedown(() => {
this.emitter.raiseEvent("tab-element-mouse-down", { tab });
});
this.refreshTabSizeClass(tab);
});
layout.on("tabCloseRequested", (tab: GoldenLayout.Tab) => {
this.emitter.raiseEvent("tab-close-requested", { item: tab.contentItem });
});
layout.on("componentCreated", (component: GoldenLayout.ContentItem) => {
const result = this.emitter.raiseEvent("content-component-created", { component, workspaceId: id });
if (Array.isArray(result)) {
Promise.all(result).then(() => {
waitFor.signal();
}).catch((e) => waitFor.reject(e));
} else {
result.then(() => {
waitFor.signal();
}).catch((e) => waitFor.reject(e));
}
});
layout.init();
return waitFor.promise;
}
private initWorkspaceConfig(workspaceConfig: GoldenLayout.Config) {
return new Promise((res) => {
workspaceConfig.settings.selectionEnabled = true;
store.workspaceLayout = new GoldenLayout(workspaceConfig, $(this._workspaceLayoutElementId));
const outerResizeObserver = new ResizeObserver((entries: Array<{ target: Element }>) => {
Array.from(entries).forEach((e) => {
this.emitter.raiseEvent("outer-layout-container-resized", { target: e.target });
});
});
outerResizeObserver.observe($("#outter-layout-container")[0]);
(workspaceConfig.content[0] as GoldenLayout.StackConfig).content.forEach((configObj) => {
const workspaceId = configObj.id;
this.registerWorkspaceComponent(idAsString(workspaceId));
});
store.workspaceLayout.on("initialised", () => {
this.emitter.raiseEvent("workspace-layout-initialised", {});
res();
});
store.workspaceLayout.on("stackCreated", (stack: GoldenLayout.Stack) => {
const closeButton = stack.header.controlsContainer.children(".lm_close")[0];
if (closeButton) {
closeButton.onclick = () => {
this.emitter.raiseEvent("close-frame", {});
};
}
if (!this._options.disableCustomButtons) {
const button = document.createElement("li");
button.classList.add("lm_add_button");
button.onclick = (e) => {
e.stopPropagation();
this._emitter.raiseEvent("workspace-add-button-clicked", {});
};
stack.header.workspaceControlsContainer.prepend($(button));
}
stack.on("activeContentItemChanged", async () => {
if (store.workspaceIds.length === 0) {
return;
}
const activeItem = stack.getActiveContentItem();
const activeWorkspaceId = activeItem.config.id;
await this.waitForLayout(idAsString(activeWorkspaceId));
// don't ignore the windows from the currently selected workspace because the event
// which adds the workspacesFrame hasn't still added the new workspace and the active item status the last tab
const allOtherWindows = store.workspaceIds.reduce((acc, id) => {
return [...acc, ...store.getById(id).windows];
}, []);
const toBack: Window[] = allOtherWindows;
this.emitter.raiseEvent("workspace-selection-changed", { workspace: store.getById(activeWorkspaceId), toBack });
});
});
store.workspaceLayout.on("itemCreated", (item: GoldenLayout.ContentItem) => {
if (item.isComponent) {
item.on("size-changed", () => {
this.emitter.raiseEvent("workspace-content-container-resized", { target: item, id: idAsString(item.config.id) });
this.emitter.raiseEventWithDynamicName(`workspace-content-container-resized-${item.config.id}`, item);
});
}
});
store.workspaceLayout.on("tabCreated", (tab: GoldenLayout.Tab) => {
const saveButton = document.createElement("div");
saveButton.classList.add("lm_saveButton");
saveButton.onclick = (e) => {
e.stopPropagation();
this.emitter.raiseEvent("workspace-save-requested", { workspaceId: idAsString(tab.contentItem.config.id) });
};
if (!this._options.disableCustomButtons) {
tab.element[0].prepend(saveButton);
}
this.refreshTabSizeClass(tab);
});
store.workspaceLayout.on("tabCloseRequested", (tab: GoldenLayout.Tab) => {
this.emitter.raiseEvent("workspace-tab-close-requested",
{ workspace: store.getById(tab.contentItem.config.id) });
});
store.workspaceLayout.init();
});
}
private setupOuterLayout() {
this.emitter.onOuterLayoutContainerResized((target) => {
store.workspaceLayout.updateSize($(target).width(), $(target).height());
});
}
private setupContentLayouts(id: string) {
this.emitter.onContentContainerResized((item) => {
const currLayout = store.getById(id).layout;
if (currLayout) {
// The size must be passed in order to handle resizes like maximize of the browser
currLayout.updateSize($(item.element).width(), $(item.element).height());
}
}, id);
}
private registerWindowComponent(layout: GoldenLayout, placementId: string) {
this.registerComponent(layout, `app${placementId}`, (container) => {
const div = document.createElement("div");
div.setAttribute("style", "height:100%;");
div.id = `app${placementId}`;
container.getElement().append(div);
});
}
private registerEmptyWindowComponent(layout: GoldenLayout, workspaceId: string) {
this.registerComponent(layout, this._emptyVisibleWindowName, (container) => {
const emptyContainerDiv = document.createElement("div");
emptyContainerDiv.classList.add("empty-container-background");
const newButton = document.createElement("button");
newButton.classList.add("add-button");
newButton.onclick = (e) => {
e.stopPropagation();
const contentItem = container.tab.contentItem;
const parentType = contentItem.parent.type === "stack" ? "group" : contentItem.parent.type;
if (contentItem.parent.config.workspacesConfig.wrapper) {
this.emitter.raiseEvent("add-button-clicked", {
args: {
laneId: idAsString(contentItem.parent.parent.config.id),
workspaceId,
parentType: contentItem.parent.parent.type,
bounds: getElementBounds(newButton)
}
});
return;
}
this.emitter.raiseEvent("add-button-clicked", {
args: {
laneId: idAsString(contentItem.parent.config.id),
workspaceId,
parentType,
bounds: getElementBounds(newButton)
}
});
};
emptyContainerDiv.append(newButton);
container.getElement().append(emptyContainerDiv);
});
}
private registerWorkspaceComponent(workspaceId: string) {
this.registerComponent(store.workspaceLayout, configFactory.getWorkspaceLayoutComponentName(workspaceId), (container: GoldenLayout.Container) => {
const div = document.createElement("div");
div.setAttribute("style", "height:calc(100% - 1px); width:calc(100% - 1px);");
div.id = `nestHere${workspaceId}`;
const newButton = document.createElement("button");
newButton.classList.add("add-button");
newButton.onclick = (e) => {
e.stopPropagation();
const contentItem = container.tab.contentItem;
this.emitter.raiseEvent("add-button-clicked", {
args: {
laneId: idAsString(contentItem.parent.id),
workspaceId,
bounds: getElementBounds(newButton)
}
});
};
div.appendChild(newButton);
container.getElement().append(div);
$(newButton).hide();
});
}
private registerComponent(layout: GoldenLayout,
name: string,
callback?: (container: GoldenLayout.Container, componentState: ComponentState) => void) {
try {
// tslint:disable-next-line:only-arrow-functions
layout.registerComponent(name, function (container: GoldenLayout.Container, componentState: ComponentState) {
if (callback) {
callback(container, componentState);
}
});
} catch (error) {
// tslint:disable-next-line:no-console
console.log(`Tried to register and already existing component - ${name}`);
}
}
private waitForLayout(id: string) {
return new Promise((res) => {
const unsub = this._registry.add(`content-layout-initialised-${id}`, () => {
res();
unsub();
});
if (store.getById(id)) {
res();
unsub();
}
});
}
private waitForWindowContainer(placementId: string) {
return new Promise((res) => {
const unsub = this.emitter.onContentComponentCreated((component) => {
if (component.config.id === placementId) {
res();
unsub();
}
});
if (store.getWindowContentItem(placementId)) {
res();
unsub();
}
});
}
private getWindowInfoFromConfig(config: GoldenLayout.ItemConfig): { windowId: string; url: string; appName: string; placementId: string } {
if (config.type !== "component") {
return this.getWindowInfoFromConfig(config.content[0]);
}
return {
placementId: idAsString(config.id),
windowId: config.componentState.windowId,
appName: config.componentState.appName,
url: config.componentState.url
};
}
private refreshLayoutSize() {
const bounds = getElementBounds($(this._workspaceLayoutElementId));
store.workspaceLayout.updateSize(bounds.width, bounds.height);
}
private refreshTabSizeClass(tab: GoldenLayout.Tab) {
const tabs = tab.header.tabs;
const haveClassSmall = tabs.map((t) => t.element).some((e) => e.hasClass("lm_tab_small"));
const haveClassMini = tabs.map((t) => t.element).some((e) => e.hasClass("lm_tab_mini"));
if (haveClassSmall) {
tab.element.addClass("lm_tab_small");
}
if (haveClassMini) {
tab.element.addClass("lm_tab_mini");
}
}
} | the_stack |
import swdcTracker from 'swdc-tracker';
import {api_endpoint} from '../Constants';
import {version} from 'vscode';
import {
getPluginName,
getItem,
getPluginId,
getVersion,
getWorkspaceFolders,
getGitEventFile,
isGitProject,
getEditorName,
} from '../Util';
import {KpmItem} from '../model/models';
import {getResourceInfo} from '../repo/KpmRepoManager';
import {
getDefaultBranchFromRemoteBranch,
getRepoIdentifierInfo,
getLocalChanges,
getLatestCommitForBranch,
getChangesForCommit,
authors,
getCommitsForAuthors,
getInfoForCommit,
commitAlreadyOnRemote,
isMergeCommit,
} from '../repo/GitUtil';
import {getPreference} from '../DataController';
import {getFileDataAsJson, getJsonItem, setJsonItem, storeJsonData} from './FileManager';
import {DocChangeInfo, ProjectChangeInfo} from '@swdotcom/editor-flow';
const moment = require('moment-timezone');
export class TrackerManager {
private static instance: TrackerManager;
private trackerReady: boolean = false;
private pluginParams: any = this.getPluginParams();
private eventVersions: Map<string, number> = new Map();
private constructor() {}
static getInstance(): TrackerManager {
if (!TrackerManager.instance) {
TrackerManager.instance = new TrackerManager();
}
return TrackerManager.instance;
}
public dispose() {
swdcTracker.dispose();
}
public async init() {
// initialize tracker with swdc api host, namespace, and appId
const result = await swdcTracker.initialize(api_endpoint, 'CodeTime', 'swdc-vscode');
if (result.status === 200) {
this.trackerReady = true;
}
}
public async trackCodeTimeEvent(projectChangeInfo: ProjectChangeInfo) {
if (!this.trackerReady) {
return;
}
// extract the project info from the keystroke stats
const projectInfo = {
project_directory: projectChangeInfo.project_directory,
project_name: projectChangeInfo.project_name,
};
// loop through the files in the keystroke stats "source"
const fileKeys = Object.keys(projectChangeInfo.docs_changed);
for await (const file of fileKeys) {
const docChangeInfo: DocChangeInfo = projectChangeInfo.docs_changed[file];
// start and end are UTC seconds
const fileStartDate: Date = new Date(docChangeInfo.start * 1000);
const fileEndDate: Date = new Date(docChangeInfo.end * 1000);
const codetime_entity = {
keystrokes: docChangeInfo.keystrokes,
lines_added: docChangeInfo.linesAdded,
lines_deleted: docChangeInfo.linesDeleted,
characters_added: docChangeInfo.charactersAdded,
characters_deleted: docChangeInfo.charactersDeleted,
single_deletes: docChangeInfo.singleDeletes,
multi_deletes: docChangeInfo.multiDeletes,
single_adds: docChangeInfo.singleAdds,
multi_adds: docChangeInfo.multiAdds,
auto_indents: docChangeInfo.autoIndents,
replacements: docChangeInfo.replacements,
start_time: fileStartDate.toISOString(),
end_time: fileEndDate.toISOString(),
};
const file_entity = {
file_name: docChangeInfo.file_name,
file_path: docChangeInfo.file_path,
syntax: docChangeInfo.syntax,
line_count: docChangeInfo.line_count,
character_count: docChangeInfo.character_count,
};
const repoParams = await this.getRepoParams(projectChangeInfo.project_directory);
const codetime_event = {
...codetime_entity,
...file_entity,
...projectInfo,
...this.pluginParams,
...this.getJwtParams(),
...repoParams,
};
swdcTracker.trackCodeTimeEvent(codetime_event);
}
}
public async trackUIInteraction(item: KpmItem) {
// ui interaction doesn't require a jwt, no need to check for that here
if (!this.trackerReady || !item) {
return;
}
const ui_interaction = {
interaction_type: item.interactionType,
};
const ui_element = {
element_name: item.name,
element_location: item.location,
color: item.color ? item.color : null,
icon_name: item.interactionIcon ? item.interactionIcon : null,
cta_text: !item.hideCTAInTracker ? item.label || item.description || item.tooltip : 'redacted',
};
const ui_event = {
...ui_interaction,
...ui_element,
...this.pluginParams,
...this.getJwtParams(),
};
swdcTracker.trackUIInteraction(ui_event);
}
public async trackGitLocalEvent(gitEventName: string, branch?: string, commit?: string) {
if (!this.trackerReady) {
return;
}
const projectParams = this.getProjectParams();
if (gitEventName === 'uncommitted_change') {
this.trackUncommittedChangeGitEvent(projectParams);
} else if (gitEventName === 'local_commit' && branch) {
this.trackLocalCommitGitEvent(projectParams, branch, commit);
} else {
return;
}
}
public async trackGitRemoteEvent(event: any) {
if (!this.trackerReady) {
return;
}
const projectParams = this.getProjectParams();
const remoteBranch = event.path.split('.git/')[1];
this.trackBranchCommitGitEvent(projectParams, remoteBranch, event.path);
}
public async trackGitDeleteEvent(event: any) {
this.removeBranchFromTrackingHistory(event.path);
}
private async trackUncommittedChangeGitEvent(projectParams: any) {
const uncommittedChanges = await this.getUncommittedChangesParams(projectParams.project_directory);
this.sendGitEvent('uncommitted_change', projectParams, uncommittedChanges);
}
private async trackLocalCommitGitEvent(projectParams: any, branch: string, commit?: string) {
if (!commit) {
commit = await getLatestCommitForBranch(projectParams.project_directory, branch);
}
if (await commitAlreadyOnRemote(projectParams.project_directory, commit)) {
return;
}
if (await isMergeCommit(projectParams.project_directory, commit)) {
return;
}
const commitInfo = await getInfoForCommit(projectParams.project_directory, commit);
const file_changes = await getChangesForCommit(projectParams.project_directory, commit);
const eventData = {commit_id: commit, git_event_timestamp: commitInfo.authoredTimestamp, file_changes};
this.sendGitEvent('local_commit', projectParams, eventData);
}
private async trackBranchCommitGitEvent(projectParams: any, remoteBranch: string, event_path: string) {
const defaultBranch = await getDefaultBranchFromRemoteBranch(projectParams.project_directory, remoteBranch);
const gitAuthors = await authors(projectParams.project_directory);
let lastTrackedRef = this.getLatestTrackedCommit(event_path);
let gitEventName;
if (remoteBranch === defaultBranch) {
gitEventName = 'default_branch_commit';
} else {
gitEventName = 'branch_commit';
// If we have not tracked this branch before, then pull all commits
// based on the default branch being the parent. This may not be true
// but it will prevent us from pulling the entire commit history of
// the author.
if (lastTrackedRef === '') {
lastTrackedRef = defaultBranch;
}
}
const commits = await getCommitsForAuthors(
projectParams.project_directory,
remoteBranch,
lastTrackedRef,
gitAuthors
);
for (const commit of commits) {
const file_changes = await getChangesForCommit(projectParams.project_directory, commit.commit);
const eventData = {commit_id: commit.commit, git_event_timestamp: commit.authoredTimestamp, file_changes};
this.sendGitEvent(gitEventName, projectParams, eventData);
}
// Save the latest commit SHA
if (commits[0]) {
this.setLatestTrackedCommit(event_path, commits[0].commit);
}
}
private async sendGitEvent(gitEventName: string, projectParams: any, eventData?: any) {
if (getPreference('disableGitData') === true) return;
const repoParams = await this.getRepoParams(projectParams.project_directory);
const gitEvent = {
git_event_type: gitEventName,
...eventData,
...this.pluginParams,
...this.getJwtParams(),
...projectParams,
...repoParams,
};
// send the event
swdcTracker.trackGitEvent(gitEvent);
}
public async trackEditorAction(entity: string, type: string, event?: any) {
if (!this.trackerReady) {
return;
}
const projectParams = this.getProjectParams();
if (type == 'save') {
if (this.eventVersionIsTheSame(event)) return;
if (isGitProject(projectParams.project_directory)) {
this.trackGitLocalEvent('uncommitted_change', event);
}
}
const repoParams = await this.getRepoParams(projectParams.project_directory);
const editor_event = {
entity,
type,
...this.pluginParams,
...this.getJwtParams(),
...projectParams,
...this.getFileParams(event, projectParams.project_directory),
...repoParams,
};
// send the event
swdcTracker.trackEditorAction(editor_event);
}
// Static attributes
getPluginParams(): any {
return {
plugin_id: getPluginId(),
plugin_name: getPluginName(),
plugin_version: getVersion(),
editor_name: getEditorName(),
editor_version: version,
};
}
// Dynamic attributes
getJwtParams(): any {
return {jwt: getItem('jwt')?.split('JWT ')[1]};
}
getProjectParams() {
const workspaceFolders = getWorkspaceFolders();
const project_directory = workspaceFolders.length ? workspaceFolders[0].uri.fsPath : '';
const project_name = workspaceFolders.length ? workspaceFolders[0].name : '';
return {project_directory, project_name};
}
async getRepoParams(projectRootPath: string) {
const resourceInfo = await getResourceInfo(projectRootPath);
if (!resourceInfo || !resourceInfo.identifier) {
// return empty data, no need to parse further
return {
identifier: '',
org_name: '',
repo_name: '',
repo_identifier: '',
git_branch: '',
git_tag: '',
};
}
// retrieve the git identifier info
const gitIdentifiers = getRepoIdentifierInfo(resourceInfo.identifier);
return {
...gitIdentifiers,
repo_identifier: resourceInfo.identifier,
git_branch: resourceInfo.branch,
git_tag: resourceInfo.tag,
};
}
async getUncommittedChangesParams(projectRootPath: string) {
const stats = await getLocalChanges(projectRootPath);
return {file_changes: stats};
}
eventVersionIsTheSame(event: any) {
const isSame = this.eventVersions.get(event.fileName) == event.version;
if (isSame) {
return true;
} else {
// Add filename and version to map
this.eventVersions.set(event.fileName, event.version);
if (this.eventVersions.size > 5) {
// remove oldest entry in map to stay small
this.eventVersions.delete(this.eventVersions.keys().next().value);
}
return false;
}
}
getFileParams(event: any, projectRootPath: string) {
if (!event) return {};
// File Open and Close have document attributes on the event.
// File Change has it on a `document` attribute
const textDoc = event.document || event;
if (!textDoc) {
return {
file_name: '',
file_path: '',
syntax: '',
line_count: 0,
character_count: 0,
};
}
let character_count = 0;
if (typeof textDoc.getText === 'function') {
character_count = textDoc.getText().length;
}
return {
file_name: textDoc.fileName?.split(projectRootPath)?.[1],
file_path: textDoc.fileName,
syntax: textDoc.languageId || textDoc.fileName?.split('.')?.slice(-1)?.[0],
line_count: textDoc.lineCount || 0,
character_count,
};
}
setLatestTrackedCommit(dotGitFilePath: string, commit: string) {
// dotGitFilePath: /Users/somebody/code/repo_name/.git/refs/remotes/origin/main
setJsonItem(getGitEventFile(), dotGitFilePath, {latestTrackedCommit: commit});
}
getLatestTrackedCommit(dotGitFilePath: string): string {
// dotGitFilePath: /Users/somebody/code/repo_name/.git/refs/remotes/origin/main
const data = getJsonItem(getGitEventFile(), dotGitFilePath);
return data?.latestTrackedCommit || '';
}
removeBranchFromTrackingHistory(dotGitFilePath: string) {
let data = getFileDataAsJson(getGitEventFile());
delete data[dotGitFilePath];
storeJsonData(getGitEventFile(), data);
}
} | the_stack |
import type { Socket } from 'socket.io-client';
import { ConfiguredDocumentClass, ConfiguredDocumentClassForName, DocumentConstructor } from '../../types/helperTypes';
declare global {
/**
* The core Game instance which encapsulates the data, settings, and states relevant for managing the game experience.
* The singleton instance of the Game class is available as the global variable game.
*/
class Game {
/**
* @param view - The named view which is active for this game instance.
* @param data - An object of all the World data vended by the server when the client first connects
* @param sessionId - The ID of the currently active client session retrieved from the browser cookie
* @param socket - The open web-socket which should be used to transact game-state data
*/
constructor(view: Game['view'], data: Game.ConstructorData, sessionId: Game['sessionId'], socket: Game['socket']);
/**
* The named view which is currently active.
* Game views include: join, setup, players, license, game, stream
*/
view: Game.View;
/**
* The object of world data passed from the server
*/
data: Game.Data;
/** The Release data for this version of Foundry */
release: foundry.config.ReleaseData;
/**
* The id of the active World user, if any
*/
userId: string | null;
/**
* The game World which is currently active
*/
world: this['data']['world'];
/**
* The System which is used to power this game world
*/
system: this['data']['system'];
/**
* A Map of active modules which are currently enabled in this World
* @remarks
* - This is actually defined twice. The second time it has the documentation "A mapping of installed modules".
* - This includes _all_ modules that are installed, not only those that are enabled.
*/
modules: Map<string, this['data']['modules'][number]>;
/**
* A mapping of WorldCollection instances, one per primary Document type.
*/
collections: foundry.utils.Collection<WorldCollection<DocumentConstructor, string>>;
/**
* A mapping of CompendiumCollection instances, one per Compendium pack.
*/
packs: foundry.utils.Collection<CompendiumCollection<CompendiumCollection.Metadata>>;
/**
* Localization support
*/
i18n: Localization;
/**
* The Keyboard Manager
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
* @defaultValue `null`
*/
keyboard: KeyboardManager | null;
/**
* The Mouse Manager
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
* @defaultValue `null`
*/
mouse: MouseManager | null;
/**
* The Gamepad Manager
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
* @defaultValue `null`
*/
gamepad: GamepadManager | null;
/**
* The New User Experience manager.
*/
nue: NewUserExperience;
/**
* The user role permissions setting
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
* @defaultValue `null`
*/
permissions: Game.Permissions | null;
/**
* The client session id which is currently active
*/
sessionId: string;
/**
* Client settings which are used to configure application behavior
*/
settings: ClientSettings;
/**
* Client keybindings which are used to configure application behavior
*/
keybindings: ClientKeybindings;
/**
* A reference to the open Socket.io connection
*/
socket: io.Socket | null;
/**
* A singleton GameTime instance which manages the progression of time within the game world.
*/
time: GameTime;
/**
* A singleton reference to the Canvas object which may be used.
*/
canvas: Canvas;
/**
* A singleton instance of the Audio Helper class
*/
audio: AudioHelper;
/**
* A singleton instance of the Video Helper class
*/
video: VideoHelper;
/**
* Whether the Game is running in debug mode
* @defaultValue `false`
*/
debug: boolean;
/**
* A flag for whether texture assets for the game canvas are currently loading
* @defaultValue `false`
*/
loading: boolean;
/**
* A flag for whether the Game has successfully reached the "ready" hook
* @defaultValue `false`
*/
ready: boolean;
/** Returns the current version of the Release, usable for comparisons using isNewerVersion */
get version(): string;
/**
* Fetch World data and return a Game instance
* @param view - The named view being created
* @param sessionId - The current sessionId of the connecting client
* @returns A Promise which resolves to the created Game instance
*/
static create(view: string, sessionId: string | null): Promise<Game>;
/**
* Establish a live connection to the game server through the socket.io URL
* @param sessionId - The client session ID with which to establish the connection
* @returns A promise which resolves to the connected socket, if successful
*/
static connect(sessionId: string): Promise<io.Socket>;
/**
* Retrieve the cookies which are attached to the client session
* @returns The session cookies
*/
static getCookies(): Record<string, string>;
/**
* Request World data from server and return it
* @param socket - The active socket connection
* @param view - The view for which data is being requested
*/
static getData(socket: Socket, view: string): Promise<unknown>;
/**
* Request World data from server and return it
*/
static getWorldData(socket: io.Socket): Promise<Game.Data>;
/**
* Get the current World status upon initial connection.
*/
static getWorldStatus(socket: io.Socket): Promise<boolean>;
/**
* Configure package data that is currently enabled for this world
*/
setupPackages(data: Game.Data): void;
/**
* Return the named scopes which can exist for packages.
* Scopes are returned in the prioritization order that their content is loaded.
* @returns An array of string package scopes
*/
getPackageScopes(): string[];
/**
* Initialize the Game for the current window location
*/
initialize(): void;
/**
* Display certain usability error messages which are likely to result in the player having a bad experience.
*/
protected _displayUsabilityErrors(): void;
/**
* Shut down the currently active Game. Requires GameMaster user permission.
*/
shutDown(): Promise<void>;
/**
* Fully set up the game state, initializing Documents, UI applications, and the Canvas
*/
setupGame(): Promise<void>;
/**
* Initialize game state data by creating WorldCollection instances for every primary Document type
*/
initializeDocuments(): void;
/**
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
*/
users?: ConfiguredCollectionClassForName<'User'>;
/**
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
*/
folders?: ConfiguredCollectionClassForName<'Folder'>;
/**
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
*/
actors?: ConfiguredCollectionClassForName<'Actor'>;
/**
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
*/
items?: ConfiguredCollectionClassForName<'Item'>;
/**
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
*/
scenes?: ConfiguredCollectionClassForName<'Scene'>;
/**
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
*/
combats?: ConfiguredCollectionClassForName<'Combat'>;
/**
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
*/
journal?: ConfiguredCollectionClassForName<'JournalEntry'>;
/**
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
*/
macros?: ConfiguredCollectionClassForName<'Macro'>;
/**
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
*/
playlists?: ConfiguredCollectionClassForName<'Playlist'>;
/**
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
*/
tables?: ConfiguredCollectionClassForName<'RollTable'>;
/**
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
*/
cards?: ConfiguredCollectionClassForName<'Cards'>;
/**
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
*/
messages?: ConfiguredCollectionClassForName<'ChatMessage'>;
/**
* Initialize the Compendium packs which are present within this Game
* Create a Collection which maps each Compendium pack using it's collection ID
*/
initializePacks(): Promise<this['packs']>;
/**
* Initialize the WebRTC implementation
*/
initializeRTC(): Promise<boolean>;
/**
* @remarks Initialized between the `'setup'` and `'ready'` hook events.
*/
webrtc?: AVMaster;
/**
* Initialize core UI elements
*/
initializeUI(): void;
/**
* Initialize the game Canvas
*/
initializeCanvas(): Promise<void>;
/**
* Ensure that necessary fonts have loaded and are ready for use
* Enforce a maximum timeout in milliseconds.
* Proceed with rendering after that point even if fonts are not yet available.
* @param ms - The timeout to delay
*/
protected _checkFontsReady(ms: number): Promise<void>;
/**
* Initialize Keyboard controls
*/
initializeKeyboard(): void;
/**
* Initialize Mouse controls
*/
initializeMouse(): void;
/**
* Initialize Gamepad controls
*/
initializeGamepads(): void;
/**
* Register core game settings
*/
registerSettings(): void;
/**
* Is the current session user authenticated as an application administrator?
*/
get isAdmin(): boolean;
/**
* The currently connected User entity, or null if Users is not yet initialized
*/
get user(): StoredDocument<InstanceType<ConfiguredDocumentClass<typeof User>>> | null;
/**
* A convenience accessor for the currently viewed Combat encounter
*/
get combat(): CombatEncounters['viewed'];
/**
* A state variable which tracks whether or not the game session is currently paused
*/
get paused(): boolean;
/**
* A convenient reference to the currently active canvas tool
*/
get activeTool(): string;
/**
* Toggle the pause state of the game
* Trigger the `pauseGame` Hook when the paused state changes
* @param pause - The desired pause state. When true, the game will be paused, when false the game will be un-paused.
* @param push - Push the pause state change to other connected clients? Requires an GM user.
* (default: `false`)
*/
togglePause(pause: boolean, push?: boolean): void;
/**
* Open Character sheet for current token or controlled actor
* @returns The ActorSheet which was toggled, or null if the User has no character
*/
toggleCharacterSheet(): ActorSheet | null;
/**
* Log out of the game session by returning to the Join screen
*/
logOut(): void;
/**
* Scale the base font size according to the user's settings.
* @param index - Optionally supply a font size index to use, otherwise use the user's setting.
* Available font sizes, starting at index 1, are: 8, 10, 12, 14, 16, 18, 20, 24, 28, and 32.
*/
scaleFonts(index?: number): void;
/**
* Activate Socket event listeners which are used to transact game state data with the server
*/
activateSocketListeners(): void;
/**
* Activate Event Listeners which apply to every Game View
*/
activateListeners(): void;
/**
* Support mousewheel control for range type input elements
* @param event - A Mouse Wheel scroll event
*/
protected static _handleMouseWheelInputChange(event: WheelEvent): void;
/**
* On left mouse clicks, check if the element is contained in a valid hyperlink and open it in a new tab.
*/
protected _onClickHyperlink(event: MouseEvent): void;
/**
* Prevent starting a drag and drop workflow on elements within the document unless the element has the draggable
* attribute explicitly defined or overrides the dragstart handler.
* @param event - The initiating drag start event
*/
protected _onPreventDragstart(event: DragEvent): boolean;
/**
* Disallow dragging of external content onto anything but a file input element
* @param event - The requested drag event
*/
protected _onPreventDragover(event: DragEvent): void;
/**
* Disallow dropping of external content onto anything but a file input element
* @param event - The requested drag event
*/
protected _onPreventDrop(event: DragEvent): void;
/**
* On a left-click event, remove any currently displayed inline roll tooltip
* @param event - The mousedown pointer event
*/
protected _onPointerDown(event: PointerEvent): void;
/**
* Fallback handling for mouse-up events which aren't handled further upstream.
* @param event - The mouseup pointer event
*/
protected _onPointerUp(event: PointerEvent): void;
/**
* Handle resizing of the game window by adjusting the canvas and repositioning active interface applications.
* @param event - The window resize event which has occurred
* @internal
*/
protected _onWindowResize(event: UIEvent): void;
/**
* Handle window unload operations to clean up any data which may be pending a final save
* @param event - The window unload event which is about to occur
*/
protected _onWindowBeforeUnload(event: Event): Promise<void>;
/**
* Handle cases where the browser window loses focus to reset detection of currently pressed keys
* @param event - The originating window.blur event
*/
protected _onWindowBlur(event: FocusEvent): void;
/**
* @param event - (unused)
*/
protected _onWindowPopState(event: PopStateEvent): void;
/**
* Initialize elements required for the current view
*/
protected _initializeView(): Promise<void>;
/**
* Initialization steps for the primary Game view
*/
protected _initializeGameView(): Promise<void>;
/**
* Initialization steps for the Stream helper view
*/
protected _initializeStreamView(): Promise<void>;
/**
* @deprecated since v9 - Use initializeDocuments instead.
*/
initializeEntities(): void;
}
namespace Game {
interface Language {
lang: string;
name: string;
path: string;
}
interface PackageData<T> {
availability: number;
data: T;
esmodules: string[];
id: string;
languages: Language[];
locked: boolean;
packs: {
absPath: string;
/** @deprecated since V9 */
entity: foundry.CONST.COMPENDIUM_DOCUMENT_TYPES;
label: string;
name: string;
package: string;
path: string;
private: boolean;
system?: string;
type: foundry.CONST.COMPENDIUM_DOCUMENT_TYPES;
};
scripts: string[];
styles: string[];
type: 'world' | 'system' | 'module';
unavailable: boolean;
}
interface ModuleData<T> extends PackageData<T> {
active: boolean;
path: string;
type: 'module';
}
interface SystemData<T> extends PackageData<T> {
_systemUpdateCheckTime: number;
documentTypes: {
[Key in
| foundry.CONST.DOCUMENT_TYPES
| 'ActiveEffect'
| 'Adventure'
| 'AmbientLight'
| 'AmbientSound'
| 'Card'
| 'Combatant'
| 'Drawing'
| 'FogExploration'
| 'MeasuredTemplate'
| 'Note'
| 'PlaylistSound'
| 'Setting'
| 'TableResult'
| 'Tile'
| 'Token'
| 'Wall']: string[];
};
model: {
Actor: Record<string, Record<string, unknown>>;
Cards: Record<string, Record<string, unknown>>;
Item: Record<string, Record<string, unknown>>;
};
path: string;
template: {
Actor?: {
types: string[];
templates?: Record<string, unknown>;
} & Record<string, unknown>;
Item?: {
types: string[];
templates?: Record<string, unknown>;
} & Record<string, unknown>;
};
type: 'system';
}
interface WorldData<T> extends PackageData<T> {
_systemUpdateCheckTime: number;
type: 'world';
}
type Data = {
activeUsers: string[];
addresses: {
local: string;
remote: string;
remoteIsAccessible: boolean;
};
coreUpdate: {
channel: unknown | null;
couldReachWebsite: boolean;
hasUpdate: boolean;
slowResponse: boolean;
version: unknown | null;
willDisableModules: boolean;
};
files: {
s3?: {
endpoint: {
protocol: string;
host: string;
port: number;
hostname: string;
pathname: string;
path: string;
href: string;
};
buckets: string[];
} | null;
storages: ('public' | 'data' | 's3')[];
};
modules: ModuleData<foundry.packages.ModuleData>[];
options: {
demo: boolean;
language: string;
port: number;
routePrefix: string | null;
updateChannel: string;
};
packs: {
/** @deprecated since V9 */
entity: foundry.CONST.COMPENDIUM_DOCUMENT_TYPES;
index: {
_id: string;
name: string;
type: string;
}[];
label: string;
name: string;
package: string;
path: string;
private: boolean;
system?: string;
type: foundry.CONST.COMPENDIUM_DOCUMENT_TYPES;
}[];
paused: boolean;
release: {
build: number;
channel: 'Stable' | 'Testing' | 'Development' | 'Prototype';
download: string;
generation: string;
notes: string;
time: number;
};
system: SystemData<foundry.packages.SystemData>;
systemUpdate: string | null;
userId: string;
/** @deprecated since V9 */
version?: string;
world: WorldData<foundry.packages.WorldData>;
} & {
[DocumentType in
| foundry.CONST.DOCUMENT_TYPES
| 'Setting' as ConfiguredDocumentClassForName<DocumentType>['metadata']['collection']]?: InstanceType<
ConfiguredDocumentClassForName<DocumentType>
>['data']['_source'][];
};
type ConstructorData = Omit<Data, 'world' | 'system' | 'modules'> & {
world: WorldData<foundry.packages.WorldData['_source']>;
system: SystemData<foundry.packages.SystemData['_source']>;
modules: ModuleData<foundry.packages.ModuleData['_source']>[];
};
type Permissions = {
[Key in keyof typeof foundry.CONST.USER_PERMISSIONS]: foundry.CONST.USER_ROLES[];
};
type View = ValueOf<typeof foundry.CONST.GAME_VIEWS>;
}
}
type ConfiguredCollectionClassForName<Name extends foundry.CONST.DOCUMENT_TYPES> = InstanceType<
CONFIG[Name]['collection']
>; | the_stack |
import chalk from 'chalk'
import indent from 'indent-string'
import leven from 'js-levenshtein'
import type { BaseField, DMMF } from '../dmmf-types'
import Decimal from 'decimal.js'
import type { DMMFClass } from '../dmmf'
export interface Dictionary<T> {
[key: string]: T
}
export const keyBy: <T>(collection: T[], prop: string) => Dictionary<T> = (collection, prop) => {
const acc = {}
for (const obj of collection) {
const key = obj[prop]
acc[key] = obj
}
return acc
}
export const keyBy2: <T>(collection1: T[], collection2: T[], prop: string) => Dictionary<T> = (
collection1,
collection2,
prop,
) => {
const acc = {}
for (const obj of collection1) {
const key = obj[prop]
acc[key] = obj
}
for (const obj of collection2) {
const key = obj[prop]
acc[key] = obj
}
return acc
}
export const ScalarTypeTable = {
String: true,
Int: true,
Float: true,
Boolean: true,
Long: true,
DateTime: true,
ID: true,
UUID: true,
Json: true,
Bytes: true,
Decimal: true,
BigInt: true,
}
export function isScalar(str: string): boolean {
if (typeof str !== 'string') {
return false
}
return ScalarTypeTable[str] || false
}
export const needNamespace = {
Json: 'JsonValue',
Decimal: 'Decimal',
}
export function needsNamespace(field: BaseField, dmmf: DMMFClass): boolean {
if (typeof field.type === 'string') {
if (dmmf.datamodelEnumMap[field.type]) {
return false
}
if (GraphQLScalarToJSTypeTable[field.type]) {
return Boolean(needNamespace[field.type])
}
}
return true
}
export const GraphQLScalarToJSTypeTable = {
String: 'string',
Int: 'number',
Float: 'number',
Boolean: 'boolean',
Long: 'number',
DateTime: ['Date', 'string'],
ID: 'string',
UUID: 'string',
Json: 'JsonValue',
Bytes: 'Buffer',
Decimal: ['Decimal', 'number', 'string'],
BigInt: ['bigint', 'number'],
}
export const JSOutputTypeToInputType = {
JsonValue: 'InputJsonValue',
}
export const JSTypeToGraphQLType = {
string: 'String',
boolean: 'Boolean',
object: 'Json',
}
export function stringifyGraphQLType(type: string | DMMF.InputType | DMMF.SchemaEnum) {
if (typeof type === 'string') {
return type
}
return type.name
}
export function wrapWithList(str: string, isList: boolean) {
if (isList) {
return `List<${str}>`
}
return str
}
// from https://github.com/excitement-engineer/graphql-iso-date/blob/master/src/utils/validator.js#L121
const RFC_3339_REGEX =
/^(\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60))(\.\d{1,})?(([Z])|([+|-]([01][0-9]|2[0-3]):[0-5][0-9]))$/
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
export function getGraphQLType(value: any, potentialType?: string | DMMF.SchemaEnum | DMMF.InputType): string {
if (value === null) {
return 'null'
}
if (Object.prototype.toString.call(value) === '[object BigInt]') {
return 'BigInt'
}
// https://github.com/MikeMcl/decimal.js/blob/master/decimal.js#L4499
if (Decimal.isDecimal(value)) {
return 'Decimal'
}
if (Buffer.isBuffer(value)) {
return 'Bytes'
}
if (Array.isArray(value)) {
let scalarTypes = value.reduce((acc, val) => {
const type = getGraphQLType(val, potentialType)
if (!acc.includes(type)) {
acc.push(type)
}
return acc
}, [])
// Merge Float and Int together
if (scalarTypes.includes('Float') && scalarTypes.includes('Int')) {
scalarTypes = ['Float']
}
return `List<${scalarTypes.join(' | ')}>`
}
const jsType = typeof value
if (jsType === 'number') {
if (Math.trunc(value) === value) {
return 'Int'
} else {
return 'Float'
}
}
if (Object.prototype.toString.call(value) === '[object Date]') {
return 'DateTime'
}
if (jsType === 'string') {
if (UUID_REGEX.test(value)) {
return 'UUID'
}
const date = new Date(value)
if (
potentialType &&
typeof potentialType === 'object' &&
(potentialType as DMMF.SchemaEnum).values &&
(potentialType as DMMF.SchemaEnum).values.includes(value)
) {
return potentialType.name
}
if (date.toString() === 'Invalid Date') {
return 'String'
}
if (RFC_3339_REGEX.test(value)) {
return 'DateTime'
}
}
return JSTypeToGraphQLType[jsType]
}
export function graphQLToJSType(gql: string) {
return GraphQLScalarToJSTypeTable[gql]
}
export function getSuggestion(str: string, possibilities: string[]): string | null {
const bestMatch = possibilities.reduce<{
distance: number
str: string | null
}>(
(acc, curr) => {
const distance = leven(str, curr)
if (distance < acc.distance) {
return {
distance,
str: curr,
}
}
return acc
},
{
// heuristic to be not too strict, but allow some big mistakes (<= ~ 5)
distance: Math.min(Math.floor(str.length) * 1.1, ...possibilities.map((p) => p.length * 3)),
str: null,
},
)
return bestMatch.str
}
export function stringifyInputType(input: string | DMMF.InputType | DMMF.SchemaEnum, greenKeys = false): string {
if (typeof input === 'string') {
return input
}
if ((input as DMMF.SchemaEnum).values) {
return `enum ${input.name} {\n${indent((input as DMMF.SchemaEnum).values.join(', '), 2)}\n}`
} else {
const body = indent(
(input as DMMF.InputType).fields // TS doesn't discriminate based on existence of fields properly
.map((arg) => {
const key = `${arg.name}`
const str = `${greenKeys ? chalk.green(key) : key}${arg.isRequired ? '' : '?'}: ${chalk.white(
arg.inputTypes
.map((argType) => {
return wrapWithList(
argIsInputType(argType.type) ? argType.type.name : stringifyGraphQLType(argType.type),
argType.isList,
)
})
.join(' | '),
)}`
if (!arg.isRequired) {
return chalk.dim(str)
}
return str
})
.join('\n'),
2,
)
return `${chalk.dim('type')} ${chalk.bold.dim(input.name)} ${chalk.dim('{')}\n${body}\n${chalk.dim('}')}`
}
}
export function argIsInputType(arg: DMMF.ArgType): arg is DMMF.InputType {
if (typeof arg === 'string') {
return false
}
return true
}
export function getInputTypeName(input: string | DMMF.InputType | DMMF.SchemaField | DMMF.SchemaEnum) {
if (typeof input === 'string') {
if (input === 'Null') {
return 'null'
}
return input
}
return input.name
}
export function getOutputTypeName(input: string | DMMF.OutputType | DMMF.SchemaField | DMMF.SchemaEnum) {
if (typeof input === 'string') {
return input
}
return input.name
}
export function inputTypeToJson(
input: string | DMMF.InputType | DMMF.SchemaEnum,
isRequired: boolean,
nameOnly = false,
): string | object {
if (typeof input === 'string') {
if (input === 'Null') {
return 'null'
}
return input
}
if ((input as DMMF.SchemaEnum).values) {
return (input as DMMF.SchemaEnum).values.join(' | ')
}
// TS "Trick" :/
const inputType: DMMF.InputType = input as DMMF.InputType
// If the parent type is required and all fields are non-scalars,
// it's very useful to show to the user, which options they actually have
const showDeepType =
isRequired &&
inputType.fields.every(
(arg) => arg.inputTypes[0].location === 'inputObjectTypes' || arg.inputTypes[1]?.location === 'inputObjectTypes',
)
if (nameOnly) {
return getInputTypeName(input)
}
return inputType.fields.reduce((acc, curr) => {
let str = ''
if (!showDeepType && !curr.isRequired) {
str = curr.inputTypes.map((argType) => getInputTypeName(argType.type)).join(' | ')
} else {
str = curr.inputTypes.map((argInputType) => inputTypeToJson(argInputType.type, curr.isRequired, true)).join(' | ')
}
acc[curr.name + (curr.isRequired ? '' : '?')] = str
return acc
}, {})
}
export function destroyCircular(from, seen: any[] = []) {
const to: any = Array.isArray(from) ? [] : {}
seen.push(from)
for (const key of Object.keys(from)) {
const value = from[key]
if (typeof value === 'function') {
continue
}
if (!value || typeof value !== 'object') {
to[key] = value
continue
}
if (seen.indexOf(from[key]) === -1) {
to[key] = destroyCircular(from[key], seen.slice(0))
continue
}
to[key] = '[Circular]'
}
if (typeof from.name === 'string') {
to.name = from.name
}
if (typeof from.message === 'string') {
to.message = from.message
}
if (typeof from.stack === 'string') {
to.stack = from.stack
}
return to
}
export function unionBy<T>(arr1: T[], arr2: T[], iteratee: (element: T) => string | number): T[] {
const map = {}
for (const element of arr1) {
map[iteratee(element)] = element
}
for (const element of arr2) {
const key = iteratee(element)
if (!map[key]) {
map[key] = element
}
}
return Object.values(map)
}
export function uniqBy<T>(arr: T[], iteratee: (element: T) => string | number): T[] {
const map = {}
for (const element of arr) {
map[iteratee(element)] = element
}
return Object.values(map)
}
export function capitalize(str: string): string {
return str[0].toUpperCase() + str.slice(1)
}
/**
* Converts the first character of a word to lower case
* @param name
*/
export function lowerCase(name: string): string {
return name.substring(0, 1).toLowerCase() + name.substring(1)
}
export function isGroupByOutputName(type: string): boolean {
return type.endsWith('GroupByOutputType')
}
export function isSchemaEnum(type: any): type is DMMF.SchemaEnum {
return (
typeof type === 'object' && type.name && typeof type.name === 'string' && type.values && Array.isArray(type.values)
)
} | the_stack |
'use strict';
import * as objects from 'vs/base/common/objects';
import { parse, stringify } from 'vs/base/common/marshalling';
import * as strings from 'vs/base/common/strings';
import URI from 'vs/base/common/uri';
import * as dom from 'vs/base/browser/dom';
import {
IDecorationRenderOptions, IModelDecorationOptions, IModelDecorationOverviewRulerOptions, IThemeDecorationRenderOptions,
IContentDecorationRenderOptions, OverviewRulerLane, TrackedRangeStickiness
} from 'vs/editor/common/editorCommon';
import { AbstractCodeEditorService } from 'vs/editor/common/services/abstractCodeEditorService';
import { IDisposable, toDisposable } from 'vs/base/common/lifecycle';
export class CodeEditorServiceImpl extends AbstractCodeEditorService {
private _styleSheet: HTMLStyleElement;
private _decorationOptionProviders: { [key: string]: IModelDecorationOptionsProvider };
constructor(styleSheet = dom.createStyleSheet()) {
super();
this._styleSheet = styleSheet;
this._decorationOptionProviders = Object.create(null);
}
public registerDecorationType(key: string, options: IDecorationRenderOptions, parentTypeKey?: string): void {
let provider = this._decorationOptionProviders[key];
if (!provider) {
if (!parentTypeKey) {
provider = new DecorationTypeOptionsProvider(this._styleSheet, key, options);
} else {
provider = new DecorationSubTypeOptionsProvider(this._styleSheet, key, parentTypeKey, options);
}
this._decorationOptionProviders[key] = provider;
}
provider.refCount++;
}
public removeDecorationType(key: string): void {
let provider = this._decorationOptionProviders[key];
if (provider) {
provider.refCount--;
if (provider.refCount <= 0) {
delete this._decorationOptionProviders[key];
provider.dispose();
this.listCodeEditors().forEach((ed) => ed.removeDecorations(key));
}
}
}
public resolveDecorationOptions(decorationTypeKey: string, writable: boolean): IModelDecorationOptions {
let provider = this._decorationOptionProviders[decorationTypeKey];
if (!provider) {
throw new Error('Unknown decoration type key: ' + decorationTypeKey);
}
return provider.getOptions(this, writable);
}
}
interface IModelDecorationOptionsProvider extends IDisposable {
refCount: number;
getOptions(codeEditorService: AbstractCodeEditorService, writable: boolean): IModelDecorationOptions;
}
class DecorationSubTypeOptionsProvider implements IModelDecorationOptionsProvider {
public refCount: number;
private _disposable: IDisposable;
private _parentTypeKey: string;
private _beforeContentClassName: string;
private _afterContentClassName: string;
constructor(styleSheet: HTMLStyleElement, key: string, parentTypeKey: string, options: IDecorationRenderOptions) {
this._parentTypeKey = parentTypeKey;
this.refCount = 0;
let themedOpts = getThemedRenderOptions(options);
this._beforeContentClassName = DecorationRenderHelper.createCSSRules(
styleSheet,
key,
parentTypeKey,
ModelDecorationCSSRuleType.BeforeContentClassName,
{
light: DecorationRenderHelper.getCSSTextForModelDecorationContentClassName(themedOpts.light.before),
dark: DecorationRenderHelper.getCSSTextForModelDecorationContentClassName(themedOpts.dark.before)
}
);
this._afterContentClassName = DecorationRenderHelper.createCSSRules(
styleSheet,
key,
parentTypeKey,
ModelDecorationCSSRuleType.AfterContentClassName,
{
light: DecorationRenderHelper.getCSSTextForModelDecorationContentClassName(themedOpts.light.after),
dark: DecorationRenderHelper.getCSSTextForModelDecorationContentClassName(themedOpts.dark.after)
}
);
if (this._beforeContentClassName || this._afterContentClassName) {
this._disposable = toDisposable(() => {
dom.removeCSSRulesContainingSelector(CSSNameHelper.getDeletionSubstring(key), styleSheet);
});
}
}
public getOptions(codeEditorService: AbstractCodeEditorService, writable: boolean): IModelDecorationOptions {
let options = codeEditorService.resolveDecorationOptions(this._parentTypeKey, true);
if (this._beforeContentClassName) {
options.beforeContentClassName = this._beforeContentClassName;
}
if (this._afterContentClassName) {
options.afterContentClassName = this._afterContentClassName;
}
return options;
}
public dispose(): void {
if (this._disposable) {
this._disposable.dispose();
delete this._disposable;
}
}
}
class DecorationTypeOptionsProvider implements IModelDecorationOptionsProvider {
private _disposable: IDisposable;
public refCount: number;
public className: string;
public inlineClassName: string;
public beforeContentClassName: string;
public afterContentClassName: string;
public glyphMarginClassName: string;
public isWholeLine: boolean;
public overviewRuler: IModelDecorationOverviewRulerOptions;
public stickiness: TrackedRangeStickiness;
constructor(styleSheet: HTMLStyleElement, key: string, options: IDecorationRenderOptions) {
this.refCount = 0;
let themedOpts = getThemedRenderOptions(options);
this.className = DecorationRenderHelper.createCSSRules(
styleSheet,
key,
null,
ModelDecorationCSSRuleType.ClassName,
{
light: DecorationRenderHelper.getCSSTextForModelDecorationClassName(themedOpts.light),
dark: DecorationRenderHelper.getCSSTextForModelDecorationClassName(themedOpts.dark)
}
);
this.inlineClassName = DecorationRenderHelper.createCSSRules(
styleSheet,
key,
null,
ModelDecorationCSSRuleType.InlineClassName,
{
light: DecorationRenderHelper.getCSSTextForModelDecorationInlineClassName(themedOpts.light),
dark: DecorationRenderHelper.getCSSTextForModelDecorationInlineClassName(themedOpts.dark)
}
);
this.beforeContentClassName = DecorationRenderHelper.createCSSRules(
styleSheet,
key,
null,
ModelDecorationCSSRuleType.BeforeContentClassName,
{
light: DecorationRenderHelper.getCSSTextForModelDecorationContentClassName(themedOpts.light.before),
dark: DecorationRenderHelper.getCSSTextForModelDecorationContentClassName(themedOpts.dark.before)
}
);
this.afterContentClassName = DecorationRenderHelper.createCSSRules(
styleSheet,
key,
null,
ModelDecorationCSSRuleType.AfterContentClassName,
{
light: DecorationRenderHelper.getCSSTextForModelDecorationContentClassName(themedOpts.light.after),
dark: DecorationRenderHelper.getCSSTextForModelDecorationContentClassName(themedOpts.dark.after)
}
);
this.glyphMarginClassName = DecorationRenderHelper.createCSSRules(
styleSheet,
key,
null,
ModelDecorationCSSRuleType.GlyphMarginClassName,
{
light: DecorationRenderHelper.getCSSTextForModelDecorationGlyphMarginClassName(themedOpts.light),
dark: DecorationRenderHelper.getCSSTextForModelDecorationGlyphMarginClassName(themedOpts.dark)
}
);
this.isWholeLine = Boolean(options.isWholeLine);
if (
typeof themedOpts.light.overviewRulerColor !== 'undefined'
|| typeof themedOpts.dark.overviewRulerColor !== 'undefined'
) {
this.overviewRuler = {
color: themedOpts.light.overviewRulerColor || themedOpts.dark.overviewRulerColor,
darkColor: themedOpts.dark.overviewRulerColor || themedOpts.light.overviewRulerColor,
position: options.overviewRulerLane || OverviewRulerLane.Center
};
}
this._disposable = toDisposable(() => {
dom.removeCSSRulesContainingSelector(CSSNameHelper.getDeletionSubstring(key), styleSheet);
});
}
public getOptions(codeEditorService: AbstractCodeEditorService, writable: boolean): IModelDecorationOptions {
if (!writable) {
return this;
}
return {
inlineClassName: this.inlineClassName,
beforeContentClassName: this.beforeContentClassName,
afterContentClassName: this.afterContentClassName,
className: this.className,
glyphMarginClassName: this.glyphMarginClassName,
isWholeLine: this.isWholeLine,
overviewRuler: this.overviewRuler,
stickiness: this.stickiness
};
}
public dispose(): void {
if (this._disposable) {
this._disposable.dispose();
delete this._disposable;
}
}
}
class DecorationRenderHelper {
private static _CSS_MAP = {
color: 'color:{0} !important;',
backgroundColor: 'background-color:{0};',
outline: 'outline:{0};',
outlineColor: 'outline-color:{0};',
outlineStyle: 'outline-style:{0};',
outlineWidth: 'outline-width:{0};',
border: 'border:{0};',
borderColor: 'border-color:{0};',
borderRadius: 'border-radius:{0};',
borderSpacing: 'border-spacing:{0};',
borderStyle: 'border-style:{0};',
borderWidth: 'border-width:{0};',
textDecoration: 'text-decoration:{0};',
cursor: 'cursor:{0};',
letterSpacing: 'letter-spacing:{0};',
gutterIconPath: 'background:url(\'{0}\') center center no-repeat;',
gutterIconSize: 'background-size:{0};',
contentText: 'content:\'{0}\';',
contentIconPath: 'content:url(\'{0}\');',
margin: 'margin:{0};',
width: 'width:{0};',
height: 'height:{0};'
};
/**
* Build the CSS for decorations styled via `className`.
*/
public static getCSSTextForModelDecorationClassName(opts: IThemeDecorationRenderOptions): string {
let cssTextArr = [];
DecorationRenderHelper.collectCSSText(opts, ['backgroundColor', 'outline', 'outlineColor', 'outlineStyle', 'outlineWidth'], cssTextArr);
DecorationRenderHelper.collectBorderSettingsCSSText(opts, cssTextArr);
return cssTextArr.join('');
}
/**
* Build the CSS for decorations styled via `inlineClassName`.
*/
public static getCSSTextForModelDecorationInlineClassName(opts: IThemeDecorationRenderOptions): string {
let cssTextArr = [];
DecorationRenderHelper.collectCSSText(opts, ['textDecoration', 'cursor', 'color', 'letterSpacing'], cssTextArr);
return cssTextArr.join('');
}
/**
* Build the CSS for decorations styled before or after content.
*/
public static getCSSTextForModelDecorationContentClassName(opts: IContentDecorationRenderOptions): string {
let cssTextArr = [];
if (typeof opts !== 'undefined') {
DecorationRenderHelper.collectBorderSettingsCSSText(opts, cssTextArr);
if (typeof opts.contentIconPath === 'string') {
cssTextArr.push(strings.format(this._CSS_MAP.contentIconPath, URI.file(opts.contentIconPath).toString().replace(/'/g, '%27')));
} else if (opts.contentIconPath instanceof URI) {
cssTextArr.push(strings.format(this._CSS_MAP.contentIconPath, opts.contentIconPath.toString(true).replace(/'/g, '%27')));
}
if (typeof opts.contentText === 'string') {
const truncated = opts.contentText.match(/^.*$/m)[0]; // only take first line
const escaped = truncated.replace(/['\\]/g, '\\$&');
cssTextArr.push(strings.format(this._CSS_MAP.contentText, escaped));
}
DecorationRenderHelper.collectCSSText(opts, ['textDecoration', 'color', 'backgroundColor', 'margin'], cssTextArr);
if (DecorationRenderHelper.collectCSSText(opts, ['width', 'height'], cssTextArr)) {
cssTextArr.push('display:inline-block;');
}
}
return cssTextArr.join('');
}
/**
* Build the CSS for decorations styled via `glpyhMarginClassName`.
*/
public static getCSSTextForModelDecorationGlyphMarginClassName(opts: IThemeDecorationRenderOptions): string {
let cssTextArr = [];
if (typeof opts.gutterIconPath !== 'undefined') {
if (typeof opts.gutterIconPath === 'string') {
cssTextArr.push(strings.format(this._CSS_MAP.gutterIconPath, URI.file(opts.gutterIconPath).toString()));
} else {
cssTextArr.push(strings.format(this._CSS_MAP.gutterIconPath, opts.gutterIconPath.toString(true).replace(/'/g, '%27')));
}
if (typeof opts.gutterIconSize !== 'undefined') {
cssTextArr.push(strings.format(this._CSS_MAP.gutterIconSize, opts.gutterIconSize));
}
}
return cssTextArr.join('');
}
private static border_rules = ['border', 'borderRadius', 'borderColor', 'borderSpacing', 'borderStyle', 'borderWidth'];
public static collectBorderSettingsCSSText(opts: any, cssTextArr: string[]): boolean {
if (DecorationRenderHelper.collectCSSText(opts, DecorationRenderHelper.border_rules, cssTextArr)) {
cssTextArr.push(strings.format('box-sizing: border-box;'));
return true;
}
return false;
}
private static collectCSSText(opts: any, properties: string[], cssTextArr: string[]): boolean {
let lenBefore = cssTextArr.length;
for (let property of properties) {
if (typeof opts[property] !== 'undefined') {
cssTextArr.push(strings.format(this._CSS_MAP[property], opts[property]));
}
}
return cssTextArr.length !== lenBefore;
}
/**
* Create CSS rules for `cssTexts` with the generated class names from `ruleType`
*/
public static createCSSRules(styleSheet: HTMLStyleElement, key: string, parentKey: string, ruleType: ModelDecorationCSSRuleType, cssTexts: { light: string, dark: string }): string {
function createCSSSelector(themeType: ThemeType, cssText: string) {
let selector = CSSNameHelper.getSelector(themeType, key, parentKey, ruleType);
dom.createCSSRule(selector, cssText, styleSheet);
}
let hasContent = false;
if (cssTexts.light.length > 0) {
createCSSSelector(ThemeType.Light, cssTexts.light);
hasContent = true;
}
if (cssTexts.dark.length > 0) {
createCSSSelector(ThemeType.Dark, cssTexts.dark);
createCSSSelector(ThemeType.HighContrastBlack, cssTexts.dark);
hasContent = true;
}
if (hasContent) {
let className = CSSNameHelper.getClassName(key, ruleType);
if (parentKey) {
className = className + ' ' + CSSNameHelper.getClassName(parentKey, ruleType);
}
return className;
}
return void 0;
}
}
const enum ThemeType {
Light = 0,
Dark = 1,
HighContrastBlack = 2
}
const enum ModelDecorationCSSRuleType {
ClassName = 0,
InlineClassName = 1,
GlyphMarginClassName = 2,
BeforeContentClassName = 3,
AfterContentClassName = 4
}
class CSSNameHelper {
private static _getSelectorPrefixOf(theme: ThemeType): string {
if (theme === ThemeType.Light) {
return '.monaco-editor.vs';
}
if (theme === ThemeType.Dark) {
return '.monaco-editor.vs-dark';
}
return '.monaco-editor.hc-black';
}
public static getClassName(key: string, type: ModelDecorationCSSRuleType): string {
return 'ced-' + key + '-' + type;
}
public static getSelector(themeType: ThemeType, key: string, parentKey: string, ruleType: ModelDecorationCSSRuleType): string {
let selector = this._getSelectorPrefixOf(themeType) + ' .' + this.getClassName(key, ruleType);
if (parentKey) {
selector = selector + '.' + this.getClassName(parentKey, ruleType);
}
if (ruleType === ModelDecorationCSSRuleType.BeforeContentClassName) {
selector += '::before';
} else if (ruleType === ModelDecorationCSSRuleType.AfterContentClassName) {
selector += '::after';
}
return selector;
}
public static getDeletionSubstring(key: string): string {
return '.ced-' + key + '-';
}
}
// ---- Normalize decoration render options per theme
interface IResolvedDecorationRenderOptions {
light: IThemeDecorationRenderOptions;
dark: IThemeDecorationRenderOptions;
}
function getThemedRenderOptions<T>(opts: { light?: T, dark?: T }): { light?: T, dark?: T } {
// TODO@alex,joh - not really how/what deep clone is being used
// for here but it will break the URI TODO@martin
// let light = <T> objects.deepClone(opts);
let light = <T>parse(stringify(opts));
objects.mixin(light, opts.light);
// let dark = <T> objects.deepClone(opts);
let dark = <T>parse(stringify(opts));
objects.mixin(dark, opts.dark);
return {
light: light,
dark: dark
};
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.