text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import localVarRequest from 'request';
import http from 'http';
/* tslint:disable:no-unused-locals */
import { SettingsChangeRequest } from '../model/settingsChangeRequest';
import { SettingsResponse } from '../model/settingsResponse';
import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models';
import { HttpBasicAuth, HttpBearerAuth, ApiKeyAuth, OAuth } from '../model/models';
import { HttpError, RequestFile } from './apis';
let defaultBasePath = 'https://api.hubapi.com';
// ===============================================
// This file is autogenerated - Please do not edit
// ===============================================
export enum SettingsApiApiKeys {
hapikey,
}
export class SettingsApi {
protected _basePath = defaultBasePath;
protected _defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications = {
'default': <Authentication>new VoidAuth(),
'hapikey': new ApiKeyAuth('query', 'hapikey'),
}
protected interceptors: Interceptor[] = [];
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
set basePath(basePath: string) {
this._basePath = basePath;
}
set defaultHeaders(defaultHeaders: any) {
this._defaultHeaders = defaultHeaders;
}
get defaultHeaders() {
return this._defaultHeaders;
}
get basePath() {
return this._basePath;
}
public setDefaultAuthentication(auth: Authentication) {
this.authentications.default = auth;
}
public setApiKey(key: SettingsApiApiKeys, value: string) {
(this.authentications as any)[SettingsApiApiKeys[key]].apiKey = value;
}
public addInterceptor(interceptor: Interceptor) {
this.interceptors.push(interceptor);
}
/**
* Resets webhook target URL to empty, and max concurrency limit to `0` for the given app. This will effectively pause all webhook subscriptions until new settings are provided.
* @summary Clear webhook settings
* @param appId The ID of the target app.
*/
public async clear (appId: number, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body?: any; }> {
const localVarPath = this.basePath + '/webhooks/v3/{appId}/settings'
.replace('{' + 'appId' + '}', encodeURIComponent(String(appId)));
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['*/*'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'appId' is not null or undefined
if (appId === null || appId === undefined) {
throw new Error('Required parameter appId was null or undefined when calling clear.');
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'DELETE',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
let authenticationPromise = Promise.resolve();
if (this.authentications.hapikey.apiKey) {
authenticationPromise = authenticationPromise.then(() => this.authentications.hapikey.applyToRequest(localVarRequestOptions));
}
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
/**
* Used to set the webhook target URL and max concurrency limit for the given app.
* @summary Configure webhook settings
* @param appId The ID of the target app.
* @param settingsChangeRequest Settings state to create new with or replace existing settings with.
*/
public async configure (appId: number, settingsChangeRequest: SettingsChangeRequest, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: SettingsResponse; }> {
const localVarPath = this.basePath + '/webhooks/v3/{appId}/settings'
.replace('{' + 'appId' + '}', encodeURIComponent(String(appId)));
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['application/json', '*/*'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'appId' is not null or undefined
if (appId === null || appId === undefined) {
throw new Error('Required parameter appId was null or undefined when calling configure.');
}
// verify required parameter 'settingsChangeRequest' is not null or undefined
if (settingsChangeRequest === null || settingsChangeRequest === undefined) {
throw new Error('Required parameter settingsChangeRequest was null or undefined when calling configure.');
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'PUT',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: ObjectSerializer.serialize(settingsChangeRequest, "SettingsChangeRequest")
};
let authenticationPromise = Promise.resolve();
if (this.authentications.hapikey.apiKey) {
authenticationPromise = authenticationPromise.then(() => this.authentications.hapikey.applyToRequest(localVarRequestOptions));
}
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: SettingsResponse; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
body = ObjectSerializer.deserialize(body, "SettingsResponse");
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
/**
* Returns the current state of webhook settings for the given app. These settings include the app\'s configured target URL and max concurrency limit.
* @summary Get webhook settings
* @param appId The ID of the target app.
*/
public async getAll (appId: number, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: SettingsResponse; }> {
const localVarPath = this.basePath + '/webhooks/v3/{appId}/settings'
.replace('{' + 'appId' + '}', encodeURIComponent(String(appId)));
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['application/json', '*/*'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'appId' is not null or undefined
if (appId === null || appId === undefined) {
throw new Error('Required parameter appId was null or undefined when calling getAll.');
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'GET',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
let authenticationPromise = Promise.resolve();
if (this.authentications.hapikey.apiKey) {
authenticationPromise = authenticationPromise.then(() => this.authentications.hapikey.applyToRequest(localVarRequestOptions));
}
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: SettingsResponse; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
body = ObjectSerializer.deserialize(body, "SettingsResponse");
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
} | the_stack |
import {ArrayExpression, BinaryExpression, CallExpression, Expression, Identifier, Literal, LogicalExpression, MemberExpression, Program, Statement, UnaryExpression} from "estree";
import {QueryEngineConstants} from "./query-engine-constants";
import {ParseException} from "./parse-exception";
import {ScriptExpression} from "./script-expression";
import {ScriptExpressionType} from "./script-expression-type";
/**
* Builds a script from an abstract syntax tree.
*/
export abstract class ScriptBuilder<E extends ScriptExpression, T> {
/**
* Constructs a {@code ScriptBuilder}.
*
* @param functions the ternjs functions
*/
constructor(private functions: any) {
}
/**
* Converts the specified abstract syntax tree to a transform script.
*
* @param program - the program node
* @returns the transform script
* @throws {Error} if a function definition is not valid
* @throws {ParseException} if the program is not valid
*/
toScript(program: Program): T {
// Check node parameters
if (program.type !== "Program") {
throw new Error("Cannot convert non-program");
}
if (program.body.length > 1) {
throw new Error("Program is too long");
}
// Convert to a script
const expression = program.body.length == 0 ? null : this.parseStatement(program.body[0] as Statement);
return this.prepareScript(expression);
}
/**
* Creates a script expression with the specified child expression appended to the parent expression.
*/
protected abstract appendChildExpression(parent: E, child: E): E;
/**
* Creates a script expression for the specified AST node.
*/
protected abstract createScriptExpression<X extends ScriptExpressionType>(source: any, type: X, start: number, end: number): E;
/**
* Creates a script expression from a function definition and AST node.
*/
protected abstract createScriptExpressionFromDefinition(definition: any, node: acorn.Node, ...var_args: E[]): E;
/**
* Indicates if the specified function definition can be converted to a script expression.
*/
protected abstract hasScriptExpression(definition: any): boolean;
/**
* Indicates if the specified expression type is an object.
*/
protected abstract isObject<X extends ScriptExpressionType>(sparkType: X): boolean;
/**
* Parses an identifier into a script expression.
*/
protected abstract parseIdentifier(node: Identifier & acorn.Node): E;
/**
* Converts the specified script expression to a transform script.
*/
protected abstract prepareScript(expression: E): T;
/**
* Gets the Ternjs name of the specified expression type.
*/
protected abstract toTernjsName<X extends ScriptExpressionType>(sparkType: X): string;
/**
* Converts an array expression node to a script expression.
*
* @param node - the array expression node
* @returns the script expression
* @throws {Error} if a function definition is not valid
* @throws {ParseException} if the node is not valid
*/
private parseArrayExpression(node: ArrayExpression & acorn.Node): E {
const source = node.elements.map(this.parseExpression.bind(this));
return this.createScriptExpression(source, ScriptExpressionType.ARRAY, node.start, node.end);
}
/**
* Converts a binary expression node to a script expression.
*
* @param node - the binary expression node
* @returns the script expression
* @throws {Error} if the function definition is not valid
* @throws {ParseException} if a function argument cannot be converted to the required type
*/
private parseBinaryExpression(node: BinaryExpression & acorn.Node): E {
// Get the function definition
let def = null;
switch (node.operator) {
case "+":
def = this.functions.add;
break;
case "-":
def = this.functions.subtract;
break;
case "*":
def = this.functions.multiply;
break;
case "/":
def = this.functions.divide;
break;
case "==":
def = this.functions.equal;
break;
case "!=":
def = this.functions.notEqual;
break;
case ">":
def = this.functions.greaterThan;
break;
case ">=":
def = this.functions.greaterThanOrEqual;
break;
case "<":
def = this.functions.lessThan;
break;
case "<=":
def = this.functions.lessThanOrEqual;
break;
case "%":
def = this.functions.mod;
break;
default:
}
if (def == null) {
throw new ParseException("Binary operator not supported: " + node.operator, node.start);
}
// Convert to a Spark expression
const left = this.parseExpression(node.left);
const right = this.parseExpression(node.right);
return this.createScriptExpressionFromDefinition(def, node, left, right);
}
/**
* Converts a call expression node to a script expression.
*
* @param node - the call expression node
* @returns the script expression
* @throws {Error} if the function definition is not valid
* @throws {ParseException} if a function argument cannot be converted to the required type
*/
private parseCallExpression(node: CallExpression): E {
// Get the function definition
let def;
let name;
let parent = null;
switch (node.callee.type) {
case "Identifier":
def = this.functions[node.callee.name];
name = node.callee.name;
break;
case "MemberExpression":
parent = this.parseExpression(node.callee.object as Expression);
// Find function definition
let ternjsName = this.toTernjsName(parent.type);
if (ternjsName !== null) {
def = this.functions[QueryEngineConstants.DEFINE_DIRECTIVE][ternjsName][(node.callee.property as Identifier).name];
} else {
throw new ParseException("Result type has no members: " + parent.type);
}
break;
default:
throw new ParseException("Function call type not supported: " + node.callee.type);
}
if (def == null) {
throw new ParseException("Function is not defined: " + name);
}
// Convert to a Spark expression
const args = [def, node].concat(node.arguments.map(this.parseExpression.bind(this)));
const spark = this.createScriptExpressionFromDefinition.apply(this, args);
return (parent !== null) ? this.appendChildExpression(parent, spark) : spark;
}
/**
* Converts the specified expression to a script expression object.
*/
private parseExpression(expression: Expression): E {
switch (expression.type) {
case "ArrayExpression":
return this.parseArrayExpression(expression as ArrayExpression & acorn.Node);
case "BinaryExpression":
return this.parseBinaryExpression(expression as BinaryExpression & acorn.Node);
case "CallExpression":
return this.parseCallExpression(expression as CallExpression);
case "Identifier":
return this.parseIdentifier(expression as Identifier & acorn.Node);
case "Literal":
const literal = expression as Literal & acorn.Node;
return this.createScriptExpression(literal.raw, ScriptExpressionType.LITERAL, literal.start, literal.end);
case "LogicalExpression":
return this.parseLogicalExpression(expression as LogicalExpression & acorn.Node);
case "MemberExpression":
return this.parseMemberExpression(expression as MemberExpression & acorn.Node);
case "UnaryExpression":
return this.parseUnaryExpression(expression as UnaryExpression & acorn.Node);
default:
throw new Error("Unsupported expression type: " + expression.type);
}
}
/**
* Converts a logical expression node to a script expression.
*
* @param node - the logical expression node
* @returns the script expression
* @throws {Error} if the function definition is not valid
* @throws {ParseException} if a function argument cannot be converted to the required type
*/
private parseLogicalExpression(node: LogicalExpression & acorn.Node): E {
// Get the function definition
let def = null;
switch (node.operator) {
case "&&":
def = this.functions.and;
break;
case "||":
def = this.functions.or;
break;
default:
}
if (def == null) {
throw new ParseException("Logical operator not supported: " + node.operator, node.start);
}
// Convert to a Spark expression
const left = this.parseExpression(node.left);
const right = this.parseExpression(node.right);
return this.createScriptExpressionFromDefinition(def, node, left, right);
}
/**
* Converts the specified member expression to a script expression object.
*
* @param node - the abstract syntax tree
* @returns the script expression
* @throws {Error} if a function definition is not valid
* @throws {ParseException} if the node is not valid
*/
private parseMemberExpression(node: MemberExpression & acorn.Node): E {
// Check object type
if (node.object.type !== "Identifier") {
throw new ParseException("Unexpected object type for member expression: " + node.object.type);
}
// Create child expression
const parentDef = this.functions[node.object.name];
const childDef = parentDef[(node.property as Identifier).name];
const expression = this.createScriptExpressionFromDefinition(childDef, node);
// Check for parent expression
if (this.hasScriptExpression(parentDef)) {
const parent = this.createScriptExpressionFromDefinition(parentDef, node);
return this.appendChildExpression(parent, expression);
} else {
return expression;
}
}
/**
* Converts the specified statement to a script expression object.
*
* @param statement - the abstract syntax tree
* @returns the script expression
* @throws {Error} if a function definition is not valid
* @throws {ParseException} if the node is not valid
*/
private parseStatement(statement: Statement): E {
if (statement.type === "ExpressionStatement") {
return this.parseExpression(statement.expression);
} else {
throw new Error("Unsupported statement type: " + statement.type);
}
}
/**
* Converts a unary expression node to a script expression.
*
* @param node - the unary expression node
* @returns the script expression
* @throws {Error} if the function definition is not valid
* @throws {ParseException} if a function argument cannot be converted to the required type
*/
private parseUnaryExpression(node: UnaryExpression & acorn.Node): E {
// Get the function definition
let arg = this.parseExpression(node.argument);
let def = null;
switch (node.operator) {
case "-":
if (ScriptExpressionType.COLUMN.equals(arg.type)) {
def = this.functions.negate;
} else if (ScriptExpressionType.LITERAL.equals(arg.type)) {
return this.createScriptExpression("-" + arg.source, ScriptExpressionType.LITERAL, arg.start, node.end);
}
break;
case "!":
def = this.functions.not;
break;
default:
}
if (def === null) {
throw new ParseException("Unary operator not supported: " + node.operator, node.start);
}
// Convert to a Spark expression
return this.createScriptExpressionFromDefinition(def, node, arg);
}
} | the_stack |
import * as constants from "../constants";
import * as path from "path";
import { isInteractive } from "../common/helpers";
import { ICreateProjectData, IProjectService } from "../definitions/project";
import { IOptions } from "../declarations";
import { ICommand, ICommandParameter } from "../common/definitions/commands";
import { IErrors } from "../common/declarations";
import { injector } from "../common/yok";
export class CreateProjectCommand implements ICommand {
public enableHooks = false;
public allowedParameters: ICommandParameter[] = [this.$stringParameter];
private static BlankTemplateKey = "Blank";
private static BlankTemplateDescription = "A blank app";
private static BlankTsTemplateKey = "Blank Typescript";
private static BlankTsTemplateDescription = "A blank typescript app";
private static HelloWorldTemplateKey = "Hello World";
private static HelloWorldTemplateDescription = "A Hello World app";
private static DrawerTemplateKey = "SideDrawer";
private static DrawerTemplateDescription =
"An app with pre-built pages that uses a drawer for navigation";
private static TabsTemplateKey = "Tabs";
private static TabsTemplateDescription =
"An app with pre-built pages that uses tabs for navigation";
private isInteractionIntroShown = false;
private createdProjectData: ICreateProjectData;
constructor(
private $projectService: IProjectService,
private $logger: ILogger,
private $errors: IErrors,
private $options: IOptions,
private $prompter: IPrompter,
private $stringParameter: ICommandParameter
) {}
public async execute(args: string[]): Promise<void> {
const interactiveAdverbs = ["First", "Next", "Finally"];
const getNextInteractiveAdverb = () => {
return interactiveAdverbs.shift() || "Next";
};
if (
(this.$options.tsc ||
this.$options.ng ||
this.$options.vue ||
this.$options.react ||
this.$options.svelte ||
this.$options.js) &&
this.$options.template
) {
this.$errors.failWithHelp(
"You cannot use a flavor option like --ng, --vue, --react, --svelte, --tsc and --js together with --template."
);
}
let projectName = args[0];
let selectedTemplate: string;
if (this.$options.js) {
selectedTemplate = constants.JAVASCRIPT_NAME;
} else if (this.$options.vue && this.$options.tsc) {
selectedTemplate = "@nativescript/template-blank-vue-ts";
} else if (this.$options.tsc) {
selectedTemplate = constants.TYPESCRIPT_NAME;
} else if (this.$options.ng) {
selectedTemplate = constants.ANGULAR_NAME;
} else if (this.$options.vue) {
selectedTemplate = constants.VUE_NAME;
} else if (this.$options.react) {
selectedTemplate = constants.REACT_NAME;
} else if (this.$options.svelte) {
selectedTemplate = constants.SVELTE_NAME;
} else {
selectedTemplate = this.$options.template;
}
if (!projectName && isInteractive()) {
this.printInteractiveCreationIntroIfNeeded();
projectName = await this.$prompter.getString(
`${getNextInteractiveAdverb()}, what will be the name of your app?`,
{ allowEmpty: false }
);
this.$logger.info();
}
projectName = await this.$projectService.validateProjectName({
projectName: projectName,
force: this.$options.force,
pathToProject: this.$options.path,
});
if (!selectedTemplate && isInteractive()) {
this.printInteractiveCreationIntroIfNeeded();
selectedTemplate = await this.interactiveFlavorAndTemplateSelection(
getNextInteractiveAdverb(),
getNextInteractiveAdverb()
);
}
this.createdProjectData = await this.$projectService.createProject({
projectName: projectName,
template: selectedTemplate,
appId: this.$options.appid,
pathToProject: this.$options.path,
// its already validated above
force: true,
ignoreScripts: this.$options.ignoreScripts,
});
}
private async interactiveFlavorAndTemplateSelection(
flavorAdverb: string,
templateAdverb: string
) {
const selectedFlavor = await this.interactiveFlavorSelection(flavorAdverb);
const selectedTemplate: string = await this.interactiveTemplateSelection(
selectedFlavor,
templateAdverb
);
return selectedTemplate;
}
private async interactiveFlavorSelection(adverb: string) {
const flavorSelection = await this.$prompter.promptForDetailedChoice(
`${adverb}, which style of NativeScript project would you like to use:`,
[
{
key: constants.NgFlavorName,
description: "Learn more at https://nativescript.org/angular",
},
{
key: constants.ReactFlavorName,
description:
"Learn more at https://github.com/shirakaba/react-nativescript",
},
{
key: constants.VueFlavorName,
description: "Learn more at https://nativescript.org/vue",
},
{
key: constants.SvelteFlavorName,
description: "Learn more at https://svelte-native.technology",
},
{
key: constants.TsFlavorName,
description: "Learn more at https://nativescript.org/typescript",
},
{
key: constants.JsFlavorName,
description: "Use NativeScript without any framework",
},
]
);
return flavorSelection;
}
private printInteractiveCreationIntroIfNeeded() {
if (!this.isInteractionIntroShown) {
this.isInteractionIntroShown = true;
this.$logger.info();
this.$logger.printMarkdown(`# Let’s create a NativeScript app!`);
this.$logger.printMarkdown(`
Answer the following questions to help us build the right app for you. (Note: you
can skip this prompt next time using the --template option, or the --ng, --react, --vue, --svelte, --ts, or --js flags.)
`);
}
}
private async interactiveTemplateSelection(
flavorSelection: string,
adverb: string
) {
const selectedFlavorTemplates: {
key?: string;
value: string;
description?: string;
}[] = [];
let selectedTemplate: string;
switch (flavorSelection) {
case constants.NgFlavorName: {
selectedFlavorTemplates.push(...this.getNgTemplates());
break;
}
case constants.ReactFlavorName: {
selectedFlavorTemplates.push(...this.getReactTemplates());
break;
}
case constants.VueFlavorName: {
selectedFlavorTemplates.push(...this.getVueTemplates());
break;
}
case constants.SvelteFlavorName: {
selectedFlavorTemplates.push(...this.getSvelteTemplates());
break;
}
case constants.TsFlavorName: {
selectedFlavorTemplates.push(...this.getTsTemplates());
break;
}
case constants.JsFlavorName: {
selectedFlavorTemplates.push(...this.getJsTemplates());
break;
}
}
if (selectedFlavorTemplates.length > 1) {
this.$logger.info();
const templateChoices = selectedFlavorTemplates.map((template) => {
return { key: template.key, description: template.description };
});
const selectedTemplateKey = await this.$prompter.promptForDetailedChoice(
`${adverb}, which template would you like to start from:`,
templateChoices
);
selectedTemplate = selectedFlavorTemplates.find(
(t) => t.key === selectedTemplateKey
).value;
} else {
selectedTemplate = selectedFlavorTemplates[0].value;
}
return selectedTemplate;
}
private getJsTemplates() {
const templates = [
{
key: CreateProjectCommand.HelloWorldTemplateKey,
value: constants.RESERVED_TEMPLATE_NAMES.javascript,
description: CreateProjectCommand.HelloWorldTemplateDescription,
},
{
key: CreateProjectCommand.DrawerTemplateKey,
value: "@nativescript/template-drawer-navigation",
description: CreateProjectCommand.DrawerTemplateDescription,
},
{
key: CreateProjectCommand.TabsTemplateKey,
value: "@nativescript/template-tab-navigation",
description: CreateProjectCommand.TabsTemplateDescription,
},
];
return templates;
}
private getTsTemplates() {
const templates = [
{
key: CreateProjectCommand.HelloWorldTemplateKey,
value: constants.RESERVED_TEMPLATE_NAMES.typescript,
description: CreateProjectCommand.HelloWorldTemplateDescription,
},
{
key: CreateProjectCommand.DrawerTemplateKey,
value: "@nativescript/template-drawer-navigation-ts",
description: CreateProjectCommand.DrawerTemplateDescription,
},
{
key: CreateProjectCommand.TabsTemplateKey,
value: "@nativescript/template-tab-navigation-ts",
description: CreateProjectCommand.TabsTemplateDescription,
},
];
return templates;
}
private getNgTemplates() {
const templates = [
{
key: CreateProjectCommand.HelloWorldTemplateKey,
value: constants.RESERVED_TEMPLATE_NAMES.angular,
description: CreateProjectCommand.HelloWorldTemplateDescription,
},
{
key: CreateProjectCommand.DrawerTemplateKey,
value: "@nativescript/template-drawer-navigation-ng",
description: CreateProjectCommand.DrawerTemplateDescription,
},
{
key: CreateProjectCommand.TabsTemplateKey,
value: "@nativescript/template-tab-navigation-ng",
description: CreateProjectCommand.TabsTemplateDescription,
},
];
return templates;
}
private getReactTemplates() {
const templates = [
{
key: CreateProjectCommand.HelloWorldTemplateKey,
value: constants.RESERVED_TEMPLATE_NAMES.react,
description: CreateProjectCommand.HelloWorldTemplateDescription,
},
];
return templates;
}
private getSvelteTemplates() {
const templates = [
{
key: CreateProjectCommand.HelloWorldTemplateKey,
value: constants.RESERVED_TEMPLATE_NAMES.svelte,
description: CreateProjectCommand.HelloWorldTemplateDescription,
},
];
return templates;
}
private getVueTemplates() {
const templates = [
{
key: CreateProjectCommand.BlankTemplateKey,
value: "@nativescript/template-blank-vue",
description: CreateProjectCommand.BlankTemplateDescription,
},
{
key: CreateProjectCommand.BlankTsTemplateKey,
value: "@nativescript/template-blank-vue-ts",
description: CreateProjectCommand.BlankTsTemplateDescription,
},
{
key: CreateProjectCommand.DrawerTemplateKey,
value: "@nativescript/template-drawer-navigation-vue",
description: CreateProjectCommand.DrawerTemplateDescription,
},
{
key: CreateProjectCommand.TabsTemplateKey,
value: "@nativescript/template-tab-navigation-vue",
description: CreateProjectCommand.TabsTemplateDescription,
},
];
return templates;
}
public async postCommandAction(args: string[]): Promise<void> {
const { projectDir, projectName } = this.createdProjectData;
const relativePath = path.relative(process.cwd(), projectDir);
const greyDollarSign = "$".grey;
this.$logger.clearScreen();
this.$logger.info(
[
[
`Project`.green,
projectName.cyan,
`was successfully created.`.green,
].join(" "),
"",
`Now you can navigate to your project with ${
`cd ${relativePath}`.cyan
} and then:`,
"",
`Run the project on multiple devices:`,
"",
` ${greyDollarSign} ${"ns run ios".green}`,
` ${greyDollarSign} ${"ns run android".green}`,
"",
"Debug the project with Chrome DevTools:",
"",
` ${greyDollarSign} ${"ns debug ios".green}`,
` ${greyDollarSign} ${"ns debug android".green}`,
``,
`For more options consult the docs or run ${"ns --help".green}`,
"",
].join("\n")
);
// Commented as we may bring this back with a playground revision/rewrite
// this.$logger.printMarkdown(
// `After that you can preview it on device by executing \`$ ns preview\``
// );
}
}
injector.registerCommand("create", CreateProjectCommand); | the_stack |
import { EventHandler } from './event-handler';
import { isNullOrUndefined, getValue, setValue, isObject, extend } from './util';
const SVG_REG: RegExp = /^svg|^path|^g/;
export interface ElementProperties {
id?: string;
className?: string;
innerHTML?: string;
styles?: string;
attrs?: { [key: string]: string };
}
/**
* Function to create Html element.
*
* @param {string} tagName - Name of the tag, id and class names.
* @param {ElementProperties} properties - Object to set properties in the element.
* @param {ElementProperties} properties.id - To set the id to the created element.
* @param {ElementProperties} properties.className - To add classes to the element.
* @param {ElementProperties} properties.innerHTML - To set the innerHTML to element.
* @param {ElementProperties} properties.styles - To set the some custom styles to element.
* @param {ElementProperties} properties.attrs - To set the attributes to element.
* @returns {any} ?
* @private
*/
export function createElement(tagName: string, properties?: ElementProperties): HTMLElement {
const element: Element = (SVG_REG.test(tagName) ? document.createElementNS('http://www.w3.org/2000/svg', tagName) : document.createElement(tagName));
if (typeof (properties) === 'undefined') {
return <HTMLElement>element;
}
element.innerHTML = (properties.innerHTML ? properties.innerHTML : '');
if (properties.className !== undefined) {
element.className = properties.className;
}
if (properties.id !== undefined) {
element.id = properties.id;
}
if (properties.styles !== undefined) {
element.setAttribute('style', properties.styles);
}
if (properties.attrs !== undefined) {
attributes(element, properties.attrs);
}
return <HTMLElement>element;
}
/**
* The function used to add the classes to array of elements
*
* @param {Element[]|NodeList} elements - An array of elements that need to add a list of classes
* @param {string|string[]} classes - String or array of string that need to add an individual element as a class
* @returns {any} .
* @private
*/
export function addClass(elements: Element[] | NodeList, classes: string | string[]): Element[] | NodeList {
const classList: string[] = getClassList(classes);
for (const ele of (elements as Element[])) {
for (const className of classList) {
if (isObject(ele)) {
const curClass: string = getValue('attributes.className', ele);
if (isNullOrUndefined(curClass)) {
setValue('attributes.className', className, ele);
} else if (!new RegExp('\\b' + className + '\\b', 'i').test(curClass)) {
setValue('attributes.className', curClass + ' ' + className, ele);
}
} else {
if (!ele.classList.contains(className)) {
ele.classList.add(className);
}
}
}
}
return elements;
}
/**
* The function used to add the classes to array of elements
*
* @param {Element[]|NodeList} elements - An array of elements that need to remove a list of classes
* @param {string|string[]} classes - String or array of string that need to add an individual element as a class
* @returns {any} .
* @private
*/
export function removeClass(elements: Element[] | NodeList, classes: string | string[]): Element[] | NodeList {
const classList: string[] = getClassList(classes);
for (const ele of (elements as Element[])) {
const flag: boolean = isObject(ele);
const canRemove: boolean = flag ? getValue('attributes.className', ele) : ele.className !== '';
if (canRemove) {
for (const className of classList) {
if (flag) {
const classes: string = getValue('attributes.className', ele);
const classArr: string[] = classes.split(' ');
const index: number = classArr.indexOf(className);
if (index !== -1) {
classArr.splice(index, 1);
}
setValue('attributes.className', classArr.join(' '), ele);
} else {
ele.classList.remove(className);
}
}
}
}
return elements;
}
/**
* The function used to get classlist.
*
* @param {string | string[]} classes - An element the need to check visibility
* @returns {string[]} ?
* @private
*/
function getClassList(classes: string | string[]): string[] {
let classList: string[] = [];
if (typeof classes === 'string') {
classList.push(classes);
} else {
classList = classes;
}
return classList;
}
/**
* The function used to check element is visible or not.
*
* @param {Element|Node} element - An element the need to check visibility
* @returns {boolean} ?
* @private
*/
export function isVisible(element: Element | Node): boolean {
const ele: HTMLElement = <HTMLElement>element;
return (ele.style.visibility === '' && ele.offsetWidth > 0);
}
/**
* The function used to insert an array of elements into a first of the element.
*
* @param {Element[]|NodeList} fromElements - An array of elements that need to prepend.
* @param {Element} toElement - An element that is going to prepend.
* @param {boolean} isEval - ?
* @returns {Element[] | NodeList} ?
* @private
*/
export function prepend(fromElements: Element[] | NodeList, toElement: Element, isEval?: boolean): Element[] | NodeList {
const docFrag: DocumentFragment = document.createDocumentFragment();
for (const ele of (fromElements as Element[])) {
docFrag.appendChild(ele);
}
toElement.insertBefore(docFrag, toElement.firstElementChild);
if (isEval) {
executeScript(toElement);
}
return fromElements;
}
/**
* The function used to insert an array of elements into last of the element.
*
* @param {Element[]|NodeList} fromElements - An array of elements that need to append.
* @param {Element} toElement - An element that is going to prepend.
* @param {boolean} isEval - ?
* @returns {Element[] | NodeList} ?
* @private
*/
export function append(fromElements: Element[] | NodeList, toElement: Element, isEval?: boolean): Element[] | NodeList {
const docFrag: DocumentFragment = document.createDocumentFragment();
for (const ele of <Element[]>fromElements) {
docFrag.appendChild(ele);
}
toElement.appendChild(docFrag);
if (isEval) {
executeScript(toElement);
}
return fromElements;
}
/**
* The function is used to evaluate script from Ajax request
*
* @param {Element} ele - An element is going to evaluate the script
* @returns {void} ?
*/
function executeScript(ele: Element): void {
const eleArray: NodeList = ele.querySelectorAll('script');
eleArray.forEach((element: Element) => {
const script: HTMLScriptElement = document.createElement('script');
script.text = element.innerHTML;
document.head.appendChild(script);
detach(script);
});
}
/**
* The function used to remove the element from parentnode
*
* @param {Element|Node|HTMLElement} element - An element that is going to detach from the Dom
* @returns {any} ?
* @private
*/
// eslint-disable-next-line
export function detach(element: Element | Node | HTMLElement): any {
const parentNode: Node = element.parentNode;
if (parentNode) {
return <Element>parentNode.removeChild(element);
}
}
/**
* The function used to remove the element from Dom also clear the bounded events
*
* @param {Element|Node|HTMLElement} element - An element remove from the Dom
* @returns {void} ?
* @private
*/
export function remove(element: Element | Node | HTMLElement): void {
const parentNode: Node = element.parentNode;
EventHandler.clearEvents(<Element>element);
parentNode.removeChild(element);
}
/**
* The function helps to set multiple attributes to an element
*
* @param {Element|Node} element - An element that need to set attributes.
* @param {string} attributes - JSON Object that is going to as attributes.
* @returns {Element} ?
* @private
*/
// eslint-disable-next-line
export function attributes(element: Element | Node | any, attributes: { [key: string]: string }): Element {
const keys: string[] = Object.keys(attributes);
const ele: Element = <Element>element;
for (const key of keys) {
if (isObject(ele)) {
let iKey: string = key;
if (key === 'tabindex') {
iKey = 'tabIndex';
}
ele.attributes[iKey] = attributes[key];
} else {
ele.setAttribute(key, attributes[key]);
}
}
return ele;
}
/**
* The function selects the element from giving context.
*
* @param {string} selector - Selector string need fetch element
* @param {Document|Element} context - It is an optional type, That specifies a Dom context.
* @param {boolean} needsVDOM ?
* @returns {any} ?
* @private
*/
// eslint-disable-next-line
export function select(selector: string, context: Document | Element = document, needsVDOM?: boolean): any {
selector = querySelectId(selector);
return context.querySelector(selector);
}
/**
* The function selects an array of element from the given context.
*
* @param {string} selector - Selector string need fetch element
* @param {Document|Element} context - It is an optional type, That specifies a Dom context.
* @param {boolean} needsVDOM ?
* @returns {HTMLElement[]} ?
* @private
*/
// eslint-disable-next-line
export function selectAll(selector: string, context: Document | Element = document, needsVDOM?: boolean): HTMLElement[] {
selector = querySelectId(selector);
const nodeList: NodeList = context.querySelectorAll(selector);
return <HTMLElement[] & NodeList>nodeList;
}
/**
* The function selects an id of element from the given context.
*
* @param {string} selector - Selector string need fetch element
* @returns {string} ?
* @private
*/
function querySelectId(selector: string): string {
const charRegex: RegExp = /(!|"|\$|%|&|'|\(|\)|\*|\/|:|;|<|=|\?|@|\]|\^|`|{|}|\||\+|~)/g;
if (selector.match(/#[0-9]/g) || selector.match(charRegex)) {
const idList: string[] = selector.split(',');
for (let i: number = 0; i < idList.length; i++) {
const list: string[] = idList[i].split(' ');
for (let j: number = 0; j < list.length; j++) {
if (list[j].indexOf('#') > -1) {
if (!list[j].match(/\[.*\]/)) {
const splitId: string[] = list[j].split('#');
if (splitId[1].match(/^\d/) || splitId[1].match(charRegex)) {
const setId: string[] = list[j].split('.');
setId[0] = setId[0].replace(/#/, '[id=\'') + '\']';
list[j] = setId.join('.');
}
}
}
}
idList[i] = list.join(' ');
}
return idList.join(',');
}
return selector;
}
/**
* Returns single closest parent element based on class selector.
*
* @param {Element} element - An element that need to find the closest element.
* @param {string} selector - A classSelector of closest element.
* @returns {Element} ?
* @private
*/
export function closest(element: Element | Node, selector: string): Element {
let el: Element = <Element>element;
if (typeof el.closest === 'function') {
return el.closest(selector);
}
while (el && el.nodeType === 1) {
if (matches(el, selector)) {
return el;
}
el = <Element>el.parentNode;
}
return null;
}
/**
* Returns all sibling elements of the given element.
*
* @param {Element|Node} element - An element that need to get siblings.
* @returns {Element[]} ?
* @private
*/
export function siblings(element: Element | Node): Element[] {
const siblings: Element[] = [];
const childNodes: Node[] = Array.prototype.slice.call(element.parentNode.childNodes);
for (const curNode of childNodes) {
if (curNode.nodeType === Node.ELEMENT_NODE && element !== curNode) {
siblings.push(<Element>curNode);
}
}
return <Element[]>siblings;
}
/**
* set the value if not exist. Otherwise set the existing value
*
* @param {HTMLElement} element - An element to which we need to set value.
* @param {string} property - Property need to get or set.
* @param {string} value - value need to set.
* @returns {string} ?
* @private
*/
export function getAttributeOrDefault(element: HTMLElement, property: string, value: string): string {
let attrVal: string;
const isObj: boolean = isObject(element);
if (isObj) {
attrVal = getValue('attributes.' + property, element);
} else {
attrVal = element.getAttribute(property);
}
if (isNullOrUndefined(attrVal) && value) {
if (!isObj) {
element.setAttribute(property, value.toString());
} else {
element.attributes[property] = value;
}
attrVal = value;
}
return attrVal;
}
/**
* Set the style attributes to Html element.
*
* @param {HTMLElement} element - Element which we want to set attributes
* @param {any} attrs - Set the given attributes to element
* @returns {void} ?
* @private
*/
export function setStyleAttribute(element: HTMLElement, attrs: { [key: string]: Object }): void {
if (attrs !== undefined) {
Object.keys(attrs).forEach((key: string) => {
// eslint-disable-next-line
(<any>element).style[key] = attrs[key];
});
}
}
/**
* Method for add and remove classes to a dom element.
*
* @param {Element} element - Element for add and remove classes
* @param {string[]} addClasses - List of classes need to be add to the element
* @param {string[]} removeClasses - List of classes need to be remove from the element
* @returns {void} ?
* @private
*/
export function classList(element: Element, addClasses: string[], removeClasses: string[]): void {
addClass([element], addClasses);
removeClass([element], removeClasses);
}
/**
* Method to check whether the element matches the given selector.
*
* @param {Element} element - Element to compare with the selector.
* @param {string} selector - String selector which element will satisfy.
* @returns {void} ?
* @private
*/
export function matches(element: Element, selector: string): boolean {
// eslint-disable-next-line
let matches: Function = element.matches || (element as any).msMatchesSelector || element.webkitMatchesSelector;
if (matches) {
return matches.call(element, selector);
} else {
return [].indexOf.call(document.querySelectorAll(selector), element) !== -1;
}
}
/**
* Method to get the html text from DOM.
*
* @param {HTMLElement} ele - Element to compare with the selector.
* @param {string} innerHTML - String selector which element will satisfy.
* @returns {void} ?
* @private
*/
export function includeInnerHTML(ele: HTMLElement, innerHTML: string): void {
ele.innerHTML = innerHTML;
}
/**
* Method to get the containsclass.
*
* @param {HTMLElement} ele - Element to compare with the selector.
* @param {string} className - String selector which element will satisfy.
* @returns {any} ?
* @private
*/
// eslint-disable-next-line
export function containsClass(ele: HTMLElement, className: string): any {
if (isObject(ele)) {
// eslint-disable-next-line
return new RegExp('\\b' + className + '\\b', 'i').test((ele as any).attributes.className);
} else {
return ele.classList.contains(className);
}
}
/**
* Method to check whether the element matches the given selector.
*
* @param {Object} element - Element to compare with the selector.
* @param {boolean} deep ?
* @returns {any} ?
* @private
*/
// eslint-disable-next-line
export function cloneNode(element: Object, deep?: boolean): any {
if (isObject(element)) {
if (deep) {
return extend({}, {}, element, true);
}
} else {
return (element as HTMLElement).cloneNode(deep);
}
} | the_stack |
// A '.tsx' file enables JSX support in the TypeScript compiler,
// for more information see the following page on the TypeScript wiki:
// https://github.com/Microsoft/TypeScript/wiki/JSX
import { ReactNode } from 'react';
// 重新导出 ReactNode
export { ReactNode } from 'react';
/**
* 提供 UBB 处理上下文所需要的相关数据。
*/
export class UbbCodeContextData {
/**
* 引用深度,0表示最外层
*/
isInQuote: boolean = false;
/**
* 是否是一列引用中最后一行引用
* 用来定制样式
*/
islastQuote: boolean = false;
/**
* 图片计数
*/
imageCount = 0;
}
/**
* 处理 UBB 编码时可用于存储相关信息的上下文对象。
*/
export class UbbCodeContext {
/**
* 关联到本次处理上下文的处理引擎对象。
*/
private _engine: UbbCodeEngine;
/**
* 获取关联到本次处理上下文的处理引擎对象。
* @returns {UbbCodeEngine} 关联到本次处理上下文的处理引擎对象。
*/
get engine(): UbbCodeEngine {
return this._engine;
}
/**
* 处理 UBB 需要注意的选项。
*/
private _options: UbbCodeOptions;
/**
* 获取处理 UBB 需要注意的选项。
* @returns {UbbCodeOptions} 处理 UBB 需要注意的选项。
*/
get options(): UbbCodeOptions {
return this._options;
}
/**
* 初始化一个上下文对象的新实例。
* @param engine 引擎对象。
* @param options 处理选项。
*/
constructor(engine: UbbCodeEngine, options: UbbCodeOptions) {
this._engine = engine;
this._options = options;
}
/**
* 获取上下文相关的数据。
* @returns {UbbCodeContextData} 上下文相关的数据。
*/
get data(): UbbCodeContextData {
return this._engine.data;
}
}
/**
* 控制 UBB 编码的选项。在 UBB 编码过程中,需要考虑这些选项。
*/
export class UbbCodeOptions {
/**
* 是否自动检测 URL 并添加链接效果。
*/
autoDetectUrl = true;
/**
* 是否允许外部链接。
*/
allowExternalUrl = true;
/**
* 是否允许显示图像。
*/
allowImage = true;
/**
* 是否允许显示外部图像
*/
allowExternalImage = true;
/**
* 是否允许鼠标移至图片时显示工具栏
*/
allowToolbox = false;
/**
* 是否允许多媒体资源,如视频,音频,Flash 等。
*/
allowMediaContent = true;
/**
* 是否允许自动播放多媒体资源。
*/
allowAutoPlay = true;
/**
* 是否允许解析表情。
*/
allowEmotion = true;
/**
* UBB 处理中的兼容性控制选项。
*/
compatibility = UbbCompatiblityMode.Recommended;
/**
* 是否允许解析markdown
*/
allowMarkDown?= true;
/**
* 最大允许的图片数量
*
*/
maxImageCount = Infinity;
}
/**
* 定义 UBB 呈现时使用的兼容性模式。
*/
export enum UbbCompatiblityMode {
/**
* 使用最低级别兼容性,尽可能保持 UBB 代码的原始含义,即使可能会带来显示效果问题。
*/
Transitional,
/**
* 如果能在不改变语义的情况下使用较新的呈现技术,则使用新技术;如果不能保证语义一致则不进行更改。
*/
Recommended,
/**
* 强制使用对现代浏览器更友好的新技术呈现,即使可能在一定程度上改变语义。
*/
EnforceMorden
}
/**
* 定义符号的类型。
*/
enum TokenType {
/**
* 一串文本。
*/
String,
/**
* 项目之间的分隔符。
*/
ItemSeperator,
/**
* 单个项目内名称和值的分隔符。
*/
NameValueSeperator
}
/**
* 表示一个符号。
*/
class Token {
/**
* 获取或设置符号的类型。
*/
type: TokenType;
/**
* 获取或设置符号的值。
*/
value: string;
/**
* 初始化一个符号对象的新实例。
* @param type 符号的类型。
* @param value 符号的值。
*/
constructor(type: TokenType, value: string) {
this.type = type;
this.value = value;
}
/**
* 获取表示项目分隔符的符号。
*/
static itemSeperator = new Token(TokenType.ItemSeperator, null);
/**
* 获取表示值分隔符的符号。
*/
static nameValueSeperator = new Token(TokenType.NameValueSeperator, null);
/**
* 创建一个表示一串文本的符号。
* @param value 文本的值内容。
*/
static stringValue(value: string) {
return new Token(TokenType.String, value);
}
}
/**
* 定义 UBB 片段的类型。
*/
export enum UbbSegmentType {
/**
* 纯文字片段。
*/
Text,
/**
* 标签片段。
*/
Tag
}
/**
* 表示 UBB 内容的一个片段。
*/
export abstract class UbbSegment {
/**
* 获取该 UBB 片段的类型。
* @returns {UbbSegmentType} 该 UBB 片段的类型。
*/
abstract get type(): UbbSegmentType;
/**
* 该对象的上级片段。
*/
private _parent: UbbTagSegment;
/**
* 获取该对象的上级片段。
* @returns {UbbSegment} 该对象的上级片段。
*/
get parent(): UbbTagSegment { return this._parent };
/**
* 初始化一个 UBB 片段的新实例。
* @param parent 新片段的上级。
*/
constructor(parent: UbbTagSegment) {
this._parent = parent;
}
/**
* 复制一个节点并更换新上级。
* @param newParent 新的上级。
*/
abstract clone(newParent: UbbTagSegment): UbbSegment;
}
/**
* 表示 UBB 的文字片段。
*/
export class UbbTextSegment extends UbbSegment {
get type(): UbbSegmentType { return UbbSegmentType.Text };
/**
* 片段中包含的文字。
*/
private _text: string;
/**
* 获取片段中包含的文字。
* @returns {string} 片段中包含的文字。
*/
get text() { return this._text };
/**
* 创建一个新的 UbbTextSegment 对象。
* @param text 新片段包含的文字。
*/
constructor(text: string, parent: UbbTagSegment) {
super(parent);
this._text = text;
}
clone(newParent: UbbTagSegment): UbbSegment {
return new UbbTextSegment(this._text, newParent);
}
}
/**
* 表示 UBB 的标签片段。
*/
export class UbbTagSegment extends UbbSegment {
get type(): UbbSegmentType { return UbbSegmentType.Tag; }
/**
* 标签片段是否关闭。
*/
private _isClosed = false;
/**
* 获取一个值,指示标签是否关闭。
* @returns {boolean}
*/
get isClosed() { return this._isClosed };
/**
* 标签的数据类型。
*/
private _tagData: UbbTagData;
/**
* 标签中包含的子标签数据。
*/
private _subSegments: UbbSegment[] = [];
/**
* 标签中包含的子标签。
*/
private _content: string;
get tagData(): UbbTagData { return this._tagData };
get subSegments(): UbbSegment[] { return this._subSegments; };
constructor(tagData: UbbTagData, parent: UbbTagSegment) {
super(parent);
this._tagData = tagData;
}
/**
* 强制关闭一个标签,并将标签挂接到新的上级标签。
* @param segment 要关闭的标签。
* @param newParent 新的上级标签。
* @returns {UbbSegment[]} 产生的新的标签的集合。
*/
private static forceClose(segment: UbbSegment, newParent: UbbTagSegment): void {
// 文字标签无需关闭
if (segment.type === UbbSegmentType.Text) {
newParent._subSegments.push(segment.clone(newParent));
} else {
// 已经关闭的标签也无需关闭
const seg = segment as UbbTagSegment;
if (seg.isClosed) {
newParent._subSegments.push(segment.clone(newParent));
} else {
console.warn('标签 %s 没有正确关闭,已经被转换为纯文字。', seg.tagData.tagName);
// 未关闭标签,自己将被转换为纯文字
newParent._subSegments.push(new UbbTextSegment(seg.tagData.startTagString, segment.parent));
// 自己的下级将被递归强制关闭,并提升为和自己同级
for (const sub of seg._subSegments) {
UbbTagSegment.forceClose(sub, newParent);
}
}
}
}
/**
* 关闭该标签,并强制处理所有未关闭的下级标签。
*/
close() {
// 复制自己的下级并清空数组。
const subs = this._subSegments;
this._subSegments = [];
for (const item of subs) {
UbbTagSegment.forceClose(item, this);
}
// 设置关闭状态
this._isClosed = true;
}
clone(newParent: UbbTagSegment): UbbSegment {
const result = new UbbTagSegment(this._tagData, newParent);
result._content = this._content;
result._isClosed = this._isClosed;
for (const item of this._subSegments) {
result._subSegments.push(item.clone(result));
}
return result;
}
/**
* 获取标签的内部内容,不包括标签自身。
*/
getContentText() {
const subContents: string[] = [];
for (const subItem of this._subSegments) {
if (subItem.type === UbbSegmentType.Text) {
subContents.push((subItem as UbbTextSegment).text);
} else {
subContents.push((subItem as UbbTagSegment).getFullText());
}
}
return subContents.join('');
}
/**
* 获取标签的全部文字内容。
*/
getFullText(): string {
return this.tagData.startTagString + this.getContentText() + this.tagData.endTagString;
}
}
/**
* 定义 UBB 标签中包含的数据。
*/
export class UbbTagData {
/**
* 标签包含的所有原始文字。
*/
private _originalString: string;
/**
* 获取标签包含的原始文字。
* @returns {string} 标签包含的原始文字。
*/
get orignalString() { return this._originalString };
constructor(orignalString: string, parameters: UbbTagParameter[]) {
if (!parameters) {
throw new Error('参数不能为空。');
}
this._originalString = orignalString;
this._parameters = parameters;
// 填充命名参数
this._namedParameters = {};
for (let item of parameters) {
if (item.name) {
this._namedParameters[item.name] = item.value;
}
}
}
static parse(tagString: string): UbbTagData {
// 空字符串处理
if (!tagString) {
return null;
}
const tokens = getAllTokens(tagString);
// 无法分割标签
if (tokens.length === 0) {
return null;
}
const result = convertTokens(tokens);
return new UbbTagData(tagString, result);
/**
* 提取字符串中的所有符号。
*/
function getAllTokens(tokenString): Token[] {
let index = 0;
/**
* 从字符串中扫描获得下一个完整的语义符号。
* @returns {string} 下一个完整的语义符号。
*/
function scanToken(lastTokenType: TokenType): Token {
/**
* 从当前位置开始扫描字符串,直到找到对应的结束字符。
* @param quoteType 单引号或者双引号
* @returns {string} 从当前位置开始到相同字符结束的字符串。
*/
function scanQuoted(quoteType: string) {
// 开始字符串。
const quoteMark = tokenString[index];
let endMarkLocation = tokenString.indexOf(quoteType, index + 1);
// 找不到结束符号
if (endMarkLocation < 0) {
console.error('UBB: 解析标签字符串 %s 时无法找到位置 %d 处 %s 对应的结束字符串。', tokenString, index, quoteMark);
endMarkLocation = tokenString.length;
}
const start = index + 1;
index = endMarkLocation + 1;
return tokenString.substring(start, endMarkLocation);
}
while (true) {
// 超过范围。
if (index >= tokenString.length) {
return null;
}
const c = tokenString[index];
if (/\s/i.test(c)) { // 空白字符,直接忽略
index++;
continue;
}
else if (c === ',') { // 项目分隔符
index++;
return Token.itemSeperator;
} else if (c === '=') { // 名称值分隔符
index++;
return Token.nameValueSeperator;
} else if (c === '"' || c === '\'') { // 引号开始,找到结束为止
return Token.stringValue(scanQuoted(c));
} else {
const start = index;
// 根据最后一个标记的类型,本次标记的终止符会有所变化
const matchExp = lastTokenType === TokenType.ItemSeperator ? /[=,]/i : /,/i;
// 寻找下个分隔符
const nextSeperator = tokenString.substring(index + 1).match(matchExp);
if (nextSeperator) {
// 结束位置
const endMarkLocation = nextSeperator.index + index + 1;
index = endMarkLocation;
return Token.stringValue(tokenString.substring(start, endMarkLocation));
} else { // 找不到下一个符号,说明这是最后一个符号
index = tokenString.length;
return Token.stringValue(tokenString.substring(start));
}
}
}
}
const allTokens: Token[] = [];
let lastTokenType = TokenType.ItemSeperator;
while (true) {
const newToken = scanToken(lastTokenType);
if (newToken) {
allTokens.push(newToken);
lastTokenType = newToken.type;
} else {
break;
}
}
return allTokens;
}
/**
* 将令牌转换为参数集合。
* @param tokens 要转换的令牌的数组。
*/
function convertTokens(tokens: Token[]) {
const parameters: UbbTagParameter[] = [];
if (!tokens || tokens.length === 0) {
console.error('UBB: 无法将标签字符串 %s 解析为参数的集合。', tagString);
return parameters;
}
let lastName: string = null;
let lastValue: string = null;
let lastTokenType = TokenType.ItemSeperator;
for (let token of tokens) {
switch (token.type) {
case TokenType.ItemSeperator:
parameters.push(new UbbTagParameter(lastName, lastValue));
lastName = null;
lastValue = null;
lastTokenType = TokenType.ItemSeperator;
break;
case TokenType.NameValueSeperator:
if (lastTokenType !== TokenType.String) {
throw new Error('名称值分隔符只能出现在值之后。');
}
lastName = lastValue;
lastValue = null;
lastTokenType = TokenType.NameValueSeperator;
break;
default:
if (lastTokenType === TokenType.String) {
throw new Error('不能连续出现多个值。');
}
lastValue = token.value;
lastTokenType = TokenType.String;
break;
}
}
// 添加最后一个值
parameters.push(new UbbTagParameter(lastName, lastValue));
// 第一个项目需要特殊处理,默认是名称而非值
if (!parameters[0].name) {
parameters[0] = new UbbTagParameter(parameters[0].value, null);
}
return parameters;
}
}
/**
* 保存 UBB 所有参数数据的内部数组。
*/
private _parameters: UbbTagParameter[];
/**
* 保存所有命名参数的内部数据。
*/
private _namedParameters: {
[name: string]: string
};
/**
* 获取标签的名称。
* @returns {string} 标签的名称。
*/
get tagName() {
return this._parameters[0].name;
}
/**
* 获取标签的开始标记字符串。
* @returns {string} 标签的开始标记字符串。
*/
get startTagString(): string {
return `[${this.orignalString}]`;
}
/**
* 获取标签的结束标记字符串。
* @returns {string} 标签的结束标记字符串。
*/
get endTagString(): string {
return `[/${this.tagName}]`;
}
/**
* 获取标签的主要值,也即紧跟在标签名称和等号后的值。
* @returns {string} 标签的主要值。
*/
get mainValue() {
return this._parameters[0].value;
}
/**
* 获取给定参数的值。
* @param indexOrName 要获取的参数的索引或者名称。
* @returns {string} 给定位置参数的值。
*/
value(indexOrName: number | string): string {
if (typeof indexOrName === 'number') {
return this._parameters[indexOrName].value;
} else if (typeof indexOrName === 'string') {
return this._namedParameters[indexOrName];
} else {
throw new Error('参数必须是字符串或者数字。');
}
}
/**
* 获取给定参数的名称。
* @param index 要获取的参数的索引。
* @returns {string} 给定位置参数的名称。
*/
name(index: number) {
return this._parameters[index].name;
}
/**
* 获取当前标签中包含的参数的个数。
*/
get parameterCount(): number {
return this._parameters.length;
}
/**
* 获取给定的参数。
* @param index 要获取的参数的索引。
* @returns {UbbTagParameter} 给定位置的参数。
*/
parameter(index: number) {
return this._parameters[index];
}
}
/**
* 表示 UBB 标签中单个参数的内容。
*/
class UbbTagParameter {
/**
* 初始化一个对象的新实例。
* @param name 新参数的名称。
* @param value 新参数的值。
*/
constructor(name: string, value: string) {
this._name = name;
this._value = value;
}
/**
* 参数的名称。
*/
private _name: string;
/**
* 参数的值。
*/
private _value: string;
/**
* 获取参数的名称。如果参数没有名称,则该属性为 null。
*/
get name() {
return this._name;
}
/**
* 获取参数的值。如果该参数没有值,则该属性为 null。
*/
get value() {
return this._value;
}
}
/**
* 定义标签的处理模式。
*/
export enum UbbTagMode {
/**
* 标签内部允许其它 UBB 标签。处理程序将递归处理子内容,直到遇到该标签的结束标签。
*/
Recursive,
/**
* 标签内部只允许纯文字,处理程序将不在递归解析内容,而是直接寻找结束标签,并将中间的内容作为纯文字进行处理。
*/
Text,
/**
* 标签是不允许内容。在这种状况下,标签之后的内容将被视为和标签同级的新内容;一个例外情况是在标签标记后直接写入结束标记,如果遇到这种情况,则忽略结束标记。
*/
Empty
}
/**
* 表示 UBB 文字处理程序的基类。
*/
export abstract class UbbTextHandler {
/**
* 获取或设置该文字处理程序支持的内容。
*/
abstract get supportedContent(): string | RegExp;
/**
* 处理给定的内容并返回处理结果。
* @param match 通过对内容使用 supportedContent 属性进行正则匹配产生的匹配结果。
* @param context UBB 处理上下文对象。
* @returns {string} 处理后返回的结果。
*/
abstract exec(match: RegExpMatchArray, context: UbbCodeContext): ReactNode;
}
/**
* 定义 UBB 处理程序的基类。
*/
export abstract class UbbTagHandler {
/**
* 获取该处理程序支持处理的标签的名称。
* @returns {string | string[] | RegExp} 该处理程序支持处理的标签的名称,可以为字符串,字符串数组或者正则表达式。
*/
abstract get supportedTagNames(): string | string[] | RegExp;
/**
* 调用该处理程序处理给定的 UBB 内容。
* @param tagSegment UBB 标签相关内容。
* @param context UBB 处理上下文。
*/
abstract exec(tagSegment: UbbTagSegment, context: UbbCodeContext): ReactNode;
/**
* 通过对标签的分析,判断该标签的类型。
* @param tagData 标签中包含的内容。
*/
getTagMode(tagData: UbbTagData): UbbTagMode {
return UbbTagMode.Recursive;
}
/**
* 在解析完成处理标签内部的内容后,将标签本身作为文本处理。
* @param tagData 标签相关的数据。
* @param content 标签的内容。
*/
protected static renderTagAsString(tagData: UbbTagData, content: ReactNode): ReactNode {
return [
tagData.startTagString,
content,
tagData.endTagString
];
}
}
/**
* 定义基于文字的 UBB 标签处理程序的基类。
*/
export abstract class TextTagHandler extends UbbTagHandler {
exec(tagSegment: UbbTagSegment, context: UbbCodeContext) {
return this.execCore(tagSegment.getContentText(), tagSegment.tagData, context);
}
/**
* 递归处理的核心方法。
* @param innerContent 已经处理完毕的内部内容。
* @param tagData 标签相关的数据。
* @param context 处理上下文对象。
*/
protected abstract execCore(innerContent: string, tagData: UbbTagData, context: UbbCodeContext): ReactNode;
}
/**
* 定义递归处理内容的标签处理程序的基类。
*/
export abstract class RecursiveTagHandler extends UbbTagHandler {
exec(tagSegment: UbbTagSegment, context: UbbCodeContext) {
const result: ReactNode[] = [];
for (const subSeg of tagSegment.subSegments) {
result.push(context.engine.execSegment(subSeg, context));
}
return this.execCore(result, tagSegment.tagData, context);
}
/**
* 递归处理的核心方法。
* @param innerContent 已经处理完毕的内部内容。
* @param tagData 标签相关的数据。
* @param context 处理上下文对象。
*/
protected abstract execCore(innerContent: ReactNode, tagData: UbbTagData, context: UbbCodeContext): ReactNode;
}
/**
* 定义 UBB 处理程序列表。
*/
class UbbHandlerList {
/**
* 命名的内部标签处理器列表。
*/
private _namedTagHandlerList: {
[tagName: string]: UbbTagHandler;
} = {};
/**
* 未命名的内部标签处理程序列表。
*/
private _unnamedTagHanlderList: UbbTagHandler[] = [];
/**
* 文字处理标签程序列表。
*/
private _textHandlers: UbbTextHandler[] = [];
/**
* 获取文字处理程序列表。
* @returns {UbbTextHandler[]} 系统中注册的所有文字处理程序的集合。
*/
get textHandlers(): UbbTextHandler[] {
return this._textHandlers;
}
/**
* 获取给定标签名称的处理程序。
* @param supportedTagNames 标签名称。
* @returns {UbbTagHandler} 标签处理程序。
*/
getHandler(tagName: string): UbbTagHandler {
// 首先寻找命名的标签处理程序
const namedTagHandler = this._namedTagHandlerList[tagName];
// 找到
if (namedTagHandler) {
return namedTagHandler;
}
// 寻找未命名的标签处理程序
for (const handler of this._unnamedTagHanlderList) {
if ((handler.supportedTagNames as RegExp).test(tagName)) {
return handler;
}
}
// 找不到任何标签处理程序
return null;
}
/**
* 注册一个给定的标签处理程序。
* @param tagHandlerClass 处理程序对象的类型。
*/
register(tagHandlerClass: (new () => UbbTagHandler)) {
// ReSharper disable once InconsistentNaming
this.registerInstance(new tagHandlerClass());
}
/**
* 注册一个给定的处理程序实例。
* @param tagHandler 要注册的标签处理器。
*/
registerInstance(tagHandler: UbbTagHandler): void {
if (!tagHandler || !tagHandler.supportedTagNames) {
throw new Error('参数 tagHandler 无效,或者未提供正确的标签名称。');
}
if (typeof tagHandler.supportedTagNames === 'string') {
this.registerNamedCore([tagHandler.supportedTagNames], tagHandler);
} else if (tagHandler.supportedTagNames instanceof Array) {
this.registerNamedCore(tagHandler.supportedTagNames, tagHandler);
} else {
this.registerUnnamedCore(tagHandler);
}
}
/**
* 注册一个给定的文字处理程序。
* @param textHandlerClass 文字处理程序对象的类型。
*/
registerText(textHandlerClass: (new () => UbbTextHandler)) {
// ReSharper disable once InconsistentNaming
this.registerTextInstance(new textHandlerClass());
}
/**
* 注册一个文本处理程序实例。
* @param textHandler 要注册的文本处理程序。
*/
registerTextInstance(textHandler: UbbTextHandler) {
if (!textHandler) {
throw new Error('参数 textHandler 无效。');
}
this._textHandlers.push(textHandler);
}
/**
* 注册命名处理程序的核心方法。
* @param tagNames 处理程序关联的一个或多个标签名。
* @param tagHandler 处理程序对象。
*/
private registerNamedCore(tagNames: string[], tagHandler: UbbTagHandler): void {
for (const tagName of tagNames) {
if (tagName in this._namedTagHandlerList) {
console.error('标签 %s 的处理程序已经被注册。', tagName);
} else {
this._namedTagHandlerList[tagName] = tagHandler;
}
}
}
/**
* 注册未命名处理程序的核心方法。
* @param tagHandler 处理程序对象。
*/
private registerUnnamedCore(tagHandler: UbbTagHandler): void {
this._unnamedTagHanlderList.push(tagHandler);
}
}
/**
* 提供处理 UBB 程序的核心方法。
*/
export class UbbCodeEngine {
/**
* 获取该引擎中注册的处理程序。
*/
private _handlers = new UbbHandlerList();
/**
* 该引擎中注册的处理程序。
*/
get handlers() {
return this._handlers;
}
/**
* 引擎保存的上下文数据。
*/
private _data = new UbbCodeContextData();
/**
* 获取引擎保存的上下文数据。
* @returns {UbbCodeContextData} 引擎保存的上下文数据。
*/
get data(): UbbCodeContextData {
return this._data;
}
/**
* 获取给定标签名称的处理程序。
* @param supportedTagNames 给定的标签名称。
* @returns {UbbTagHandler} 给定标签名称的处理程序。
*/
getHandler(tagName: string): UbbTagHandler {
return this._handlers.getHandler(tagName);
}
/**
* 执行 UBB 解析的核心函数。
* @param content 要解析的内容。
* @param options 解析使用的相关选项。
* @returns {string} 解析后的 HTML 代码。
*/
exec(content: string, options: UbbCodeOptions): ReactNode {
const context = new UbbCodeContext(this, options);
return this.execCore(content, context);
}
/**
* 尝试找到关闭标记对应的开始标记,并关闭该标记。
* @param supportedTagNames 标记名称。
* @param parent 该标记的第一个上级。
* @returns {UbbTagSegment} 新的上级标签。
*/
private static tryHandleEndTag(tagName: string, parent: UbbTagSegment): UbbTagSegment {
let p = parent;
// 循环找到合适的上级,并关闭上级
while (p && p.tagData) {
if (p.tagData.tagName === tagName) {
p.close();
return p.parent;
}
p = p.parent;
}
// 没有找到任何上级
console.warn('UBB: 找不到结束标签 %s 的开始标签,该标签将被作为一般文字处理。', tagName);
parent.subSegments.push(new UbbTextSegment(`[/${tagName}]`, parent));
return parent;
}
/**
* 构建标签的核心方法。
* @param content 包含多个标签的字符串。
* @param parent 字符串的上级容器。
*/
private buildSegmentsCore(content: string, parent: UbbTagSegment) {
// const tagMatchRegExp = /([\s\S]*?)\[(.+?)]/gi;
const tagMatchRegExp = {
lastIndex: 0,
exec(content: string) {
const i1 = this.lastIndex
const i2 = content.indexOf('[', i1)
if (i2 === -1)
return null
const i3 = content.indexOf(']', i2)
if (i3 === -1)
return null
this.lastIndex = i3 + 1
return [content.slice(i1, i2), content.slice(i2 + 1, i3)]
}
}
while (true) {
const startIndex = tagMatchRegExp.lastIndex;
const tagMatch = tagMatchRegExp.exec(content);
// 未找到标记,则这是最后一个标签。
if (!tagMatch) {
// 提取最后一段内容,如果找到,附加到最后
const remainContent = content.substring(startIndex);
if (remainContent) {
parent.subSegments.push(new UbbTextSegment(remainContent, parent));
}
return;
}
const [beforeText, tagString] = tagMatch;
// 添加前面的文字。
if (beforeText) {
parent.subSegments.push(new UbbTextSegment(beforeText, parent));
}
// 检测是否是结束标记
const endTagMatch = tagString.match(/^\/(.+)$/i);
if (endTagMatch) {
const endTagName = endTagMatch[1];
parent = UbbCodeEngine.tryHandleEndTag(endTagName, parent);
} else {
try {
// 提取新的标签数据
const tagData = UbbTagData.parse(tagString);
// 获得处理程序
const handler = this._handlers.getHandler(tagData.tagName);
// 没有处理程序,输出警告
if (!handler) {
console.warn('UBB: 标签字符串 %s 中给定的标签名 %s 没有有效的处理程序,将被视为一般文字', tagString, tagData.tagName);
parent.subSegments.push(new UbbTextSegment(tagData.startTagString, parent));
continue;
}
// 获取标签类型。
const tagMode = handler.getTagMode(tagData);
switch (tagMode) {
// 递归处理
case UbbTagMode.Recursive:
const newTag = new UbbTagSegment(tagData, parent);
parent.subSegments.push(newTag);
parent = newTag;
break;
// 文本模式下,直接寻找结束标签
case UbbTagMode.Text:
const endTagMatch = content.indexOf(tagData.endTagString, tagMatchRegExp.lastIndex);
// 没找到结束标签
if (endTagMatch === -1) {
console.warn('UBB: 找不到标签字符串 %s 对应的结束标签,该内容将被视为一般文字。', tagData.startTagString);
parent.subSegments.push(new UbbTextSegment(tagData.startTagString, parent));
} else {
// 直接创建新标签及其子标签,忽略中间内容
const innerContent = content.substring(tagMatchRegExp.lastIndex, endTagMatch);
const newTag = new UbbTagSegment(tagData, parent);
parent.subSegments.push(newTag);
parent = newTag;
const subTag = new UbbTextSegment(innerContent, newTag);
newTag.subSegments.push(subTag);
newTag.close();
// 让下次标签搜索直接从之后开始
tagMatchRegExp.lastIndex = endTagMatch + tagData.endTagString.length;
}
break;
// 单模式标签
case UbbTagMode.Empty:
// 创建新标签并直接结束
const newEmptyTag = new UbbTagSegment(tagData, parent);
parent.subSegments.push(newEmptyTag);
newEmptyTag.close();
// 如果紧跟着结束标签,则忽略结束标签
if (content.startsWith(tagData.endTagString, tagMatchRegExp.lastIndex)) {
tagMatchRegExp.lastIndex += tagData.endTagString.length;
}
break;
default:
throw new Error(`UBB: 标签 ${tagData.tagName} 的处理程序发生错误`);
}
} catch (error) {
// 提取数据失败,则视为没有匹配
console.warn('UBB: 标签字符串 %s 解析失败,将被视为普通文字。', tagString);
parent.subSegments.push(new UbbTextSegment(`[${tagString}]`, parent));
}
}
}
}
/**
* 执行 UBB 处理的核心函数。
* @param content 要处理的内容。
* @param context UBB 处理上下文。
* @returns {JSX.Element} 处理完成的 HTML 内容。
*/
private execCore(content: string, context: UbbCodeContext): ReactNode {
const root = new UbbTagSegment(null, null);
this.buildSegmentsCore(content, root);
root.close();
const result: ReactNode[] = [];
for (const item of root.subSegments) {
result.push(this.execSegment(item, context));
}
return result;
}
/**
* 执行文本替换的核心方法。
* @param text 文本内容。
* @param context UBB 上下文对象。
*/
private execTextCore(text: string, context: UbbCodeContext): ReactNode {
for (const textHandler of this.handlers.textHandlers) {
// 尝试匹配内容
const matchResult = text.match(textHandler.supportedContent);
// 如果未匹配到内容,返回下一个
if (!matchResult) {
continue;
}
// console.log(matchResult);
const before = text.substr(0, matchResult.index);
const after = text.substr(matchResult.index + matchResult[0].length);
const result: ReactNode[] = [];
if (before) {
result.push(this.execTextCore(before, context));
}
result.push(textHandler.exec(matchResult, context));
if (after) {
result.push(this.execTextCore(after, context));
}
return result;
}
// 未找到任何处理程序
return text;
}
/**
* 对给定的 UBB 文本执行文本替换。
* @param text 要替换的内容。
* @param context 替换后的结果。
*/
execText(text: string, context: UbbCodeContext): ReactNode {
return this.execTextCore(text, context);
}
execSegment(segment: UbbSegment, context: UbbCodeContext): ReactNode {
if (segment.type === UbbSegmentType.Text) {
const text = (segment as UbbTextSegment).text;
return this.execText(text, context);
} else {
const tag = segment as UbbTagSegment;
const handler = this.getHandler(tag.tagData.tagName);
if (!handler) {
console.warn('没有找到标签 %s 的处理程序,将被视为一般文字。', tag.tagData.tagName);
return tag.getFullText();
}
return handler.exec(tag, context);
}
}
} | the_stack |
import { ServiceClientOptions } from "@azure/ms-rest-js";
import * as msRest from "@azure/ms-rest-js";
/**
* An interface representing LanguagesResultTranslationLanguageCode.
*/
export interface LanguagesResultTranslationLanguageCode {
name?: string;
nativeName?: string;
dir?: string;
}
/**
* An interface representing LanguagesResultTranslation.
*/
export interface LanguagesResultTranslation {
languageCode?: LanguagesResultTranslationLanguageCode;
}
/**
* An interface representing LanguagesResultTransliterationLanguageCodeScriptsItemToScriptsItem.
*/
export interface LanguagesResultTransliterationLanguageCodeScriptsItemToScriptsItem {
code?: string;
name?: string;
nativeName?: string;
dir?: string;
}
/**
* An interface representing LanguagesResultTransliterationLanguageCodeScriptsItem.
*/
export interface LanguagesResultTransliterationLanguageCodeScriptsItem {
code?: string;
name?: string;
nativeName?: string;
dir?: string;
toScripts?: LanguagesResultTransliterationLanguageCodeScriptsItemToScriptsItem[];
}
/**
* An interface representing LanguagesResultTransliterationLanguageCode.
*/
export interface LanguagesResultTransliterationLanguageCode {
name?: string;
nativeName?: string;
scripts?: LanguagesResultTransliterationLanguageCodeScriptsItem[];
}
/**
* An interface representing LanguagesResultTransliteration.
*/
export interface LanguagesResultTransliteration {
languageCode?: LanguagesResultTransliterationLanguageCode;
}
/**
* An interface representing LanguagesResultDictionaryLanguageCodeTranslationsItem.
*/
export interface LanguagesResultDictionaryLanguageCodeTranslationsItem {
name?: string;
nativeName?: string;
dir?: string;
code?: string;
}
/**
* An interface representing LanguagesResultDictionaryLanguageCode.
*/
export interface LanguagesResultDictionaryLanguageCode {
name?: string;
nativeName?: string;
dir?: string;
translations?: LanguagesResultDictionaryLanguageCodeTranslationsItem[];
}
/**
* An interface representing LanguagesResultDictionary.
*/
export interface LanguagesResultDictionary {
languageCode?: LanguagesResultDictionaryLanguageCode;
}
/**
* Example of a successful languages request
*/
export interface LanguagesResult {
translation?: LanguagesResultTranslation;
transliteration?: LanguagesResultTransliteration;
dictionary?: LanguagesResultDictionary;
}
/**
* An interface representing DictionaryExampleResultItemExamplesItem.
*/
export interface DictionaryExampleResultItemExamplesItem {
sourcePrefix?: string;
sourceTerm?: string;
sourceSuffix?: string;
targetPrefix?: string;
targetTerm?: string;
targetSuffix?: string;
}
/**
* An interface representing DictionaryExampleResultItem.
*/
export interface DictionaryExampleResultItem {
normalizedSource?: string;
normalizedTarget?: string;
examples?: DictionaryExampleResultItemExamplesItem[];
}
/**
* An interface representing DictionaryLookupResultItemTranslationsItemBackTranslationsItem.
*/
export interface DictionaryLookupResultItemTranslationsItemBackTranslationsItem {
normalizedText?: string;
displayText?: string;
numExamples?: number;
frequencyCount?: number;
}
/**
* An interface representing DictionaryLookupResultItemTranslationsItem.
*/
export interface DictionaryLookupResultItemTranslationsItem {
normalizedTarget?: string;
displayTarget?: string;
posTag?: string;
confidence?: number;
prefixWord?: string;
backTranslations?: DictionaryLookupResultItemTranslationsItemBackTranslationsItem[];
}
/**
* An interface representing DictionaryLookupResultItem.
*/
export interface DictionaryLookupResultItem {
normalizedSource?: string;
displaySource?: string;
translations?: DictionaryLookupResultItemTranslationsItem[];
}
/**
* An interface representing TranslateResultItemTranslationItem.
*/
export interface TranslateResultItemTranslationItem {
text?: string;
to?: string;
}
/**
* An interface representing TranslateResultItem.
*/
export interface TranslateResultItem {
translation?: TranslateResultItemTranslationItem[];
}
/**
* An interface representing TranslateResultAllItemDetectedLanguage.
*/
export interface TranslateResultAllItemDetectedLanguage {
language?: string;
score?: number;
}
/**
* An interface representing TranslateResultAllItemTranslationsItemTransliteration.
*/
export interface TranslateResultAllItemTranslationsItemTransliteration {
text?: string;
script?: string;
}
/**
* An interface representing TranslateResultAllItemTranslationsItemAlignment.
*/
export interface TranslateResultAllItemTranslationsItemAlignment {
proj?: string;
}
/**
* An interface representing TranslateResultAllItemTranslationsItemSentLenSrcSentLenItem.
*/
export interface TranslateResultAllItemTranslationsItemSentLenSrcSentLenItem {
integer?: number;
}
/**
* An interface representing TranslateResultAllItemTranslationsItemSentLenTransSentLenItem.
*/
export interface TranslateResultAllItemTranslationsItemSentLenTransSentLenItem {
integer?: number;
}
/**
* An interface representing TranslateResultAllItemTranslationsItemSentLen.
*/
export interface TranslateResultAllItemTranslationsItemSentLen {
srcSentLen?: TranslateResultAllItemTranslationsItemSentLenSrcSentLenItem[];
transSentLen?: TranslateResultAllItemTranslationsItemSentLenTransSentLenItem[];
}
/**
* An interface representing TranslateResultAllItemTranslationsItem.
*/
export interface TranslateResultAllItemTranslationsItem {
text?: string;
transliteration?: TranslateResultAllItemTranslationsItemTransliteration;
to?: string;
alignment?: TranslateResultAllItemTranslationsItemAlignment;
sentLen?: TranslateResultAllItemTranslationsItemSentLen;
}
/**
* An interface representing TranslateResultAllItem.
*/
export interface TranslateResultAllItem {
detectedLanguage?: TranslateResultAllItemDetectedLanguage;
translations?: TranslateResultAllItemTranslationsItem[];
}
/**
* An interface representing BreakSentenceResultItem.
*/
export interface BreakSentenceResultItem {
sentLen?: number[];
}
/**
* An interface representing TransliterateResultItem.
*/
export interface TransliterateResultItem {
text?: string;
script?: string;
}
/**
* An interface representing DetectResultItem.
*/
export interface DetectResultItem {
text?: string;
}
/**
* Text needed for break sentence request
*/
export interface BreakSentenceTextInput {
text?: string;
}
/**
* An interface representing ErrorMessageError.
*/
export interface ErrorMessageError {
code?: string;
message?: string;
}
/**
* An interface representing ErrorMessage.
*/
export interface ErrorMessage {
error?: ErrorMessageError;
}
/**
* Text needed for detect request
*/
export interface DetectTextInput {
text?: string;
}
/**
* Text needed for a dictionary lookup request
*/
export interface DictionaryLookupTextInput {
text?: string;
}
/**
* Text needed for a dictionary example request
*/
export interface DictionaryExampleTextInput {
text?: string;
translation?: string;
}
/**
* Text needed for a translate request
*/
export interface TranslateTextInput {
text?: string;
}
/**
* Text needed for a transliterate request
*/
export interface TransliterateTextInput {
text?: string;
}
/**
* An interface representing TranslatorTextClientOptions.
*/
export interface TranslatorTextClientOptions extends ServiceClientOptions {
/**
* Version of the API requested by the client. Value must be **3.0**. Default value: '3.0'.
*/
apiVersion?: string;
}
/**
* Optional Parameters.
*/
export interface TranslatorBreakSentenceOptionalParams extends msRest.RequestOptionsBase {
/**
* Language tag of the language of the input text. If not specified, Translator will apply
* automatic language detection.
*/
language?: string;
/**
* Script identifier of the script used by the input text. If a script is not specified, the
* default script of the language will be assumed.
*/
script?: string;
/**
* A client-generated GUID to uniquely identify the request. Note that you can omit this header
* if you include the trace ID in the query string using a query parameter named ClientTraceId.
*/
xClientTraceId?: string;
}
/**
* Optional Parameters.
*/
export interface TranslatorDetectOptionalParams extends msRest.RequestOptionsBase {
/**
* A client-generated GUID to uniquely identify the request. Note that you can omit this header
* if you include the trace ID in the query string using a query parameter named ClientTraceId.
*/
xClientTraceId?: string;
}
/**
* Optional Parameters.
*/
export interface TranslatorDictionaryLookupOptionalParams extends msRest.RequestOptionsBase {
/**
* A client-generated GUID to uniquely identify the request. Note that you can omit this header
* if you include the trace ID in the query string using a query parameter named ClientTraceId.
*/
xClientTraceId?: string;
}
/**
* Optional Parameters.
*/
export interface TranslatorDictionaryExamplesOptionalParams extends msRest.RequestOptionsBase {
/**
* A client-generated GUID to uniquely identify the request. Note that you can omit this header
* if you include the trace ID in the query string using a query parameter named ClientTraceId.
*/
xClientTraceId?: string;
}
/**
* Optional Parameters.
*/
export interface TranslatorLanguagesOptionalParams extends msRest.RequestOptionsBase {
/**
* A comma-separated list of names defining the group of languages to return. Allowed group names
* are- `translation`, `transliteration` and `dictionary`. If no scope is given, then all groups
* are returned, which is equivalent to passing `scope=translation,transliteration,dictionary`.
* To decide which set of supported languages is appropriate for your scenario, see the
* description of the response object.
*/
scope?: string[];
/**
* The language to use for user interface strings. Some of the fields in the response are names
* of languages or names of regions. Use this parameter to define the language in which these
* names are returned. The language is specified by providing a well-formed BCP 47 language tag.
* For instance, use the value `fr` to request names in French or use the value `zh-Hant` to
* request names in Chinese Traditional. Names are provided in the English language when a target
* language is not specified or when localization is not available.
*/
acceptLanguage?: string;
/**
* A client-generated GUID to uniquely identify the request. Note that you can omit this header
* if you include the trace ID in the query string using a query parameter named ClientTraceId.
*/
xClientTraceId?: string;
}
/**
* Optional Parameters.
*/
export interface TranslatorTranslateOptionalParams extends msRest.RequestOptionsBase {
/**
* Specifies the language of the input text. Find which languages are available to translate from
* by using the languages method. If the `from` parameter is not specified, automatic language
* detection is applied to determine the source language.
*/
from?: string;
/**
* Defines whether the text being translated is plain text or HTML text. Any HTML needs to be a
* well-formed, complete HTML element. Possible values are `plain` (default) or `html`
* . Possible values include: 'plain', 'html'
*/
textType?: TextType;
/**
* A string specifying the category (domain) of the translation. This parameter retrieves
* translations from a customized system built with Custom Translator. Default value is
* `general`.
*/
category?: string;
/**
* Specifies how profanities should be treated in translations. Possible values are: `NoAction`
* (default), `Marked` or `Deleted`.
* ### Handling Profanity
* Normally the Translator service will retain profanity that is present in the source in the
* translation. The degree of profanity and the context that makes words profane differ between
* cultures, and as a result the degree of profanity in the target language may be amplified or
* reduced.
*
* If you want to avoid getting profanity in the translation, regardless of the presence of
* profanity in the source text, you can use the profanity filtering option. The option allows
* you to choose whether you want to see profanity deleted, whether you want to mark profanities
* with appropriate tags (giving you the option to add your own post-processing), or you want no
* action taken. The accepted values of `ProfanityAction` are `Deleted`, `Marked` and `NoAction`
* (default).
*
* | ProfanityAction | Action
* |
* | ---------- | ----------
* |
* | `NoAction` | This is the default behavior. Profanity will pass from source to target.
* |
* | | Example Source (Japanese)- 彼はジャッカスです。 |
* | | Example Translation (English)- He is a jackass.
* |
* | |
* |
* | `Deleted` | Profane words will be removed from the output without replacement.
* |
* | | Example Source (Japanese)- 彼はジャッカスです。 |
* | | Example Translation (English)- He is a.
* |
* | `Marked` | Profane words are replaced by a marker in the output. The marker depends
* on the `ProfanityMarker` parameter.
* | | For `ProfanityMarker=Asterisk`, profane words are replaced with `***`
* |
* | | Example Source (Japanese)- 彼はジャッカスです。 |
* | | Example Translation (English)- He is a ***.
* |
* | | For `ProfanityMarker=Tag`, profane words are surrounded by XML tags
* <profanity> and </profanity>
* | | Example Source (Japanese)- 彼はジャッカスです。 |
* | | Example Translation (English)- He is a <profanity>jackass</profanity>.
* . Possible values include: 'NoAction', 'Marked', 'Deleted'
*/
profanityAction?: ProfanityAction;
/**
* Specifies how profanities should be marked in translations. Possible values are- `Asterisk`
* (default) or `Tag`.
*/
profanityMarker?: string;
/**
* Specifies whether to include alignment projection from source text to translated text.
* Possible values are- `true` or `false` (default).
*/
includeAlignment?: boolean;
/**
* Specifies whether to include sentence boundaries for the input text and the translated text.
* Possible values are- `true` or `false` (default).
*/
includeSentenceLength?: boolean;
/**
* Specifies a fallback language if the language of the input text can't be identified. Language
* auto-detection is applied when the `from` parameter is omitted. If detection fails, the
* `suggestedFrom` language will be assumed.
*/
suggestedFrom?: string;
/**
* Specifies the script of the input text. Supported scripts are available from the languages
* method
*/
fromScript?: string;
/**
* Specifies the script of the translated text. Supported scripts are available from the
* languages method
*/
toScript?: string[];
/**
* A client-generated GUID to uniquely identify the request. Note that you can omit this header
* if you include the trace ID in the query string using a query parameter named ClientTraceId.
*/
xClientTraceId?: string;
}
/**
* Optional Parameters.
*/
export interface TranslatorTransliterateOptionalParams extends msRest.RequestOptionsBase {
/**
* A client-generated GUID to uniquely identify the request. Note that you can omit this header
* if you include the trace ID in the query string using a query parameter named ClientTraceId.
*/
xClientTraceId?: string;
}
/**
* Defines values for TextType.
* Possible values include: 'plain', 'html'
* @readonly
* @enum {string}
*/
export type TextType = 'plain' | 'html';
/**
* Defines values for ProfanityAction.
* Possible values include: 'NoAction', 'Marked', 'Deleted'
* @readonly
* @enum {string}
*/
export type ProfanityAction = 'NoAction' | 'Marked' | 'Deleted';
/**
* Contains response data for the breakSentence operation.
*/
export type TranslatorBreakSentenceResponse = Array<BreakSentenceResultItem> & {
/**
* 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: BreakSentenceResultItem[];
};
};
/**
* Contains response data for the detect operation.
*/
export type TranslatorDetectResponse = Array<DetectResultItem> & {
/**
* 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: DetectResultItem[];
};
};
/**
* Contains response data for the dictionaryLookup operation.
*/
export type TranslatorDictionaryLookupResponse = Array<DictionaryLookupResultItem> & {
/**
* 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: DictionaryLookupResultItem[];
};
};
/**
* Contains response data for the dictionaryExamples operation.
*/
export type TranslatorDictionaryExamplesResponse = Array<DictionaryExampleResultItem> & {
/**
* 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: DictionaryExampleResultItem[];
};
};
/**
* Contains response data for the languages operation.
*/
export type TranslatorLanguagesResponse = LanguagesResult & {
/**
* 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: LanguagesResult;
};
};
/**
* Contains response data for the translate operation.
*/
export type TranslatorTranslateResponse = Array<TranslateResultAllItem> & {
/**
* 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: TranslateResultAllItem[];
};
};
/**
* Contains response data for the transliterate operation.
*/
export type TranslatorTransliterateResponse = Array<TransliterateResultItem> & {
/**
* 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: TransliterateResultItem[];
};
}; | the_stack |
import * as React from "react";
import styles from "./StaffDirectory.module.scss";
import { IStaffDirectoryProps } from "./IStaffDirectoryProps";
import { IStaffDirectoryState } from "./IStaffDirectoryState";
import { WebPartTitle } from "@pnp/spfx-controls-react";
import {
IStackTokens,
mergeStyleSets,
IBasePickerStyles,
IPersonaProps,
Spinner,
SpinnerSize,
MessageBar,
MessageBarType,
ValidationState,
Stack,
FontIcon,
NormalPeoplePicker,
ImageFit,
Image,
Text,
Link,
ILinkStyles,
LinkBase,
mergeStyles,
} from "office-ui-fabric-react";
import { IAppContext } from "../../common/IAppContext";
import {
useGetUserProperties, manpingUserProperties
} from "../../hooks/useGetUserProperties"
import { IUserExtended } from "../../entites/IUserExtended";
import { AppContext, currentSiteTheme } from "../../common/AppContext";
import { UserCard } from "../UserCard/UserCard";
import { toInteger } from "lodash";
import strings from "StaffDirectoryWebPartStrings";
import { SearchResults } from "@pnp/sp";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const imageNoData:never = require('../../../assets/Nodatarafiki.svg');
const stackTokens: IStackTokens = {
childrenGap: 10,
};
// Component Styles
const suggestionProps = {
suggestionsHeaderText: "Suggested People",
mostRecentlyUsedHeaderText: "Suggested Contacts",
noResultsFoundText: "No results found",
loadingText: "Loading",
showRemoveButtons: false,
suggestionsAvailableAlertText: "People Picker Suggestions available",
suggestionsContainerAriaLabel: "Suggested contacts",
};
const getTotalPages = (totalRows:number, pageSize:number):number => {
let _totalPages: number =
totalRows / pageSize;
const _modulus: number = totalRows % pageSize;
_totalPages = _modulus > 0 ? toInteger(_totalPages) + 1 : toInteger(_totalPages);
return _totalPages;
}
export const StaffDirectory: React.FunctionComponent<IStaffDirectoryProps> = (
props: IStaffDirectoryProps
) => {
const { showBox, context } = props;
const { getUsers} = useGetUserProperties(context);
console.log( props.themeVariant);
console.log(currentSiteTheme);
const styleClasses = mergeStyleSets({
webPartTitle: mergeStyles({
marginBottom: 20,
}),
separator:mergeStyles( {
paddingLeft: 30,
paddingRight: 30,
margin: 20,
borderBottomStyle: "solid",
borderWidth: 1,
borderBottomColor: props.themeVariant?.themeLighter
}),
styleIcon:mergeStyles( {
maxWidth: 44,
minWidth: 44,
minHeight: 30,
height: 30,
borderColor: props.themeVariant?.themePrimary ,
borderRightWidth: 0,
borderRightStyle: "none",
borderLeftWidth: 1,
borderLeftStyle: "solid",
borderTopWidth: 1,
borderTopStyle: "solid",
borderBottomWidth: 1,
borderBottomStyle: "solid",
display: "flex",
alignItems: "center",
justifyContent: "center",
}),
listContainer: mergeStyles( {
maxWidth: "100%",
overflowY: "auto",
marginTop: 20,
padding: 10,
boxShadow: showBox
? "rgb(0 0 0 / 20%) 0px 0px 2px 0px, rgb(0 0 0 / 10%) 0px 0px 10px 0px"
: "",
}),
});
const pickerStyles: Partial<IBasePickerStyles> = {
root: {
width: "100%",
maxHeight: 32,
minHeight: 32,
borderColor: props.themeVariant?.themePrimary
},
itemsWrapper: {
borderColor: props.themeVariant?.themePrimary ,
},
text: {
borderLeftWidth: 0,
minHeight: 32,
borderColor: props.themeVariant?.themePrimary,
selectors: {
":focus": {
borderColor: props.themeVariant?.themePrimary
},
":hover": {
borderColor: props.themeVariant?.themePrimary
},
"::after": {
borderColor: props.themeVariant?.themePrimary,
borderWidth: 1,
borderLeftWidth: 0,
},
},
},
};
const nextPageStyle: ILinkStyles = {
root: {
fontWeight: 600,
fontSize: props.themeVariant?.["ms-font-mediumPlus-fontSize"],
selectors: { ":hover": { textDecoration: "underline" } },
},
};
const _appContext = React.useRef<IAppContext>({} as IAppContext);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _currentUser= React.useRef<any>();
const _currentUserDepartment = React.useRef<string>('');
const [state, setState] = React.useState<IStaffDirectoryState>({
listUsers: [],
hasError: false,
errorMessage: "",
isLoading: true,
isLoadingNextPage: false,
currentPage: 1,
totalPages: 0,
});
const picker = React.useRef(null);
_currentUser.current = props.context.pageContext.user;
const _currentuserProperties = React.useRef<IUserExtended[]>([]);
const _spResults = React.useRef<SearchResults>();
React.useEffect(() => {
(async () => {
try {
_currentUser.current = props.context.pageContext.user;
_appContext.current.currentUser = _currentUser.current ;
_appContext.current.themeVariant = props.themeVariant
const _usersResults = await getUsers(
`WorkEmail: ${_currentUser.current.email}`,
);
setState({
...state,
isLoading: true,
});
_currentuserProperties.current = await manpingUserProperties(_usersResults);
_currentUserDepartment.current = _currentuserProperties?.current[0]?.department;
let _searchDepartment = '';
if (_currentUserDepartment.current){
_searchDepartment = `Department:${_currentUserDepartment.current}`
}else{
_searchDepartment = '*';
}
_spResults.current = await getUsers(
_searchDepartment,
props.pageSize
);
const _totalPages: number = getTotalPages(_spResults.current.TotalRows,props.pageSize );
setState({
...state,
listUsers: await manpingUserProperties(_spResults.current),
currentPage: 1,
totalPages: _totalPages,
isLoading: false,
});
// Pooling status each x min ( value define as property in webpart)
} catch (error) {
setState({
...state,
errorMessage: error.message
? error.message
: " Error searching users, please try later or contact support.",
hasError: true,
isLoading: false,
});
console.log(error);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props]);
// on Filter changed
const _onFilterChanged = async (
filterText: string,
currentPersonas: IPersonaProps[],
): Promise<IPersonaProps[]> => {
let filteredPersonas: IPersonaProps[] = [];
if (filterText.trim().length > 0) {
try {
const _usersResults = await getUsers(`PreferredName: ${filterText}`);
const _users = await manpingUserProperties(_usersResults);
for (const _user of _users) {
filteredPersonas.push({
text: _user.displayName,
imageUrl: _user.pictureBase64,
secondaryText: _user.department,
});
}
filteredPersonas = removeDuplicates(filteredPersonas, currentPersonas);
return filteredPersonas;
} catch (error) {
console.log(error);
return [];
}
} else {
return [];
}
};
// On Picker Changed
const _onPickerChange = async (items: IPersonaProps[]) => {
if (!(items.length === 0)) return;
try {
setState({
...state,
isLoading: true,
});
_spResults.current = await getUsers(
_currentUserDepartment.current ?? '*',
props.pageSize
);
const _totalPages: number = getTotalPages(_spResults.current.TotalRows,props.pageSize );
setState({
...state,
listUsers: await manpingUserProperties(_spResults.current),
totalPages: _totalPages,
currentPage: 1
});
} catch (error) {
console.log(error);
setState({
...state,
listUsers: [],
hasError: true,
errorMessage: error.message
? error.message
: " Error searching users, please try later or contact support.",
});
}
};
const _onNextPage = async (
event: React.MouseEvent<
HTMLElement | HTMLAnchorElement | HTMLButtonElement | LinkBase,
MouseEvent
>
) => {
event.preventDefault();
const { listUsers} = state;
setState({
...state,
isLoadingNextPage: true,
});
try {
const { currentPage } = state;
console.log('page',_spResults.current);
_spResults.current = await _spResults.current.getPage(currentPage +1 )
const _newlistUsers = listUsers.concat(await manpingUserProperties(_spResults.current));
setState({
...state,
listUsers: _newlistUsers,
isLoadingNextPage: false,
currentPage: currentPage + 1
});
} catch (error) {
console.log(error);
setState({
...state,
listUsers: [],
hasError: true,
isLoadingNextPage: false,
errorMessage: error.message
? error.message
: strings.ErrorMessage
});
}
};
// Render compoent
// Has Error
if (state.hasError) {
return (
<MessageBar messageBarType={MessageBarType.error}>{state.errorMessage}</MessageBar>
);
}
return (
<AppContext.Provider value={_appContext.current}>
<WebPartTitle
displayMode={props.displayMode}
title={props.title}
updateProperty={props.updateProperty}
className={styleClasses.webPartTitle}
/>
<Stack tokens={stackTokens} style={{ width: "100%" }}>
<Stack
style={{ width: "100%" }}
horizontal={true}
verticalAlign="center"
tokens={{ childrenGap: 0 }}
>
<div className={styleClasses.styleIcon}>
<FontIcon
iconName="Search"
style={{
verticalAlign: "center",
fontSize: props.themeVariant?.["ms-font-mediumPlus-fontSize"],
color: props.themeVariant?.themePrimary ,
}}
/>
</div>
<NormalPeoplePicker
itemLimit={1}
onResolveSuggestions={_onFilterChanged}
getTextFromItem={getTextFromItem}
pickerSuggestionsProps={suggestionProps}
className="ms-PeoplePicker"
key="normal"
onValidateInput={validateInput}
onChange={_onPickerChange}
styles={pickerStyles}
componentRef={picker}
resolveDelay={300}
disabled={state.isLoading}
onItemSelected={async (selectedItem: IPersonaProps) => {
_spResults.current = await getUsers(
`PreferredName:${selectedItem.text.trim()}`,
props.pageSize
);
const _totalPages: number = getTotalPages(_spResults.current.TotalRows,props.pageSize );
setState({
...state,
listUsers: await manpingUserProperties(_spResults.current),
isLoading: false,
totalPages: _totalPages,
currentPage: 1
});
return selectedItem;
}}
/>
</Stack>
{state.isLoading ? (
<Spinner size={SpinnerSize.medium}></Spinner>
) : (
<div
className={`${styleClasses.listContainer} ${styles.hideScrollBar}`}
style={{ maxHeight: props.maxHeight }}
>
{state.listUsers.length > 0 ? (
state.listUsers.map((user) => {
return (
<>
<UserCard
userData={user}
userAttributes={props.userAttributes}
updateUsersPresence={undefined}
></UserCard>
<div className={styleClasses.separator}></div>
</>
);
})
) : (
<>
<Stack
horizontalAlign="center"
verticalAlign="center"
style={{ marginBottom: 25 }}
>
<Image
src={imageNoData}
imageFit={ImageFit.cover}
width={250}
height={300}
></Image>
<Text variant="large">No colleagues found </Text>
</Stack>
</>
)}
{state.totalPages > 1 && state.currentPage < state.totalPages && (
<Stack
horizontal
horizontalAlign="end"
verticalAlign="center"
style={{
marginTop: 10,
marginRight: 20,
marginBottom: 20,
}}
>
<Link
styles={nextPageStyle}
disabled={state.isLoadingNextPage}
onClick={_onNextPage}
>
Next Page
</Link>
{state.isLoadingNextPage && (
<Spinner
style={{ marginLeft: 5 }}
size={SpinnerSize.small}
></Spinner>
)}
</Stack>
)}
</div>
)}
</Stack>
</AppContext.Provider>
);
};
// Get text from Persona
const getTextFromItem = (persona) => {
return persona.text;
};
// Remove dumplicate Items
const removeDuplicates = (personas, possibleDupes) => {
return personas.filter((persona) => {
return !listContainsPersona(persona, possibleDupes);
});
};
// Check if selecte list has a persona selected
const listContainsPersona = (persona, personas) => {
if (!personas || !personas.length || personas.length === 0) {
return false;
}
return (
personas.filter((item) => {
return item.text === persona.text;
}).length > 0
);
};
// Validate Input Function
const validateInput = (input) => {
if (input.trim().length > 1) {
return ValidationState.valid;
} else {
return ValidationState.invalid;
}
}; | the_stack |
import { bootstrap } from 'aurelia-bootstrapper';
import { PLATFORM } from 'aurelia-pal';
import { ComponentTester, StageComponent } from 'aurelia-testing';
import { VirtualRepeat } from '../src/virtual-repeat';
import { ITestAppInterface } from './interfaces';
import './setup';
import { AsyncQueue, createAssertionQueue, waitForNextFrame } from './utilities';
import { CloneArrayValueConverter, IdentityValueConverter } from './value-converters';
import { eachCartesianJoin, eachCartesianJoinAsync } from './lib';
import { calcMinViewsRequired as calcMinViewsRequired } from '../src/utilities';
PLATFORM.moduleName('src/virtual-repeat');
PLATFORM.moduleName('test/noop-value-converter');
PLATFORM.moduleName('src/infinite-scroll-next');
describe('vr-integration.scrolling.spec.ts', () => {
const itemHeight = 100;
const queue: AsyncQueue = createAssertionQueue();
let component: ComponentTester<VirtualRepeat>;
// let viewModel: any;
let items: string[];
let view: string;
let resources: any[];
beforeEach(() => {
component = undefined;
items = Array.from({ length: 100 }, (_: any, idx: number) => 'item' + idx);
// viewModel = { items: items };
resources = [
'src/virtual-repeat',
'test/noop-value-converter',
];
});
afterEach(() => {
try {
if (component) {
component.dispose();
}
} catch (ex) {
console.log('Error disposing component');
console.error(ex);
}
});
// Note that any test related to table, ignore border spacing as it's not easy to calculate in test environment
// todo: have tests for margin / border spacing
// describe('<tr virtual-repeat.for>', () => {
// beforeEach(() => {
// view =
// `<div style="height: 500px; overflow-y: auto">
// <table style="border-spacing: 0">
// <tr style="height: 30px">
// <th>#</th>
// <th>Name</th>
// <tr>
// <tr virtual-repeat.for="item of items" style="height: 50px;">
// <td>\${$index}</td>
// <td>\${item}</td>
// </tr>
// </table>
// </div>`;
// });
// it([
// '100 items',
// '\t[header row] <-- h:30',
// '\t[body rows] <-- h:50 each',
// '\t-- scrollTop from 0 to 79 should not affect first row'
// ].join('\n'), async () => {
// const { viewModel, virtualRepeat } = await bootstrapComponent({ items: createItems(100) });
// const scrollCtEl = virtualRepeat.getScroller();
// expect(scrollCtEl.scrollHeight).toEqual(100 * 50 + 30, 'scrollCtEl.scrollHeight');
// for (let i = 0; 79 > i; ++i) {
// scrollCtEl.scrollTop = i;
// await waitForNextFrame();
// expect(virtualRepeat.view(0).bindingContext.item).toEqual('item0');
// // todo: more validation of scrolled state here
// }
// for (let i = 80; 80 + 49 > i; ++i) {
// scrollCtEl.scrollTop = i;
// await waitForNextFrame();
// expect(virtualRepeat.view(0).bindingContext.item).toEqual('item1');
// // todo: more validation of scrolled state here
// }
// });
// });
// describe('<tbody virtual-repeat.for>', () => {
// beforeEach(() => {
// view =
// `<div style="height: 500px; overflow-y: auto">
// <table style="border-spacing: 0">
// <thead>
// <tr style="height: 30px">
// <th>#</th>
// <th>Name</th>
// <tr>
// </thead>
// <tbody virtual-repeat.for="item of items">
// <tr style="height: 50px;">
// <td>\${$index}</td>
// <td>\${item}</td>
// </tr>
// </tbody>
// </table>
// </div>`;
// });
// it([
// '100 items',
// '\t[theader row] <-- h:30',
// '\t[tbody rows] <-- h:50 each',
// '\t-- scrollTop from 0 to 79 should not affect first row'
// ].join('\n'), async () => {
// const { viewModel, virtualRepeat } = await bootstrapComponent({ items: createItems(100) });
// const scrollCtEl = document.querySelector('#scrollCtEl');
// expect(scrollCtEl.scrollHeight).toEqual(100 * 50 + 30, 'scrollCtEl.scrollHeight');
// for (let i = 0; 79 > i; ++i) {
// scrollCtEl.scrollTop = i;
// await waitForNextFrame();
// expect(virtualRepeat.view(0).bindingContext.item).toEqual('item0');
// // todo: more validation of scrolled state here
// }
// for (let i = 80; 80 + 49 > i; ++i) {
// scrollCtEl.scrollTop = i;
// await waitForNextFrame();
// expect(virtualRepeat.view(0).bindingContext.item).toEqual('item1');
// // todo: more validation of scrolled state here
// }
// });
// });
describe('multiple repeats', () => {
beforeEach(() => {
view =
`<div id="scrollCtEl" style="height: 500px; overflow-y: auto">
<table style="border-spacing: 0">
<tr style="height: 30px">
<th>#</th>
<th>Name</th>
<tr>
<tr virtual-repeat.for="item of items" style="height: 50px;">
<td>\${$index}</td>
<td>\${item}</td>
</tr>
<tr style="height: 100px">
<td colspan="2">Separator</td>
</tr>
<tr virtual-repeat.for="item of items" style="height: 50px;">
<td>\${$index}</td>
<td>\${item}</td>
</tr>
</table>
</div>`;
});
it([
'100 items.',
'\t[header row] <-- h:30',
'\t[body rows] <-- h:50 each',
'\t[separator row] <-- h:100',
'\t[body rows] <-- h:50 each',
'\t-- scrollTop from 0 to 79 should not affect first row',
].join('\n'), async () => {
const { viewModel, virtualRepeat } = await bootstrapComponent({ items: createItems(100) }, view);
const scrollCtEl = document.querySelector('#scrollCtEl');
expect(scrollCtEl.scrollHeight).toEqual(
/* 2 repeats */200
* /* height of each row */50
+ /* height of header */30
+ /* height of separator */100,
'scrollCtEl.scrollHeight'
);
for (let i = 0; 79 > i; i += 7) {
scrollCtEl.scrollTop = i;
await waitForNextFrame();
expect(virtualRepeat.view(0).bindingContext.item).toEqual('item0');
// todo: more validation of scrolled state here
}
for (let i = 80; 80 + 49 > i; i += 7) {
scrollCtEl.scrollTop = i;
await waitForNextFrame();
expect(virtualRepeat.view(0).bindingContext.item).toEqual('item1');
// todo: more validation of scrolled state here
}
const secondRepeatStart = 100 * 50 + 30 + 100;
const secondRepeat = component['rootView'].controllers[1].viewModel;
expect(secondRepeat).toBeDefined();
for (let i = 0; 50 > i; i += 7) {
scrollCtEl.scrollTop = secondRepeatStart + i;
await waitForNextFrame();
expect(virtualRepeat.topBufferHeight).toEqual(100 * 50 - (500 / 50 + 1) * 2 * 50, 'height:repeat1.topBuffer');
expect(virtualRepeat.bottomBufferHeight).toEqual(0, 'height:repeat1.botBuffer');
expect(secondRepeat.view(0).bindingContext.item).toEqual('item0');
// todo: more validation of scrolled state here
}
});
});
const repeatScrollNextCombos: IRepeatScrollNextCombo[] = [
['', 'infinite-scroll-next="getNextPage"'],
['', 'infinite-scroll-next.call="getNextPage($scrollContext)"'],
[' & toView', 'infinite-scroll-next="getNextPage"'],
[' & twoWay', 'infinite-scroll-next="getNextPage"'],
[' & twoWay', 'infinite-scroll-next.call="getNextPage($scrollContext)"'],
[' | cloneArray', 'infinite-scroll-next="getNextPage"', [CloneArrayValueConverter]],
[' | cloneArray', 'infinite-scroll-next.call="getNextPage($scrollContext)"', [CloneArrayValueConverter]],
[' | identity | cloneArray & toView', 'infinite-scroll-next="getNextPage"', [IdentityValueConverter, CloneArrayValueConverter]],
[' | identity | cloneArray & toView', 'infinite-scroll-next.call="getNextPage($scrollContext)"', [IdentityValueConverter, CloneArrayValueConverter]],
[' | cloneArray & toView', 'infinite-scroll-next="getNextPage"', [CloneArrayValueConverter]],
// cloneArray and two way creates infinite loop
// [' | cloneArray & twoWay', 'infinite-scroll-next="getNextPage"', [CloneArrayValueConverter]]
];
const scrollingTestGroups: IScrollingTestCaseGroup[] = [
{
topBufferOffset: 30,
itemHeight: 50,
scrollerHeight: 500,
title: (itemHeight, scrollerHeight, topBufferOffset, repeatAttr: string) =>
[
`div[scroller h:${scrollerHeight}] > table > tr[repeat${repeatAttr}]`,
'-- 100 items',
`-- [theader row] <-- h:${topBufferOffset}`,
`-- [tr rows] <-- h:${itemHeight} each`,
'',
].join('\n\t'),
createView: (itemHeight, scrollerHeight, topBufferOffset, repeatAttr) =>
`<div style="height: ${scrollerHeight}px; overflow-y: auto">
<table style="border-spacing: 0">
<thead>
<tr style="height: ${topBufferOffset}px">
<th>#</th>
<th>Name</th>
<tr>
</thead>
<tr virtual-repeat.for="item of items ${repeatAttr}" style="height: ${itemHeight}px;">
<td>\${$index}</td>
<td>\${item}</td>
</tr>
</table>
</div>`,
},
{
topBufferOffset: 30,
itemHeight: 50,
scrollerHeight: 500,
title: (itemHeight, scrollerHeight, topBufferOffset, repeatAttr: string) =>
[
`div[scroller h:${scrollerHeight}] > table > tbody[repeat${repeatAttr}]`,
'-- 100 items',
`-- [theader row] <-- h:${topBufferOffset}`,
`-- [tbody rows] <-- h:${itemHeight} each`,
'',
].join('\n\t'),
createView: (itemHeight, scrollerHeight, topBufferOffset, repeatAttr) =>
`<div style="height: ${scrollerHeight}px; overflow-y: auto">
<table style="border-spacing: 0">
<thead>
<tr style="height: ${topBufferOffset}px">
<th>#</th>
<th>Name</th>
<tr>
</thead>
<tbody virtual-repeat.for="item of items ${repeatAttr}">
<tr style="height: ${itemHeight}px;">
<td>\${$index}</td>
<td>\${item}</td>
</tr>
</tbody>
</table>
</div>`,
},
{
topBufferOffset: 0,
itemHeight: 50,
scrollerHeight: 500,
title: (itemHeight, scrollerHeight, topBufferOffset, repeatAttr: string) =>
[
`div[scroller h:${scrollerHeight}] > ol > li[repeat${repeatAttr}]`,
'-- 100 items',
`-- [li rows] <-- h:${itemHeight} each`,
'',
].join('\n\t'),
createView: (itemHeight, scrollerHeight, topBufferOffset, repeatAttr) =>
`<div style="height: ${scrollerHeight}px; overflow-y: auto">
<ol style="list-style: none; margin: 0;">
<li virtual-repeat.for="item of items ${repeatAttr}" style="height: ${itemHeight}px;">
\${$index}
</li>
</ol>
</div>`,
},
{
topBufferOffset: 0,
itemHeight: 50,
scrollerHeight: 500,
title: (itemHeight, scrollerHeight, topBufferOffset, repeatAttr: string) =>
[
`ol[scroller h:${scrollerHeight}] > li[repeat${repeatAttr}]`,
'-- 100 items',
`-- [li rows] <-- h:${itemHeight} each`,
'',
].join('\n\t'),
createView: (itemHeight, scrollerHeight, topBufferOffset, repeatAttr) =>
`<ol style="height: ${scrollerHeight}px; overflow-y: auto; list-style: none; margin: 0;">
<li virtual-repeat.for="item of items ${repeatAttr}" style="height: ${itemHeight}px;">
\${$index}
</li>
</ol>`,
},
];
eachCartesianJoin(
[repeatScrollNextCombos, scrollingTestGroups],
(testAttributesCombo, testGroup) => {
const [repeatAttr, scrollNextAttr, resources] = testAttributesCombo;
const { title, itemHeight, scrollerHeight, topBufferOffset, createView, extraAssert } = testGroup;
runTestGroup(
title(itemHeight, scrollerHeight, topBufferOffset, repeatAttr),
createView(itemHeight, scrollerHeight, topBufferOffset, repeatAttr),
{ itemHeight, scrollerHeight, topBufferOffset },
extraAssert
);
}
);
function runTestGroup(
title: string,
$view: string,
{
itemHeight,
scrollerHeight,
topBufferOffset,
}: {
itemHeight: number;
scrollerHeight: number;
topBufferOffset: number;
},
extraAssert: (repeat, component) => void,
extraResources?: any[]
): void {
describe(title, () => {
it([
'100 items',
`-- scrollTop from 0 to ${itemHeight - 1} should not affect first row`,
].join('\n\t'), async () => {
const ITEM_COUNT = 100;
const { viewModel, virtualRepeat } = await bootstrapComponent(
{ items: createItems(ITEM_COUNT) },
$view,
[CloneArrayValueConverter, IdentityValueConverter]
);
const scrollCtEl = virtualRepeat.getScroller();
expect(scrollCtEl.scrollHeight).toEqual(ITEM_COUNT * itemHeight + topBufferOffset, 'scrollCtEl.scrollHeight');
for (let i = 0; itemHeight > i; i += Math.floor(itemHeight / 9)) {
scrollCtEl.scrollTop = i;
await waitForNextFrame();
expect(virtualRepeat.view(0).bindingContext.item).toEqual('item0');
// todo: more validation of scrolled state here
}
for (let i = itemHeight + topBufferOffset; itemHeight + topBufferOffset + (itemHeight - 1) > i; i += Math.floor(itemHeight / 9)) {
scrollCtEl.scrollTop = i;
await waitForNextFrame();
expect(virtualRepeat.view(0).bindingContext.item).toEqual('item1');
// todo: more validation of scrolled state here
}
});
it([
`100 items`,
`-- scroll to bottom`,
`-- scroll from bottom to index ${100 - calcMinViewsRequired(scrollerHeight, itemHeight)} should not affect first row`,
].join('\n\t'), async () => {
const ITEM_COUNT = 100;
const { viewModel, virtualRepeat } = await bootstrapComponent(
{ items: createItems(ITEM_COUNT) },
$view,
[CloneArrayValueConverter, IdentityValueConverter]
);
const scroller_el = virtualRepeat.getScroller();
expect(scroller_el.scrollHeight).toEqual(ITEM_COUNT * itemHeight + topBufferOffset, 'scrollCtEl.scrollHeight');
scroller_el.scrollTop = scroller_el.scrollHeight;
await waitForNextFrame();
const minViewsRequired = calcMinViewsRequired(scrollerHeight, itemHeight);
const maxViewsRequired = minViewsRequired * 2;
let expected_first_index = 100 - maxViewsRequired;
expect(virtualRepeat.$first).toBe(expected_first_index, '@scroll bottom -> repeat._first 1');
const maxScrollTop = scroller_el.scrollTop;
// only minViewsRequired > i because by default
// it's already scrolled half way equal to minViewsRequired as scrollTop max = scrollHeight - minViewsRequired * itemHeight
for (let i = 0; minViewsRequired >= i; ++i) {
scroller_el.scrollTop = maxScrollTop - i * itemHeight;
await waitForNextFrame();
expect(virtualRepeat.$first).toBe(expected_first_index, '@scroll ⬆ -> repeat._first 2:' + i);
}
});
});
}
type IRepeatScrollNextCombo = [
/*repeat extra expression*/string,
/*infinite-scroll-next attr*/string,
/*extraResources*/ any[]?
];
interface IScrollingTestCaseGroup {
topBufferOffset: number;
itemHeight: number;
scrollerHeight: number;
title: (itemHeight: number, scrollerHeight: number, topBufferOffset: number, repeatAttr: string) => string;
createView: (itemHeight: number, scrollerHeight: number, topBufferOffset: number, repeatAttr: string) => string;
extraAssert?: (repeat: VirtualRepeat, component: ComponentTester<VirtualRepeat>) => void;
}
async function bootstrapComponent<T>($viewModel: ITestAppInterface<T>, $view: string, extraResources: any[] = []) {
component = StageComponent
.withResources(Array.from(new Set([...resources, ...extraResources])))
.inView($view)
.boundTo($viewModel);
await component.create(bootstrap);
return { virtualRepeat: component.viewModel, viewModel: $viewModel, component: component };
}
function createItems(amount: number, name: string = 'item') {
return Array.from({ length: amount }, (_, index) => name + index);
}
}); | the_stack |
import { GatewayConfig, GenericProvider, Mutation, MutationEventSignature, MutationEventTypeKind, SignMethod } from '@0xcert/ethereum-generic-provider';
import { ZERO_ADDRESS } from '@0xcert/ethereum-utils';
import { AssetLedgerDeployOrder, AssetSetOperatorOrder, DappValueApproveOrder, DynamicActionsOrder, FixedActionsOrder, GatewayBase, Order, OrderKind,
ProviderError, ProviderIssue, SignedDynamicActionsOrder, SignedFixedActionsOrder, ValueLedgerDeployOrder } from '@0xcert/scaffold';
import { createOrderHash as createActionsOrderHash, normalizeOrderIds as normalizeActionsOrderIds } from '../lib/actions-order';
import { createOrderHash as createAssetLedgerDeployOrderHash, normalizeOrderIds as normalizeAssetLedgerDeployOrderIds } from '../lib/asset-ledger-deploy-order';
import { createOrderHash as createAssetSetOperatorOrderHash, normalizeOrderIds as normalizeAssetSetOperatorOrderIds } from '../lib/asset-set-operator-order';
import { createOrderHash as createDappValueApproveOrderHash, normalizeOrderIds as normalizeDappValueApproveOrderIds } from '../lib/dapp-value-approve-order';
import { createOrderHash as createValueLedgerDeployOrderHash, normalizeOrderIds as normalizeValueLedgerDeployOrderIds } from '../lib/value-ledger-deploy-order';
import actionsOrderCancel from '../mutations/actions-order/cancel';
import actionsOrderPerform from '../mutations/actions-order/perform';
import assetLedgerDeployOrderCancel from '../mutations/asset-ledger-deploy-order/cancel';
import assetLedgerDeployOrderPerform from '../mutations/asset-ledger-deploy-order/perform';
import assetSetOperatorOrderCancel from '../mutations/asset-set-operator-order/cancel';
import assetSetOperatorOrderPerform from '../mutations/asset-set-operator-order/perform';
import dappValueApproveOrderCancel from '../mutations/dapp-value-approve-order/cancel';
import dappValueApproveOrderPerform from '../mutations/dapp-value-approve-order/perform';
import valueLedgerDeployOrderCancel from '../mutations/value-ledger-deploy-order/cancel';
import valueLedgerDeployOrderPerform from '../mutations/value-ledger-deploy-order/perform';
import actionsOrderClaimEthSign from '../queries/actions-order/claim-eth-sign';
import actionsOrderClaimPersonalSign from '../queries/actions-order/claim-personal-sign';
import getActionsOrderDataClaim from '../queries/actions-order/get-order-data-claim';
import getProxyAccountId from '../queries/actions-order/get-proxy-account-id';
import actionsOrderisValidSignature from '../queries/actions-order/is-valid-signature';
import assetLedgerDeployOrderClaimEthSign from '../queries/asset-ledger-deploy-order/claim-eth-sign';
import assetLedgerDeployOrderClaimPersonalSign from '../queries/asset-ledger-deploy-order/claim-personal-sign';
import getAssetLedgerDeployOrderDataClaim from '../queries/asset-ledger-deploy-order/get-order-data-claim';
import assetLedgerDeployOrderisValidSignature from '../queries/asset-ledger-deploy-order/is-valid-signature';
import assetSetOperatorOrderClaimEthSign from '../queries/asset-set-operator-order/claim-eth-sign';
import assetSetOperatorOrderClaimPersonalSign from '../queries/asset-set-operator-order/claim-personal-sign';
import getAssetSetOperatorOrderDataClaim from '../queries/asset-set-operator-order/get-order-data-claim';
import assetSetOperatorOrderisValidSignature from '../queries/asset-set-operator-order/is-valid-signature';
import dappValueApproveOrderClaimEthSign from '../queries/dapp-value-approve-order/claim-eth-sign';
import dappValueApproveOrderClaimPersonalSign from '../queries/dapp-value-approve-order/claim-personal-sign';
import getDappValueApproveOrderDataClaim from '../queries/dapp-value-approve-order/get-order-data-claim';
import dappValueApproveOrderisValidSignature from '../queries/dapp-value-approve-order/is-valid-signature';
import valueLedgerDeployOrderClaimEthSign from '../queries/value-ledger-deploy-order/claim-eth-sign';
import valueLedgerDeployOrderClaimPersonalSign from '../queries/value-ledger-deploy-order/claim-personal-sign';
import getValueLedgerDeployOrderDataClaim from '../queries/value-ledger-deploy-order/get-order-data-claim';
import valueLedgerDeployOrderisValidSignature from '../queries/value-ledger-deploy-order/is-valid-signature';
import { ProxyId, ProxyKind } from './types';
/**
* Ethereum gateway implementation.
*/
export class Gateway implements GatewayBase {
/**
* Address of the smart contract that represents this gateway.
*/
protected _config: GatewayConfig;
/**
* Provider instance.
*/
protected _provider: GenericProvider;
/**
* Initialize gateway.
* @param provider Provider class with which we comunicate with blockchain.
* @param config Gateway config.
*/
public constructor(provider: GenericProvider, config?: GatewayConfig) {
this._provider = provider;
this.config = config || provider.gatewayConfig;
}
/**
* Gets an instance of gateway.
* @param provider Provider class with which we communicate with blockchain.
* @param config Gateway configuration.
*/
public static getInstance(provider: GenericProvider, config?: GatewayConfig): Gateway {
return new this(provider, config);
}
/**
* Returns gateway config.
*/
public get config(): GatewayConfig {
return this._config || null;
}
/**
* Sets and normalizes gateway config.
*/
public set config(config: GatewayConfig) {
if (config) {
this._config = {
actionsOrderId: this._provider.encoder.normalizeAddress(config.actionsOrderId),
assetLedgerDeployOrderId: this._provider.encoder.normalizeAddress(config.assetLedgerDeployOrderId),
valueLedgerDeployOrderId: this._provider.encoder.normalizeAddress(config.valueLedgerDeployOrderId),
};
} else {
this._config = null;
}
}
/**
* Gets the provider that is used to communicate with blockchain.
*/
public get provider() {
return this._provider;
}
/**
* Gets hash of an order.
* @param order Order data.
*/
public async hash(order: Order): Promise<string> {
if (order.kind === OrderKind.DYNAMIC_ACTIONS_ORDER
|| order.kind === OrderKind.SIGNED_DYNAMIC_ACTIONS_ORDER
) {
order = this.createDynamicOrder(order);
order = normalizeActionsOrderIds(order, this._provider);
return createActionsOrderHash(this, order);
} else if (order.kind === OrderKind.FIXED_ACTIONS_ORDER
|| order.kind === OrderKind.SIGNED_FIXED_ACTIONS_ORDER
) {
order = normalizeActionsOrderIds(order, this._provider);
return createActionsOrderHash(this, order);
} else if (order.kind === OrderKind.ASSET_LEDGER_DEPLOY_ORDER) {
order = normalizeAssetLedgerDeployOrderIds(order, this._provider);
return createAssetLedgerDeployOrderHash(this, order);
} else if (order.kind === OrderKind.VALUE_LEDGER_DEPLOY_ORDER) {
order = normalizeValueLedgerDeployOrderIds(order, this._provider);
return createValueLedgerDeployOrderHash(this, order);
} else if (order.kind === OrderKind.ASSET_SET_OPERATOR_ORDER) {
order = normalizeAssetSetOperatorOrderIds(order, this._provider);
return createAssetSetOperatorOrderHash(order);
} else if (order.kind === OrderKind.DAPP_VALUE_APPROVE_ORDER) {
order = normalizeDappValueApproveOrderIds(order, this._provider);
return createDappValueApproveOrderHash(order);
} else {
throw new Error('Not implemented');
}
}
/**
* Gets signed claim for an order.
* @param order Order data.
*/
public async sign(order: Order): Promise<string> {
if (order.kind === OrderKind.DYNAMIC_ACTIONS_ORDER
|| order.kind === OrderKind.SIGNED_DYNAMIC_ACTIONS_ORDER
) {
order = this.createDynamicOrder(order);
order = normalizeActionsOrderIds(order, this._provider);
if (this._provider.signMethod == SignMethod.PERSONAL_SIGN) {
return actionsOrderClaimPersonalSign(this, order);
} else {
return actionsOrderClaimEthSign(this, order);
}
} else if (order.kind === OrderKind.FIXED_ACTIONS_ORDER
|| order.kind === OrderKind.SIGNED_FIXED_ACTIONS_ORDER
) {
order = normalizeActionsOrderIds(order, this._provider);
if (this._provider.signMethod == SignMethod.PERSONAL_SIGN) {
return actionsOrderClaimPersonalSign(this, order);
} else {
return actionsOrderClaimEthSign(this, order);
}
} else if (order.kind === OrderKind.ASSET_LEDGER_DEPLOY_ORDER) {
order = normalizeAssetLedgerDeployOrderIds(order, this._provider);
if (this._provider.signMethod == SignMethod.PERSONAL_SIGN) {
return assetLedgerDeployOrderClaimPersonalSign(this, order);
} else {
return assetLedgerDeployOrderClaimEthSign(this, order);
}
} else if (order.kind === OrderKind.VALUE_LEDGER_DEPLOY_ORDER) {
order = normalizeValueLedgerDeployOrderIds(order, this._provider);
if (this._provider.signMethod == SignMethod.PERSONAL_SIGN) {
return valueLedgerDeployOrderClaimPersonalSign(this, order);
} else {
return valueLedgerDeployOrderClaimEthSign(this, order);
}
} else if (order.kind === OrderKind.ASSET_SET_OPERATOR_ORDER) {
order = normalizeAssetSetOperatorOrderIds(order, this._provider);
if (this._provider.signMethod == SignMethod.PERSONAL_SIGN) {
return assetSetOperatorOrderClaimPersonalSign(this, order);
} else {
return assetSetOperatorOrderClaimEthSign(this, order);
}
} else if (order.kind === OrderKind.DAPP_VALUE_APPROVE_ORDER) {
order = normalizeDappValueApproveOrderIds(order, this._provider);
if (this._provider.signMethod == SignMethod.PERSONAL_SIGN) {
return dappValueApproveOrderClaimPersonalSign(this, order);
} else {
return dappValueApproveOrderClaimEthSign(this, order);
}
} else {
throw new Error('Not implemented');
}
}
/**
* Performs an order.
* @param order Order data.
* @param signature Signature data.
*/
public async perform(order: DynamicActionsOrder, signature: string[]): Promise<Mutation>;
public async perform(order: SignedDynamicActionsOrder, signature: string[]): Promise<Mutation>;
public async perform(order: FixedActionsOrder, signature: string[]): Promise<Mutation>;
public async perform(order: SignedFixedActionsOrder, signature: string[]): Promise<Mutation>;
public async perform(order: AssetLedgerDeployOrder, signature: string): Promise<Mutation>;
public async perform(order: ValueLedgerDeployOrder, signature: string): Promise<Mutation>;
public async perform(order: AssetSetOperatorOrder, signature: string): Promise<Mutation>;
public async perform(order: DappValueApproveOrder, signature: string): Promise<Mutation>;
public async perform(order: any, signature: any): Promise<Mutation> {
if (order.kind === OrderKind.DYNAMIC_ACTIONS_ORDER) {
order = this.createDynamicOrder(order);
if (order.signers.length !== signature.length + 1) {
throw new ProviderError(ProviderIssue.DYNAMIC_ACTIONS_ORDER_SIGNATURES);
}
order = normalizeActionsOrderIds(order, this._provider);
return actionsOrderPerform(this, order, signature);
} else if (order.kind === OrderKind.FIXED_ACTIONS_ORDER) {
if (order.signers.length !== signature.length + 1) {
throw new ProviderError(ProviderIssue.FIXED_ACTIONS_ORDER_SIGNATURES);
}
order = normalizeActionsOrderIds(order, this._provider);
return actionsOrderPerform(this, order, signature as string[]);
} else if (order.kind === OrderKind.SIGNED_DYNAMIC_ACTIONS_ORDER) {
order = this.createDynamicOrder(order);
if (order.signers.length !== signature.length) {
throw new ProviderError(ProviderIssue.SIGNED_DYNAMIC_ACTIONS_ORDER_SIGNATURES);
}
order = normalizeActionsOrderIds(order, this._provider);
return actionsOrderPerform(this, order, signature as string[]);
} else if (order.kind === OrderKind.SIGNED_FIXED_ACTIONS_ORDER) {
if (order.signers.length !== signature.length) {
throw new ProviderError(ProviderIssue.SIGNED_FIXED_ACTIONS_ORDER_SIGNATURES);
}
order = normalizeActionsOrderIds(order, this._provider);
return actionsOrderPerform(this, order, signature as string[]);
} else if (order.kind === OrderKind.ASSET_LEDGER_DEPLOY_ORDER) {
order = normalizeAssetLedgerDeployOrderIds(order, this._provider);
return assetLedgerDeployOrderPerform(this, order, signature);
} else if (order.kind === OrderKind.VALUE_LEDGER_DEPLOY_ORDER) {
order = normalizeValueLedgerDeployOrderIds(order, this._provider);
return valueLedgerDeployOrderPerform(this, order, signature);
} else if (order.kind === OrderKind.ASSET_SET_OPERATOR_ORDER) {
order = normalizeAssetSetOperatorOrderIds(order, this._provider);
return assetSetOperatorOrderPerform(this, order, signature);
} else if (order.kind === OrderKind.DAPP_VALUE_APPROVE_ORDER) {
order = normalizeDappValueApproveOrderIds(order, this._provider);
return dappValueApproveOrderPerform(this, order, signature);
} else {
throw new ProviderError(ProviderIssue.ACTIONS_ORDER_KIND_NOT_SUPPORTED);
}
}
/**
* Cancels an order.
* @param order Order data.
*/
public async cancel(order: Order): Promise<Mutation> {
if (order.kind === OrderKind.DYNAMIC_ACTIONS_ORDER
|| order.kind === OrderKind.SIGNED_DYNAMIC_ACTIONS_ORDER
) {
order = this.createDynamicOrder(order);
order = normalizeActionsOrderIds(order, this._provider);
return actionsOrderCancel(this, order);
} else if (order.kind === OrderKind.FIXED_ACTIONS_ORDER
|| order.kind === OrderKind.SIGNED_FIXED_ACTIONS_ORDER
) {
order = normalizeActionsOrderIds(order, this._provider);
return actionsOrderCancel(this, order);
} else if (order.kind === OrderKind.ASSET_LEDGER_DEPLOY_ORDER) {
order = normalizeAssetLedgerDeployOrderIds(order, this._provider);
return assetLedgerDeployOrderCancel(this, order);
} else if (order.kind === OrderKind.VALUE_LEDGER_DEPLOY_ORDER) {
order = normalizeValueLedgerDeployOrderIds(order, this._provider);
return valueLedgerDeployOrderCancel(this, order);
} else if (order.kind === OrderKind.ASSET_SET_OPERATOR_ORDER) {
order = normalizeAssetSetOperatorOrderIds(order, this._provider);
return assetSetOperatorOrderCancel(this, order);
} else if (order.kind === OrderKind.DAPP_VALUE_APPROVE_ORDER) {
order = normalizeDappValueApproveOrderIds(order, this._provider);
return dappValueApproveOrderCancel(this, order);
} else {
throw new ProviderError(ProviderIssue.ACTIONS_ORDER_KIND_NOT_SUPPORTED);
}
}
/**
* Gets address of the proxy based on the kind.
* @param proxyKind Kind of the proxy.
*/
public async getProxyAccountId(proxyKind: ProxyKind.TRANSFER_ASSET, ledgerId?: string);
public async getProxyAccountId(proxyKind: ProxyKind.CREATE_ASSET);
public async getProxyAccountId(proxyKind: ProxyKind.DESTROY_ASSET);
public async getProxyAccountId(proxyKind: ProxyKind.MANAGE_ABILITIES);
public async getProxyAccountId(proxyKind: ProxyKind.TRANSFER_TOKEN);
public async getProxyAccountId(proxyKind: ProxyKind.UPDATE_ASSET);
public async getProxyAccountId(...args: any[]) {
let proxyId = ProxyId.NFTOKEN_SAFE_TRANSFER;
switch (args[0]) {
case ProxyKind.TRANSFER_ASSET: {
if (typeof args[1] !== 'undefined' && this.provider.unsafeRecipientIds.indexOf(args[1]) !== -1) {
proxyId = ProxyId.NFTOKEN_TRANSFER;
}
break;
}
case ProxyKind.CREATE_ASSET: {
proxyId = ProxyId.XCERT_CREATE;
break;
}
case ProxyKind.DESTROY_ASSET: {
proxyId = ProxyId.XCERT_BURN;
break;
}
case ProxyKind.MANAGE_ABILITIES: {
proxyId = ProxyId.MANAGE_ABILITIES;
break;
}
case ProxyKind.TRANSFER_TOKEN: {
proxyId = ProxyId.TOKEN_TRANSFER;
break;
}
case ProxyKind.UPDATE_ASSET: {
proxyId = ProxyId.XCERT_UPDATE;
break;
}
default: {
throw new ProviderError(ProviderIssue.PROXY_KIND_NOT_SUPPORTED);
}
}
return getProxyAccountId(this, proxyId);
}
/**
* Checks if claim for this order is valid.
* @param order Order data.
* @param claim Claim data.
*/
public async isValidSignature(order: Order, claim: string, signer?: string) {
if (order.kind === OrderKind.DYNAMIC_ACTIONS_ORDER
|| order.kind === OrderKind.SIGNED_DYNAMIC_ACTIONS_ORDER
&& signer !== 'undefined'
) {
order = this.createDynamicOrder(order);
order = normalizeActionsOrderIds(order, this._provider);
return actionsOrderisValidSignature(this, order, claim, signer);
} else if (order.kind === OrderKind.FIXED_ACTIONS_ORDER
|| order.kind === OrderKind.SIGNED_FIXED_ACTIONS_ORDER
&& signer !== 'undefined'
) {
order = normalizeActionsOrderIds(order, this._provider);
return actionsOrderisValidSignature(this, order, claim, signer);
} else if (order.kind === OrderKind.ASSET_LEDGER_DEPLOY_ORDER) {
order = normalizeAssetLedgerDeployOrderIds(order, this._provider);
return assetLedgerDeployOrderisValidSignature(this, order, claim);
} else if (order.kind === OrderKind.VALUE_LEDGER_DEPLOY_ORDER) {
order = normalizeValueLedgerDeployOrderIds(order, this._provider);
return valueLedgerDeployOrderisValidSignature(this, order, claim);
} else if (order.kind === OrderKind.ASSET_SET_OPERATOR_ORDER) {
order = normalizeAssetSetOperatorOrderIds(order, this._provider);
return assetSetOperatorOrderisValidSignature(this, order, claim);
} else if (order.kind === OrderKind.DAPP_VALUE_APPROVE_ORDER) {
order = normalizeDappValueApproveOrderIds(order, this._provider);
return dappValueApproveOrderisValidSignature(this, order, claim);
} else {
throw new ProviderError(ProviderIssue.ACTIONS_ORDER_KIND_NOT_SUPPORTED);
}
}
/**
* Generates hash from order.
* @param order Order data.
*/
public async getOrderDataClaim(order: Order) {
if (order.kind === OrderKind.DYNAMIC_ACTIONS_ORDER
|| order.kind === OrderKind.SIGNED_DYNAMIC_ACTIONS_ORDER
) {
order = this.createDynamicOrder(order);
order = normalizeActionsOrderIds(order, this._provider);
return getActionsOrderDataClaim(this, order);
} else if (order.kind === OrderKind.FIXED_ACTIONS_ORDER
|| order.kind === OrderKind.SIGNED_FIXED_ACTIONS_ORDER
) {
order = normalizeActionsOrderIds(order, this._provider);
return getActionsOrderDataClaim(this, order);
} else if (order.kind === OrderKind.ASSET_LEDGER_DEPLOY_ORDER) {
order = normalizeAssetLedgerDeployOrderIds(order, this._provider);
return getAssetLedgerDeployOrderDataClaim(this, order);
} else if (order.kind === OrderKind.VALUE_LEDGER_DEPLOY_ORDER) {
order = normalizeValueLedgerDeployOrderIds(order, this._provider);
return getValueLedgerDeployOrderDataClaim(this, order);
} else if (order.kind === OrderKind.ASSET_SET_OPERATOR_ORDER) {
order = normalizeAssetSetOperatorOrderIds(order, this._provider);
return getAssetSetOperatorOrderDataClaim(this, order);
} else if (order.kind === OrderKind.DAPP_VALUE_APPROVE_ORDER) {
order = normalizeDappValueApproveOrderIds(order, this._provider);
return getDappValueApproveOrderDataClaim(this, order);
} else {
throw new ProviderError(ProviderIssue.ACTIONS_ORDER_KIND_NOT_SUPPORTED);
}
}
/**
* Gets context for mutation event parsing.
* This are event definitions for Gateway smart contracts event parsing. This method is used
* by the Mutation class to provide log information.
*/
public getContext(): MutationEventSignature[] {
return [
{
name: 'ProxyChange',
topic: '0x8edda873a8ad561ecebeb71ceb3ae6bcb70c2b76a3fcb869859895c4d4fc7416',
types: [
{
kind: MutationEventTypeKind.INDEXED,
name: 'index',
type: 'uint256',
},
{
kind: MutationEventTypeKind.NORMAL,
name: 'proxy',
type: 'address',
},
],
},
{
name: 'Perform', // actions order
topic: '0xa4be90ab47bcea0c591eaa7dd28b8ba0329e7ebddac48c5f2ca9fed68d08cf08',
types: [
{
kind: MutationEventTypeKind.INDEXED,
name: 'claim',
type: 'bytes32',
},
],
},
{
name: 'Cancel', // actions order
topic: '0xe8d9861dbc9c663ed3accd261bbe2fe01e0d3d9e5f51fa38523b265c7757a93a',
types: [
{
kind: MutationEventTypeKind.INDEXED,
name: 'claim',
type: 'bytes32',
},
],
},
{
name: 'Perform', // deploy asset/value ledger order
topic: '0x492318801c2cec532d47019a0b69f83b8d5b499a022b7adb6100a766050644f2',
types: [
{
kind: MutationEventTypeKind.INDEXED,
name: 'maker',
type: 'address',
},
{
kind: MutationEventTypeKind.INDEXED,
name: 'taker',
type: 'address',
},
{
kind: MutationEventTypeKind.NORMAL,
name: 'createdContract',
type: 'address',
},
{
kind: MutationEventTypeKind.NORMAL,
name: 'claim',
type: 'bytes32',
},
],
},
{
name: 'Cancel', // deploy asset/value ledger order
topic: '0x421b43caf093b5e58d1ea89ca0d80151eda923342cf3cfddf5eb6b30d4947ba0',
types: [
{
kind: MutationEventTypeKind.INDEXED,
name: 'maker',
type: 'address',
},
{
kind: MutationEventTypeKind.INDEXED,
name: 'taker',
type: 'address',
},
{
kind: MutationEventTypeKind.NORMAL,
name: 'claim',
type: 'bytes32',
},
],
},
];
}
/**
* For dynamic actions orders the last signer must be specified as zero address.
*/
protected createDynamicOrder(order: DynamicActionsOrder | SignedDynamicActionsOrder) {
order = JSON.parse(JSON.stringify(order));
order.signers.push(ZERO_ADDRESS);
return order;
}
} | the_stack |
import {useLayoutEffect, useState} from 'react';
import {Twitter} from 'twit';
import {TweetDeckChirp, TweetDeckColumn, TweetdeckMediaEntity} from '../types/tweetdeckTypes';
import {TweetDeckObject} from '../types/tweetdeckTypes';
import {HandlerOf} from './typeHelpers';
/**
* Finds a mustache template whose content matches the query.
* NOTE: as of October 12th 2019, TweetDeck has some of its templates as components so this methods might not find everything.
*/
export const findMustache = (TD: TweetDeckObject, query: string) =>
Object.keys(TD.mustaches).filter((i) =>
TD.mustaches[i].toLowerCase().includes(query.toLowerCase())
);
export const getChirpFromKeyAlone = (TD: TweetDeckObject, key: string) => {
const chirpNode = document.querySelector(`[data-key="${key}"]`);
if (!chirpNode) {
return undefined;
}
return getChirpFromElement(TD, chirpNode);
};
/** Finds a chirp inside TweetDeck given a key and a column key. */
export const getChirpFromKey = (
TD: TweetDeckObject,
key: string,
colKey: string
): TweetDeckChirp | null => {
const column = TD.controller.columnManager.get(colKey);
if (!column) {
return null;
}
const directChirp = column.updateIndex[key];
if (directChirp && directChirp.id === String(key)) {
return directChirp;
}
const chirpsArray: TweetDeckChirp[] = [];
Object.keys(column.updateIndex).forEach((updateKey) => {
const c = column.updateIndex[updateKey];
if (c) {
chirpsArray.push(c);
}
if (c && c.retweetedStatus) {
chirpsArray.push(c.retweetedStatus);
}
if (c && c.quotedTweet) {
chirpsArray.push(c.quotedTweet);
}
if (c && c.messages) {
chirpsArray.push(...c.messages);
}
if (c && c.targetTweet) {
chirpsArray.push(c.targetTweet);
}
});
if (column.detailViewComponent) {
if (column.detailViewComponent.chirp) {
chirpsArray.push(column.detailViewComponent.chirp);
}
if (column.detailViewComponent.mainChirp) {
chirpsArray.push(column.detailViewComponent.mainChirp);
}
if (column.detailViewComponent.repliesTo && column.detailViewComponent.repliesTo.repliesTo) {
chirpsArray.push(...column.detailViewComponent.repliesTo.repliesTo);
}
if (column.detailViewComponent.replies && column.detailViewComponent.replies.replies) {
chirpsArray.push(...column.detailViewComponent.replies.replies);
}
}
const chirp = chirpsArray.find((c) => c.id === String(key));
if (!chirp) {
console.log(`did not find chirp ${key} within ${colKey}`);
return null;
}
return chirp;
};
/** finds the chirp corresponding to an element in the DOM. */
export const getChirpFromElement = (TD: TweetDeckObject, element: HTMLElement | Element) => {
const chirpElm = element.closest('[data-key]');
if (!chirpElm) {
throw new Error('Not a chirp');
}
const chirpKey = chirpElm.getAttribute('data-key') as string;
let col: Element | undefined | null = chirpElm.closest('[data-column]');
if (!col) {
col = document.querySelector(`[data-column] [data-key="${chirpKey}"]`);
if (!col || !col.parentNode) {
throw new Error('Chirp has no column');
} else {
col = col.parentElement;
}
}
if (!col) {
return null;
}
const colKey = col.getAttribute('data-column') as string;
const chirp = getChirpFromKey(TD, chirpKey, colKey);
if (!chirp) {
return null;
}
return {
chirp: chirp,
extra: {
chirpType: chirp.chirpType,
action: chirp.action,
columnKey: colKey,
},
};
};
/** Finds all the URLs (attachments, links, etc) in a chirp. */
export const getURLsFromChirp = (chirp: TweetDeckChirp) => {
let chirpURLs: Twitter.UrlEntity[] = [];
if (!chirp) {
console.log(chirp);
return [];
}
if (chirp.entities) {
chirpURLs = [...chirp.entities.urls, ...chirp.entities.media];
} else if (chirp.targetTweet && chirp.targetTweet.entities) {
// If it got targetTweet it's an activity on a tweet
chirpURLs = [...chirp.targetTweet.entities.urls, ...chirp.targetTweet.entities.media];
} else if (chirp.retweet && chirp.retweet.entities) {
chirpURLs = [...chirp.retweet.entities.urls, ...chirp.retweet.entities.media];
} else if (chirp.retweetedStatus && chirp.retweetedStatus.entities) {
chirpURLs = [...chirp.retweetedStatus.entities.urls, ...chirp.retweetedStatus.entities.media];
}
return chirpURLs;
};
// Might not be useful anymore
export const createSelectorForChirp = (chirp: TweetDeckChirp, colKey: string) =>
`[data-column=${colKey}] [data-key="${chirp.id}"]`;
export function onComposerShown(callback: HandlerOf<boolean>) {
const drawer = document.querySelector('.drawer[data-drawer="compose"]');
const onChange = () => {
const tweetCompose = drawer?.querySelector('textarea.js-compose-text');
if (!tweetCompose) {
callback(false);
return;
}
callback(true);
};
const composerObserver = new MutationObserver(onChange);
composerObserver.observe(drawer!, {
childList: true,
});
onChange();
return () => {
composerObserver.disconnect();
};
}
export function useIsComposerVisible(onVisibleChange?: HandlerOf<boolean>) {
const [isVisible, setIsVisible] = useState(false);
useLayoutEffect(() => {
onComposerShown((bool) => {
setIsVisible(bool);
if (onVisibleChange) {
onVisibleChange(bool);
}
});
return () => {};
}, [onVisibleChange]);
return isVisible;
}
// From http://stackoverflow.com/questions/1064089/inserting-a-text-where-cursor-is-using-javascript-jquery
function insertAtCursor(input: HTMLInputElement | HTMLTextAreaElement, value: string) {
if (input.selectionStart || input.selectionStart === 0) {
const startPos = input.selectionStart;
const endPos = input.selectionEnd;
input.value =
input.value.substring(0, startPos) +
value +
input.value.substring(endPos || 0, input.value.length);
} else {
input.value += value;
}
}
export function insertInsideComposer(string: string) {
const tweetCompose = document.querySelector<HTMLTextAreaElement>('textarea.js-compose-text');
if (!tweetCompose) {
console.error('[BTD] No composer present');
return;
}
insertAtCursor(tweetCompose, string);
tweetCompose.dispatchEvent(new KeyboardEvent('input'));
tweetCompose.dispatchEvent(new Event('change'));
}
export function getCurrentTheme() {
return document.querySelector<HTMLElement>('html')!.classList.contains('dark') ? 'dark' : 'light';
}
export function onThemeChange(callback: HandlerOf<'light' | 'dark'>) {
const root = document.querySelector<HTMLElement>('html');
if (!root) {
return;
}
const onChange = () => {
const theme = root.classList.contains('dark') ? 'dark' : 'light';
callback(theme);
};
const observer = new MutationObserver(onChange);
onChange();
observer.observe(root, {
attributes: true,
attributeFilter: ['class'],
});
}
export const getMediaFromChirp = (chirp: TweetDeckChirp) => {
const urls: string[] = [];
chirp.entities.media.forEach((item) => {
switch (item.type) {
case 'video':
case 'animated_gif':
urls.push(findBiggestBitrate(item.video_info.variants).url.split('?')[0]);
break;
case 'photo':
urls.push(`${item.media_url_https}:orig`);
break;
default:
throw new Error(`unsupported media type: ${item.type}`);
}
});
return urls;
};
const findBiggestBitrate = (videos: TweetdeckMediaEntity['video_info']['variants']) => {
return videos.reduce((max, x) => {
return (x.bitrate || -1) > (max.bitrate || -1) ? x : max;
});
};
export const getFilenameDownloadData = (chirp: TweetDeckChirp, url: string) => {
const chirpCreated = new Date(chirp.created);
return {
fileExtension: url
.replace(/:[a-z]+$/, '')
.split('.')
.pop(),
fileName: url.split('/').pop()!.split('.')[0],
postedUser: chirp.retweetedStatus
? chirp.retweetedStatus.user.screenName
: chirp.user.screenName,
tweetId: chirp.retweetedStatus ? chirp.retweetedStatus.id : chirp.id,
year: chirpCreated.getFullYear(),
month: (chirpCreated.getMonth() + 1).toString().padStart(2, '0'),
day: chirpCreated.getDate().toString().padStart(2, '0'),
hours: chirpCreated.getHours().toString().padStart(2, '0'),
minutes: chirpCreated.getMinutes().toString().padStart(2, '0'),
seconds: chirpCreated.getSeconds().toString().padStart(2, '0'),
};
};
let bannerId = 0;
interface TweetDeckBannerDataActionBase {
action: 'url-ext' | 'trigger-event';
label: string;
class?: string;
}
interface TweetDeckBannerDataActionWithEvent extends TweetDeckBannerDataActionBase {
action: 'trigger-event';
event: {
type: string;
data: object;
};
}
interface TweetDeckBannerDataActionWithUrl extends TweetDeckBannerDataActionBase {
action: 'url-ext';
url: string;
}
type TweetDeckBannerDataAction =
| TweetDeckBannerDataActionWithEvent
| TweetDeckBannerDataActionWithUrl;
interface TweetDeckBannerData {
bannerClasses?: string;
message: {
text: string;
colors?: {
background?: string;
foreground?: string;
};
isUnDismissable?: boolean;
actions?: TweetDeckBannerDataAction[];
};
}
export const displayTweetDeckBanner = (jq: JQueryStatic, data: TweetDeckBannerData) => {
bannerId++;
jq(document).trigger('dataMessage', {
...data,
bannerClasses: `${data.bannerClasses} btd-banner`,
message: {
...data.message,
id: `btd-${bannerId}`,
colors: {
foreground: 'white',
background: '#009eff',
},
actions: (data.message.actions || []).map((a, index) => ({
...a,
actionId: `action-${bannerId}`,
id: `action-${bannerId}`,
class: `btd-banner-button ${a.class}`,
})),
},
});
};
export function reloadColumn(column: TweetDeckColumn) {
column.model.setClearedTimestamp(0);
if (column.reloadTweets) {
column.reloadTweets();
}
} | the_stack |
import test from 'ava';
import * as _ from 'lodash';
import * as async from 'async';
import * as td from 'testdouble';
import * as args from './testArgs';
import { cleanUpPromise } from './helper';
import { hgetall, keys, sismember, zscore } from '../ts/typed-redis-helper';
// to make prefixes per-file separate we add the filename
const prefix = args.prefix + 'feature';
import { Nohm, NohmModel, NohmClass } from '../ts';
const nohm = Nohm;
const redis = args.redis;
test.before(() => {
nohm.setPrefix(prefix);
});
test.afterEach(async () => {
await cleanUpPromise(redis, prefix);
});
const UserMockup = Nohm.model('UserMockup', {
properties: {
name: {
defaultValue: 'test',
type: 'string',
unique: true,
validations: ['notEmpty'],
},
visits: {
index: true,
type: 'integer',
},
email: {
defaultValue: 'email@email.de',
type: 'string',
unique: true,
validations: ['email'],
},
emailOptional: {
defaultValue: '',
type: 'string',
unique: true,
validations: [
{
name: 'email',
options: {
optional: true,
},
},
],
},
country: {
index: true,
defaultValue: 'Tibet',
type: 'string',
validations: ['notEmpty'],
},
json: {
defaultValue: '{}',
type: 'json',
},
},
idGenerator: 'increment',
});
nohm.model('NonIncrement', {
properties: {
name: {
type: 'string',
},
},
});
test.serial(
'creating models with and without a redis client set',
async (t) => {
nohm.client = null as any;
t.throws(
() => {
// tslint:disable-next-line:no-unused-expression
new UserMockup();
},
{ message: /No redis client/ },
'Creating a model without having a redis client set did not throw an error.',
);
await args.setClient(nohm, redis); // this waits until the connection is ready before setting the client
t.notThrows(() => {
// tslint:disable-next-line:no-unused-expression
new UserMockup();
}, 'Creating a model with a redis client set threw an error.');
},
);
test.serial('setPrefix', (t) => {
const oldPrefix = nohm.prefix;
nohm.setPrefix('hurgel');
t.snapshot(nohm.prefix, 'Setting a custom prefix did not work as expected');
nohm.prefix = oldPrefix;
});
test.serial('create a new instance', async (t) => {
const user = new UserMockup();
user.property('name', 'createTest');
user.property('email', 'createTest@asdasd.de');
await t.notThrowsAsync(async () => {
await user.save();
}, 'Creating a user did not work.:' + user.errors);
const value = await hgetall(
nohm.client,
prefix + ':hash:UserMockup:' + user.id,
);
t.true(
value.name.toString() === 'createTest',
'The user name was not saved properly',
);
t.true(
value.visits.toString() === '0',
'The user visits were not saved properly',
);
t.true(
value.email.toString() === 'createTest@asdasd.de',
'The user email was not saved properly',
);
});
test.serial('remove', async (t) => {
const user = new UserMockup();
let testExists;
testExists = (what, key, callback) => {
redis.exists(key, (err, value) => {
t.true(!err, 'There was a redis error in the remove test check.');
t.true(
value === 0,
'Deleting a user did not work: ' + what + ', key: ' + key,
);
callback();
});
};
user.property('name', 'deleteTest');
user.property('email', 'deleteTest@asdasd.de');
await user.save();
const id = user.id;
await user.remove();
t.is(
user.id,
null,
'Removing an object from the db did not set the id to null',
);
return new Promise<void>((resolve, reject) => {
async.series(
[
(callback) => {
testExists('hashes', prefix + ':hash:UserMockup:' + id, callback);
},
(callback) => {
redis.sismember(
prefix + ':index:UserMockup:name:' + user.property('name'),
id,
(err, value) => {
t.true(
err === null && value === 0,
'Deleting a model did not properly delete the normal index.',
);
callback();
},
);
},
(callback) => {
redis.zscore(
prefix + ':scoredindex:UserMockup:visits',
id,
(err, value) => {
t.true(
err === null && value === null,
'Deleting a model did not properly delete the scored index.',
);
callback();
},
);
},
(callback) => {
testExists(
'uniques',
prefix + ':uniques:UserMockup:name:' + user.property('name'),
callback,
);
},
],
(err: any) => {
if (err) {
return reject(err);
} else {
resolve();
}
},
);
});
});
test.serial('idSets', async (t) => {
const user = new UserMockup();
let tempId = '';
user.property('name', 'idSetTest');
await user.save();
tempId = user.id as string;
const value = await sismember(
user.client,
prefix + ':idsets:' + user.modelName,
tempId,
);
t.is(value, 1, 'The userid was not part of the idset after saving.');
await user.remove();
const valueAfter = await sismember(
user.client,
prefix + ':idsets:' + user.modelName,
tempId,
);
t.is(valueAfter, 0, 'The userid was still part of the idset after removing.');
});
test.serial('update', async (t) => {
const user = new UserMockup();
user.property('name', 'updateTest1');
user.property('email', 'updateTest1@email.de');
await user.save();
user.property('name', 'updateTest2');
user.property('email', 'updateTest2@email.de');
await user.save();
const value = await hgetall(
user.client,
prefix + ':hash:UserMockup:' + user.id,
);
t.true(
value.name.toString() === 'updateTest2',
'The user name was not updated properly',
);
t.true(
value.email.toString() === 'updateTest2@email.de',
'The user email was not updated properly',
);
});
test.serial('indexes', async (t) => {
const user = new UserMockup();
user.property('name', 'indexTest');
user.property('email', 'indexTest@test.de');
user.property('country', 'indexTestCountry');
user.property('visits', 20);
await user.save();
const countryIndex = await sismember(
redis,
prefix + ':index:UserMockup:country:indexTestCountry',
user.id as string,
);
t.is(
countryIndex.toString(),
user.id,
'The country index did not have the user as one of its ids.',
);
const visitsScore = await zscore(
redis,
prefix + ':scoredindex:UserMockup:visits',
user.id as string,
);
t.is(
visitsScore,
user.property('visits'),
'The visits index did not have the correct score.',
);
const visitsIndex = await sismember(
redis,
prefix + ':index:UserMockup:visits:' + user.property('visits'),
user.id as string,
);
t.is(
visitsIndex.toString(),
user.id,
'The visits index did not have the user as one of its ids.',
);
});
test.serial('__updated internal property is updated correctly', async (t) => {
const user = new UserMockup();
await user.save();
user.property('name', 'hurgelwurz');
t.true(
// @ts-ignore properties is an internal property
user.properties.get('name').__updated === true,
'__updated was not ser on property `name`.',
);
user.property('name', 'test');
t.true(
// @ts-ignore properties is an internal property
user.properties.get('name').__updated === false,
"Changing a var manually to the original didn't reset the internal __updated var",
);
await user.remove();
const user2 = new UserMockup();
user2.property('name', 'hurgelwurz');
user2.propertyReset();
t.true(
// @ts-ignore properties is an internal property
user2.properties.get('name').__updated === false,
"Changing a var by propertyReset to the original didn't reset the internal __updated var",
);
});
test.serial("delete with id that doesn't exist", async (t) => {
const user = new UserMockup();
user.id = '987654321';
await t.throwsAsync(
async () => {
return user.remove();
},
{ message: 'not found' },
);
});
test.serial(
'allProperties with JSON produces same as property()',
async (t) => {
const user = new UserMockup();
user.property('json', { test: 1 });
user.property({
name: 'allPropertiesJson',
email: 'allPropertiesJson@test.de',
});
await user.save();
const testProps = user.allProperties();
t.deepEqual(
testProps.json,
user.property('json'),
'allProperties did not properly parse json properties',
);
},
);
/*
// TODO: Check which (if any) of these need to be re-enabled
test.serial('thisInCallbacks', async (t) => {
const user = new UserMockup();
let checkCounter = 0;
const checkSum = 11;
var checkThis = function (name, cb) {
return function () {
checkCounter++;
t.true(this instanceof UserMockup, '`this` is not set to the instance in ' + name);
if (checkCounter === checkSum) {
done();
} else if (typeof (cb) === 'function') {
cb();
}
};
};
t.plan(checkSum + 1);
var done = function () {
user.remove(checkThis('remove', function () {
t.end();
}));
};
user.save(checkThis('createError', function () {
user.property({
name: 'thisInCallbacks',
email: 'thisInCallbacks@test.de'
});
user.link(user, checkThis('link'));
user.save(checkThis('create', function () {
user.load(user.id, checkThis('load'));
user.find({ name: 'thisInCallbacks' }, checkThis('find'));
user.save(checkThis('update', function () {
user.property('email', 'asd');
user.save(checkThis('updateError'));
}));
user.belongsTo(user, checkThis('belongsTo'));
user.getAll('UserMockup', checkThis('getAll'));
user.numLinks('UserMockup', checkThis('numLinks'));
user.unlinkAll(null, checkThis('unlinkAll'));
}));
}));
});
*/
test.serial.cb('defaultAsFunction', (t) => {
const TestMockup = nohm.model('TestMockup', {
properties: {
time: {
defaultValue: () => {
return +new Date();
},
type: 'timestamp',
},
},
});
const test1 = new TestMockup();
setTimeout(() => {
const test2 = new TestMockup();
t.true(
typeof test1.property('time') === 'string',
'time of test1 is not a string',
);
t.true(
typeof test2.property('time') === 'string',
'time of test2 is not a string',
);
t.true(
test1.property('time') < test2.property('time'),
'time of test2 is not lower than test1',
);
t.end();
}, 10);
});
test.serial('defaultIdGeneration', async (t) => {
const TestMockup = nohm.model('TestMockup', {
properties: {
name: {
defaultValue: 'defaultIdGeneration',
type: 'string',
},
},
});
const test1 = new TestMockup();
await test1.save();
t.is(typeof test1.id, 'string', 'The generated id was not a string');
});
test.serial('factory', async (t) => {
t.plan(3);
const name = 'UserMockup';
const user = await nohm.factory(name);
t.is(
user.modelName,
name,
'Using the factory to get an instance did not work.',
);
try {
await nohm.factory(name, 1234124235);
} catch (err) {
t.is(
err.message,
'not found',
'Instantiating a user via factory with an id and callback did not try to load it',
);
}
const nonExistingModelName = 'doesnt exist';
try {
await nohm.factory(nonExistingModelName, 1234124235);
} catch (err) {
t.is(
err.message,
`Model '${nonExistingModelName}' not found.`,
'Instantiating a user via factory with an id and callback did not try to load it',
);
}
});
test.serial('factory with non-integer id', async (t) => {
const name = 'NonIncrement';
const obj = await nohm.factory(name);
obj.property('name', 'factory_non_integer_load');
await obj.save();
const obj2 = await nohm.factory(name, obj.id);
t.deepEqual(
obj2.allProperties(),
obj.allProperties(),
'The loaded object seems to have wrong properties',
);
});
test.serial.cb('purgeDB', (t) => {
t.plan(4);
// TODO: refactor this mess
const countKeys = (
countPrefix: string,
callback: (err: Error, count: number) => void,
) => {
redis.keys(countPrefix + '*', (err, keysFound) => {
callback(err, keysFound.length);
});
};
const tests: Array<any> = [];
Object.keys(nohm.prefix).forEach((key) => {
if (typeof nohm.prefix[key] === 'object') {
Object.keys(nohm.prefix[key]).forEach((innerKey) => {
tests.push(async.apply(countKeys, nohm.prefix[key][innerKey]));
});
} else {
tests.push(async.apply(countKeys, nohm.prefix[key]));
}
});
// make sure we have some keys by first saving a model and then counting keys. then we purge and count again.
const user = new UserMockup();
user.save().then(
() => {
async.series(tests, (err, numArr: Array<{}>) => {
t.true(!err, 'Unexpected redis error');
const countBefore = numArr.reduce((num: number, add: number) => {
return num + add;
}, 0);
t.true(
countBefore > 0,
'Database did not have any keys before purgeDb call',
);
nohm.purgeDb().then(() => {
async.series(tests, (errInner, numArrInner: Array<{}>) => {
t.true(!errInner, 'Unexpected redis error');
const countAfter = numArrInner.reduce(
(num: number, add: number) => {
return num + add;
},
0,
);
t.is(countAfter, 0, 'Database did have keys left after purging.');
t.end();
});
}, t.fail);
});
},
(err) => {
t.fail(err);
},
);
});
test.serial('no key left behind', async (t) => {
const user = await nohm.factory('UserMockup');
const user2 = await nohm.factory('UserMockup');
user2.property({
name: 'user2',
email: 'user2@test.com',
});
user.link(user2);
user2.link(user, 'father');
await cleanUpPromise(redis, prefix);
const remainingKeys = await keys(redis, prefix + ':*');
// at this point only meta info should be stored
t.is(remainingKeys.length, 0, 'Not all keys were removed before tests');
await user.save();
await user2.save();
user.unlink(user2);
await user2.save();
await user2.remove();
await user.remove();
const remainingKeys2 = await keys(redis, prefix + ':*');
t.snapshot(
remainingKeys2.sort(),
'Not all keys were removed from the database',
);
});
test.serial('temporary model definitions', async (t) => {
const user = await nohm.factory('UserMockup');
// new temporary model definition with same name
const TempUserMockup = nohm.model(
'UserMockup',
{
properties: {
well_shit: {
type: 'string',
},
},
},
true,
);
const newUser = new TempUserMockup();
const user2 = await nohm.factory('UserMockup');
t.deepEqual(user.allProperties(), user2.allProperties(), 'HURASDASF');
t.notDeepEqual(user.allProperties(), newUser.allProperties(), 'HURASDASF');
});
test.serial('register nohm model via ES6 class definition', async (t) => {
class ClassModel extends NohmModel {}
// @ts-ignore - in typescript you would just use static properties
ClassModel.modelName = 'ClassModel';
// @ts-ignore
ClassModel.definitions = {
name: {
type: 'string',
unique: true,
},
};
// @ts-ignore
const ModelCtor = nohm.register(ClassModel);
const instance = new ModelCtor();
const factoryInstance = await nohm.factory('ClassModel');
t.is(
instance.id,
null,
'Created model does not have null as id before saving',
);
t.is(
typeof ModelCtor.findAndLoad,
'function',
'Created model class does not have static findAndLoad().',
);
t.is(
factoryInstance.modelName,
'ClassModel',
'Created factory model does not have the correct modelName.',
);
t.is(
instance.modelName,
'ClassModel',
'Created model does not have the correct modelName.',
);
instance.property('name', 'registerES6Test');
await instance.save();
t.not(instance.id, null, 'Created model does not have an id after saving.');
const staticLoad = await ModelCtor.load(instance.id);
t.deepEqual(
staticLoad.allProperties(),
instance.allProperties(),
'register().load failed.',
);
const staticSort = await ModelCtor.sort({ field: 'name' }, [
instance.id as string,
]);
t.deepEqual(staticSort, [instance.id], 'register().sort failed.');
const staticFind = await ModelCtor.find({
name: instance.property('name'),
});
t.deepEqual(staticFind, [instance.id], 'register().find failed.');
const staticFindAndLoad = await ModelCtor.findAndLoad({
name: instance.property('name'),
});
t.deepEqual(
staticFindAndLoad[0].allProperties(),
instance.allProperties(),
'register().findAndLoad failed.',
);
t.is(
await ModelCtor.remove(instance.id),
undefined,
'register().findAndLoad failed.',
);
t.deepEqual(
await ModelCtor.findAndLoad({
name: instance.property('name'),
}),
[],
'register().findAndLoad after remove failed.',
);
});
test.serial('return value of .property() with object', async (t) => {
const user = new UserMockup();
const object = {
name: 'propertyWithObjectReturn',
email: 'propertyWithObjectReturn@test.de',
visits: '1',
};
const properties = user.property(object);
const compareObject = {
name: object.name,
email: object.email,
visits: 1,
};
t.deepEqual(
compareObject,
properties,
'The returned properties were not correct.',
);
});
test.serial('id always stringified', async (t) => {
const user = new UserMockup();
t.is(user.id, null, 'Base state of id is not null');
user.id = 'asd';
t.is(user.id, 'asd', 'Basic string setter failed');
// @ts-ignore - specifically testing the wrong input type
user.id = 213;
t.is(user.id, '213', 'Casting string setter failed');
});
test.serial('isLoaded', async (t) => {
const user = await nohm.factory('NonIncrement');
user.property('name', 'isLoadedUser');
t.is(user.isLoaded, false, 'isLoaded true in base state.');
user.id = 'asd';
t.is(user.isLoaded, false, 'isLoaded true after setting manual id');
await user.save();
t.is(user.isLoaded, true, 'isLoaded true after setting manual id');
const id = user.id;
const loadUser = await nohm.factory('NonIncrement');
t.is(loadUser.isLoaded, false, 'isLoaded true in base state on loadUser.');
await loadUser.load(id);
t.is(loadUser.isLoaded, true, 'isLoaded false after load()');
loadUser.id = 'asdasd';
t.is(
loadUser.isLoaded,
false,
'isLoaded true after setting manual id on loaded user',
);
});
test.serial('isDirty', async (t) => {
const user = await nohm.factory('UserMockup');
const other = await nohm.factory('NonIncrement');
t.is(user.isDirty, false, 'user.isDirty true in base state.');
t.is(other.isDirty, false, 'other.isDirty true in base state.');
other.link(user);
t.is(user.isDirty, false, 'user.isDirty true after other.link(user).');
t.is(other.isDirty, true, 'other.isDirty false after other.link(user).');
user.property('name', 'isDirtyUser');
t.is(user.isDirty, true, 'user.isDirty false after first edit.');
user.property('email', 'isDirtyUser@test.de');
t.is(user.isDirty, true, 'user.isDirty false after second.');
await other.save();
t.is(user.isDirty, false, 'user.isDirty true after saving.');
t.is(other.isDirty, false, 'other.isDirty true after saving.');
user.id = user.id;
t.is(user.isDirty, false, 'user.isDirty true after same id change.');
t.not(other.id, 'new_id', 'other.id was already test value Oo');
other.id = 'new_id';
t.is(other.id, 'new_id', 'other.id change failed.');
t.is(other.isDirty, true, 'other.isDirty false after id change.');
const loadUser = await nohm.factory('UserMockup');
await loadUser.load(user.id);
t.is(loadUser.isDirty, false, 'loadUser.isDirty was true after load()');
});
test.serial('create-only failure attempt without load_pure', async (t) => {
nohm.model('withoutLoadPureCreateOnlyModel', {
properties: {
createdAt: {
defaultValue: () => Date.now() + ':' + Math.random(),
type: (_a, _b, oldValue) => oldValue, // never change the value after creation
},
},
});
const loadPure = await nohm.factory('withoutLoadPureCreateOnlyModel');
const initialValue = loadPure.property('createdAt');
loadPure.property('createdAt', 'asdasd');
t.is(
loadPure.property('createdAt'),
initialValue,
'Behavior failed to prevent property change',
);
await loadPure.save();
const controlLoadPure = await nohm.factory('withoutLoadPureCreateOnlyModel');
await controlLoadPure.load(loadPure.id);
t.not(
controlLoadPure.property('createdAt'),
initialValue,
'create-only loading produced non-cast value (should only happen with load_pure)',
);
});
test.serial('loadPure', async (t) => {
nohm.model('loadPureModel', {
properties: {
incrementOnChange: {
defaultValue: 0,
load_pure: true,
type() {
return (
1 + parseInt(this.property('incrementOnChange'), 10)
).toString();
},
},
createdAt: {
defaultValue: () => Date.now() + ':' + Math.random(),
load_pure: true,
type: (_a, _b, oldValue) => oldValue, // never change the value after creation
},
},
});
const loadPure = await nohm.factory('loadPureModel');
const initialCreatedAt = loadPure.property('createdAt');
loadPure.property('createdAt', 'asdasd');
loadPure.property('incrementOnChange', 'asdasd');
loadPure.property('incrementOnChange', 'asdasd');
const incrementedTwice = '2';
t.is(
loadPure.property('incrementOnChange'),
incrementedTwice,
'incrementedTwice change did not work',
);
t.is(
loadPure.property('createdAt'),
initialCreatedAt,
'Behavior failed to prevent property change',
);
await loadPure.save();
const controlLoadPure = await nohm.factory('loadPureModel');
await controlLoadPure.load(loadPure.id);
t.is(
controlLoadPure.property('incrementOnChange'),
incrementedTwice,
'incrementedTwice was changed during load',
);
t.is(
controlLoadPure.property('createdAt'),
initialCreatedAt,
'create-only loading produced typecast value',
);
});
test.serial('allProperties() cache is reset on propertyReset()', async (t) => {
const user = await nohm.factory('UserMockup');
const name = 'allPropertyCacheEmpty';
const email = 'allPropertyCacheEmpty@test.de';
user.property({
name,
email,
});
const allProps = user.allProperties();
user.propertyReset();
t.not(user.property('name'), name, 'Name was not reset.');
t.is(allProps.name, name, 'Name was reset in test object.');
const controlAllProps = user.allProperties();
t.notDeepEqual(
allProps,
controlAllProps,
'allProperties cache was not reset properly',
);
});
test.serial('id with : should fail', async (t) => {
const wrongIdModel = nohm.model(
'wrongIdModel',
{
properties: {
name: {
type: 'string',
},
},
idGenerator: () => {
return 'foo:bar';
},
},
true,
);
const instance = new wrongIdModel();
try {
await instance.save();
} catch (e) {
t.is(
e.message,
'Nohm IDs cannot contain the character ":". Please change your idGenerator!',
'Error thrown by wrong id was wrong.',
);
}
});
test.serial(
'manually setting id should allow saving with uniques',
async (t) => {
// see https://github.com/maritz/nohm/issues/82 for details
const props = {
name: 'manualIdWithuniques',
email: 'manualIdWithuniques@example.com',
};
const origInstance = new UserMockup();
origInstance.property(props);
await origInstance.save();
const instance = new UserMockup();
instance.id = origInstance.id;
instance.property(props);
await t.notThrowsAsync(async () => {
return instance.save();
});
},
);
test.serial('helpers.checkEqual generic tests', (t) => {
const checkEqual = require('../ts/helpers').checkEqual;
t.is(checkEqual(false, true), false, 'false, true');
t.is(checkEqual(true, false), false, 'true, false');
t.true(checkEqual(true, true), 'true, true');
t.true(checkEqual(false, false), 'false, false');
const test1 = new UserMockup();
const test2 = new UserMockup();
t.is(
checkEqual(test1, test2),
false,
`Model instances that don't have an id were identified as equal.`,
);
test1.id = 'asd';
test2.id = test1.id;
t.true(
checkEqual(test1, test2),
`Model instances that DO have an id were identified as NOT equal.`,
);
});
test.serial(
'helpers.checkEqual uses Object.hasOwnProperty for safety',
async (t) => {
const checkEqual = require('../ts/helpers').checkEqual;
const test1 = Object.create(null);
const test2 = {};
// checkEqual throws an error here if it's not using Object.hasOwnProperty()
t.is(checkEqual(test1, test2), false, 'Something is wrong');
},
);
test.serial('helpers.callbackError', (t) => {
const callbackError = require('../ts/helpers').callbackError;
t.throws(
() => {
// tslint:disable-next-line:no-empty
callbackError(() => {});
},
{
message: /^Callback style has been removed. Use the returned promise\.$/,
},
'Does not throw when given only function',
);
t.throws(
() => {
// tslint:disable-next-line:no-empty
callbackError('foo', 'bar', 'baz', () => {});
},
{
message: /^Callback style has been removed. Use the returned promise\.$/,
},
'Does not throw when last of 4 is function.',
);
t.notThrows(() => {
callbackError('foo', 'bar', 'baz');
}, 'Error thrown even though arguments contained no function.');
t.notThrows(() => {
// tslint:disable-next-line:no-empty
callbackError(() => {}, 'bar', 'baz');
}, 'Error thrown even though last argument was not a function.');
});
test('nohm class constructors', (t) => {
const mockRedis = td.object(redis);
const withClient = new NohmClass({ client: mockRedis });
t.is(withClient.client, mockRedis);
t.true(new NohmClass({ publish: true }).getPublish());
t.false(new NohmClass({ publish: false }).getPublish());
const mockPublishRedis = td.object(redis);
const withPublishClient = new NohmClass({ publish: mockPublishRedis });
t.true(withPublishClient.getPublish());
t.is(withPublishClient.getPubSubClient(), mockPublishRedis);
});
test('setClient with different client connection states', (t) => {
const subject = new NohmClass({});
t.is(subject.client, undefined);
subject.setClient();
t.false(
subject.client.connected,
'Redis client is immediately connected when not passing a client.',
);
// node_redis
// not connected yet
const mockRedis = {
connected: false,
};
td.replace(subject, 'logError');
subject.setClient(mockRedis as any);
t.is(subject.client, mockRedis);
td.verify(
subject.logError(`WARNING: setClient() received a redis client that is not connected yet.
Consider waiting for an established connection before setting it. Status (if ioredis): undefined
, connected (if node_redis): false`),
);
// connected
mockRedis.connected = true;
td.replace(subject, 'logError', () => {
throw new Error('Should not be called');
});
subject.setClient(mockRedis as any);
t.is(subject.client, mockRedis);
// ioredis
// not connected yet
const mockIORedis = {
status: 'close',
};
td.replace(subject, 'logError');
subject.setClient(mockIORedis as any);
t.is(subject.client, mockIORedis as any);
td.verify(
subject.logError(`WARNING: setClient() received a redis client that is not connected yet.
Consider waiting for an established connection before setting it. Status (if ioredis): close
, connected (if node_redis): undefined`),
);
// connected
mockIORedis.status = 'ready';
td.replace(subject, 'logError', () => {
throw new Error('Should not be called');
});
subject.setClient(mockRedis as any);
t.is(subject.client, mockRedis);
});
test.serial('logError', (t) => {
t.notThrows(() => {
td.replace(console, 'error', () => {
throw new Error('Should not be called');
});
nohm.logError(null);
(nohm.logError as any)();
const logStubThrows = td.replace(console, 'error');
nohm.logError('foo');
td.verify(logStubThrows({ message: 'foo', name: 'Nohm Error' }));
nohm.logError(new Error('foo'));
td.verify(logStubThrows({ message: new Error('foo'), name: 'Nohm Error' }));
});
}); | the_stack |
import {
Aspect,
Aspected,
Compiler,
Parser,
ViewBehaviorFactory,
ViewTemplate,
} from "@microsoft/fast-element";
import {
Attribute,
DefaultTreeCommentNode,
DefaultTreeElement,
DefaultTreeNode,
DefaultTreeParentNode,
DefaultTreeTextNode,
parse,
parseFragment,
} from "parse5";
import { AttributeBindingOp, Op, OpType } from "./op-codes.js";
/**
* Cache the results of template parsing.
*/
const opCache: Map<ViewTemplate, Op[]> = new Map();
interface Visitor {
visit?: (node: DefaultTreeNode) => void;
leave?: (node: DefaultTreeNode) => void;
}
declare module "parse5" {
interface DefaultTreeElement {
isDefinedCustomElement?: boolean;
}
}
/**
* Traverses a tree of nodes depth-first, invoking callbacks from visitor for each node as it goes.
* @param node - the node to traverse
* @param visitor - callbacks to be invoked during node traversal
*/
function traverse(node: DefaultTreeNode | DefaultTreeParentNode, visitor: Visitor) {
// Templates parsed with `parse()` are parsed as full documents and will contain
// html, body tags whether the template contains them or not. Skip over visiting and
// leaving these elements if there is no source-code location, because that indicates
// they are not in the template string.
const shouldVisit = (node as DefaultTreeElement).sourceCodeLocation !== null;
if (visitor.visit && shouldVisit) {
visitor.visit(node);
}
if ("childNodes" in node) {
const { childNodes } = node;
for (const child of childNodes) {
traverse(child, visitor);
}
}
if (node.nodeName === "template") {
traverse((node as any).content, visitor);
}
if (visitor.leave && shouldVisit) {
visitor.leave(node);
}
}
/**
* Test if a node is a comment node.
* @param node - the node to test
*/
function isCommentNode(node: DefaultTreeNode): node is DefaultTreeCommentNode {
return node.nodeName === "#comment";
}
/**
* Test if a node is a text node.
* @param node - the node to test
*/
function isTextNode(node: DefaultTreeNode): node is DefaultTreeTextNode {
return node.nodeName === "#text";
}
/**
* Test if a node is an element node
* @param node - the node to test
*/
function isElementNode(node: DefaultTreeNode): node is DefaultTreeElement {
return (node as DefaultTreeElement).tagName !== undefined;
}
function isDefaultTreeParentNode(node: any): node is DefaultTreeParentNode {
return Array.isArray(node.childNodes);
}
function firstElementChild(node: DefaultTreeParentNode): DefaultTreeElement | null {
return (
(node.childNodes.find(child => isElementNode(child)) as
| DefaultTreeElement
| undefined) || null
);
}
/**
* Parses a template into a set of operation instructions
* @param template - The template to parse
*/
export function parseTemplateToOpCodes(template: ViewTemplate): Op[] {
const cached: Op[] | undefined = opCache.get(template);
if (cached !== undefined) {
return cached;
}
const { html } = template;
if (typeof html !== "string") {
throw new Error(
"@microsoft/fast-ssr only supports rendering a ViewTemplate with a string source."
);
}
/**
* Typescript thinks that `html` is a string | HTMLTemplateElement inside the functions defined
* below, so store in a new var that is just a string type
*/
const templateString = html;
const codes = parseStringToOpCodes(templateString, template.factories);
opCache.set(template, codes);
return codes;
}
export function parseStringToOpCodes(
/**
* The string to parse
*/
templateString: string,
factories: Record<string, ViewBehaviorFactory>,
/**
* Adjust behavior when parsing a template used
* as a custom element's template
*/
forCustomElement = false
): Op[] {
const nodeTree = (forCustomElement ? parseFragment : parse)(templateString, {
sourceCodeLocationInfo: true,
});
if (!isDefaultTreeParentNode(nodeTree)) {
// I'm not sure when exactly this is encountered but the type system seems to say it's possible.
throw new Error(`Error parsing template`);
}
// TypeScript gets confused about what 'nodeTree' is.
// Creating a new var clears that up.
let tree = nodeTree as DefaultTreeParentNode;
/**
* Tracks the offset location in the source template string where the last
* flushing / skip took place.
*/
let lastOffset: number | undefined = 0;
let finalOffset: number = templateString.length;
/**
* Collection of op codes
*/
const opCodes: Op[] = [];
/**
* Parses an Element node, pushing all op codes for the element into
* the collection of ops for the template
* @param node - The element node to parse
*/
function parseElementNode(node: DefaultTreeElement): void {
// Track whether the opening tag of an element should be augmented.
// All constructable custom elements will need to be augmented,
// as well as any element with attribute bindings
let augmentOpeningTag = false;
const { tagName } = node;
const ctor: typeof HTMLElement | undefined = customElements.get(node.tagName);
node.isDefinedCustomElement = !!ctor;
// Sort attributes by whether they're related to a binding or if they have
// static value
const attributes: {
static: Map<string, string>;
dynamic: Map<Attribute, AttributeBindingOp>;
} = node.attrs.reduce(
(prev, current) => {
const parsed = Parser.parse(current.value, factories);
if (parsed) {
const factory = Compiler.aggregate(parsed) as ViewBehaviorFactory &
Aspected;
// Guard against directives like children, ref, and slotted
if (factory.binding && factory.aspectType !== Aspect.content) {
prev.dynamic.set(current, {
type: OpType.attributeBinding,
binding: factory.binding,
aspect: factory.aspectType,
target: factory.targetAspect,
useCustomElementInstance: Boolean(
node.isDefinedCustomElement
),
});
}
} else {
prev.static.set(current.name, current.value);
}
return prev;
},
{
static: new Map<string, string>(),
dynamic: new Map<Attribute, AttributeBindingOp>(),
}
);
// Emit a CustomElementOpenOp when the custom element is defined
if (ctor !== undefined) {
augmentOpeningTag = true;
opCodes.push({
type: OpType.customElementOpen,
tagName,
ctor,
staticAttributes: attributes.static,
});
} else if (node.tagName === "template") {
// Template elements need special handling due to the host directive behavior
// when used as the root element in a custom element template
// (https://www.fast.design/docs/fast-element/using-directives#host-directives).
flushTo(node.sourceCodeLocation?.startTag.startOffset);
opCodes.push({
type: OpType.templateElementOpen,
staticAttributes: attributes.static,
dynamicAttributes: Array.from(attributes.dynamic.values()),
});
skipTo(node.sourceCodeLocation!.startTag.endOffset);
return;
}
// Iterate attributes in-order so that codes can be pushed for dynamic attributes in-order.
// All dynamic attributes will be rendered from an AttributeBindingOp. Additionally, When the
// node is a custom element, all static attributes will be rendered via the CustomElementOpenOp,
// so this code skips over static attributes in that case.
for (const attr of node.attrs) {
if (attributes.dynamic.has(attr)) {
const location = node.sourceCodeLocation!.attrs[attr.name];
const code = attributes.dynamic.get(attr)!;
flushTo(location.startOffset);
augmentOpeningTag = true;
opCodes.push(code);
skipTo(location.endOffset);
} else if (!attributes.static.has(attr.name)) {
// Handle interpolated directives like children, ref, and slotted
const parsed = Parser.parse(attr.value, factories);
if (parsed) {
const location = node.sourceCodeLocation!.attrs[attr.name];
const factory = Compiler.aggregate(parsed);
flushTo(location.startOffset);
opCodes.push({ type: OpType.viewBehaviorFactory, factory });
skipTo(location.endOffset);
}
} else if (node.isDefinedCustomElement) {
const location = node.sourceCodeLocation!.attrs[attr.name];
flushTo(location.startOffset);
skipTo(location.endOffset);
}
}
if (augmentOpeningTag && node.tagName !== "template") {
if (ctor) {
flushTo(node.sourceCodeLocation!.startTag.endOffset - 1);
opCodes.push({ type: OpType.customElementAttributes });
flush(">");
skipTo(node.sourceCodeLocation!.startTag.endOffset);
} else {
flushTo(node.sourceCodeLocation!.startTag.endOffset);
}
}
if (ctor !== undefined) {
opCodes.push({ type: OpType.customElementShadow });
}
}
/**
* Flushes a string value to op codes
* @param value - The value to flush
*/
function flush(value: string): void {
const last = opCodes[opCodes.length - 1];
if (last?.type === OpType.text) {
last.value += value;
} else {
opCodes.push({ type: OpType.text, value });
}
}
/**
* Flush template content from lastIndex to provided offset
* @param offset - the offset to flush to
*/
function flushTo(offset: number = finalOffset) {
if (lastOffset === undefined) {
throw new Error(
`Cannot flush template content from a last offset that is ${typeof lastOffset}.`
);
}
const prev = lastOffset;
lastOffset = offset;
const value = templateString.substring(prev, offset);
if (value !== "") {
flush(value);
}
}
function skipTo(offset: number) {
if (lastOffset === undefined) {
throw new Error("Could not skip from an undefined offset");
}
if (offset < lastOffset) {
throw new Error(`offset must be greater than lastOffset.
offset: ${offset}
lastOffset: ${lastOffset}
`);
}
lastOffset = offset;
}
/**
* FAST leverages any <template> element that is a firstElementChild
* of the template as a binding target for any directives on the
* <template>. This block implements that behavior.
*/
if (forCustomElement) {
const fec = firstElementChild(tree);
if (fec !== null && fec.tagName === "template") {
tree = fec as DefaultTreeParentNode;
const location = fec.sourceCodeLocation!;
finalOffset = location.endTag.endOffset;
lastOffset = location.startTag.startOffset;
}
}
traverse(tree, {
visit(node: DefaultTreeNode): void {
if (isCommentNode(node) || isTextNode(node)) {
const parsed = Parser.parse(
(node as DefaultTreeCommentNode)?.data ||
(node as DefaultTreeTextNode).value,
factories
);
if (parsed) {
flushTo(node.sourceCodeLocation!.startOffset);
for (const part of parsed) {
if (typeof part === "string") {
flush(part);
} else {
opCodes.push({
type: OpType.viewBehaviorFactory,
factory: part,
});
}
}
skipTo(node.sourceCodeLocation!.endOffset);
}
} else if (isElementNode(node)) {
parseElementNode(node);
}
},
leave(node: DefaultTreeNode): void {
if (isElementNode(node)) {
if (node.isDefinedCustomElement) {
opCodes.push({ type: OpType.customElementClose });
} else if (node.tagName === "template") {
flushTo(node.sourceCodeLocation?.endTag.startOffset);
opCodes.push({ type: OpType.templateElementClose });
skipTo(node.sourceCodeLocation!.endTag.endOffset);
}
}
},
});
// Flush the remaining string content before returning op codes.
flushTo();
return opCodes;
} | the_stack |
import { errors } from '@tanker/core';
import type { Tanker, b64string } from '@tanker/core';
import { encryptionV4, utils } from '@tanker/crypto';
import { getPublicIdentity } from '@tanker/identity';
import { expect, sinon, BufferingObserver, makeTimeoutPromise, isIE } from '@tanker/test-utils';
import { SlicerStream, MergerStream, Writable } from '@tanker/stream-base';
import type { AppHelper, TestArgs, TestResourceSize } from './helpers';
import { expectProgressReport, expectType, expectDeepEqual, pipeStreams } from './helpers';
export const generateUploadTests = (args: TestArgs) => {
// Detection of: Edge | Edge iOS | Edge Android - but not Edge (Chromium-based)
const isEdge = () => /(edge|edgios|edga)\//i.test(typeof navigator === 'undefined' ? '' : navigator.userAgent);
// Some sizes may not be tested on some platforms (e.g. 'big' on Safari)
const forEachSize = (sizes: Array<TestResourceSize>, fun: (size: TestResourceSize) => void) => {
const availableSizes = Object.keys(args.resources);
return sizes.filter(size => availableSizes.includes(size)).forEach(fun);
};
describe('binary file upload and download', () => {
let appHelper: AppHelper;
let aliceIdentity: b64string;
let aliceLaptop: Tanker;
let bobIdentity: b64string;
let bobLaptop: Tanker;
let bobPublicIdentity: b64string;
before(async () => {
({ appHelper } = args);
const appId = utils.toBase64(appHelper.appId);
aliceIdentity = await appHelper.generateIdentity();
aliceLaptop = args.makeTanker(appId);
await aliceLaptop.start(aliceIdentity);
await aliceLaptop.registerIdentity({ passphrase: 'passphrase' });
bobIdentity = await appHelper.generateIdentity();
bobPublicIdentity = await getPublicIdentity(bobIdentity);
bobLaptop = args.makeTanker(appId);
await bobLaptop.start(bobIdentity);
await bobLaptop.registerIdentity({ passphrase: 'passphrase' });
});
after(async () => {
await Promise.all([
aliceLaptop.stop(),
bobLaptop.stop(),
]);
});
['gcs', 's3'].forEach(storage => {
describe(storage, () => {
if (storage === 's3') {
before(() => appHelper.setS3());
after(() => appHelper.unsetS3());
}
forEachSize(['empty', 'small', 'medium'], size => {
it(`can upload and download a ${size} file`, async () => {
const { type: originalType, resource: clear } = args.resources[size][2]!;
const fileId = await aliceLaptop.upload(clear);
const decrypted = await aliceLaptop.download(fileId);
expectType(decrypted, originalType);
expectDeepEqual(decrypted, clear);
});
});
const expectUploadProgressReport = (onProgress: sinon.SinonSpy, clearSize: number) => {
const encryptedSize = encryptionV4.getEncryptedSize(clearSize, encryptionV4.defaultMaxEncryptedChunkSize);
let chunkSize;
if (storage === 's3') {
chunkSize = 5 * 1024 * 1024;
} else if (isEdge()) {
chunkSize = encryptedSize;
} else {
chunkSize = encryptionV4.defaultMaxEncryptedChunkSize;
}
expectProgressReport(onProgress, encryptedSize, chunkSize);
onProgress.resetHistory();
};
it('can report progress at simple upload and download', async () => {
const onProgress = sinon.fake();
const { type: originalType, resource: clear, size: clearSize } = args.resources.medium[2]!;
const fileId = await aliceLaptop.upload(clear, { onProgress });
expectUploadProgressReport(onProgress, clearSize);
const decrypted = await aliceLaptop.download(fileId, { onProgress });
expectType(decrypted, originalType);
expectDeepEqual(decrypted, clear);
expectProgressReport(onProgress, clearSize, encryptionV4.defaultMaxEncryptedChunkSize - encryptionV4.overhead);
});
it('can report progress at stream upload and download', async () => {
const onProgress = sinon.fake();
const { type, resource: clear, size: clearSize } = args.resources.medium[0]!;
const uploadStream = await aliceLaptop.createUploadStream(clearSize, { onProgress });
const fileId = uploadStream.resourceId;
const slicer = new SlicerStream({ source: clear });
await pipeStreams({ streams: [slicer, uploadStream], resolveEvent: 'finish' });
expectUploadProgressReport(onProgress, clearSize);
const downloadStream = await aliceLaptop.createDownloadStream(fileId, { onProgress });
const merger = new MergerStream({ type, ...downloadStream.metadata });
const decrypted = await pipeStreams<Uint8Array>({ streams: [downloadStream, merger], resolveEvent: 'data' });
expectType(decrypted, type);
expectDeepEqual(decrypted, clear);
expectProgressReport(onProgress, clearSize, encryptionV4.defaultMaxEncryptedChunkSize - encryptionV4.overhead);
});
it('can download a file shared at upload', async () => {
const { type: originalType, resource: clear } = args.resources.small[2]!;
const fileId = await aliceLaptop.upload(clear, { shareWithUsers: [bobPublicIdentity] });
const decrypted = await bobLaptop.download(fileId);
expectType(decrypted, originalType);
expectDeepEqual(decrypted, clear);
});
it('can download a file shared via upload with streams', async () => {
const { type, resource: clear, size: clearSize } = args.resources.medium[0]!;
const uploadStream = await aliceLaptop.createUploadStream(clearSize, { shareWithUsers: [bobPublicIdentity] });
const fileId = uploadStream.resourceId;
const slicer = new SlicerStream({ source: clear });
await pipeStreams({ streams: [slicer, uploadStream], resolveEvent: 'finish' });
const decrypted = await bobLaptop.download(fileId, { type });
expectDeepEqual(decrypted, clear);
});
it('can download with streams a file shared via upload', async () => {
const { type, resource: clear } = args.resources.medium[0]!;
const fileId = await aliceLaptop.upload(clear, { shareWithUsers: [bobPublicIdentity] });
const downloadStream = await bobLaptop.createDownloadStream(fileId);
const merger = new MergerStream({ type, ...downloadStream.metadata });
const decrypted = await pipeStreams<Uint8Array>({ streams: [downloadStream, merger], resolveEvent: 'data' });
expectType(decrypted, type);
expectDeepEqual(decrypted, clear);
});
it('can upload a file and not share with self', async () => {
const { type: originalType, resource: clear } = args.resources.small[2]!;
const fileId = await aliceLaptop.upload(clear, { shareWithUsers: [bobPublicIdentity], shareWithSelf: false });
await expect(aliceLaptop.download(fileId)).to.be.rejectedWith(errors.InvalidArgument);
const decrypted = await bobLaptop.download(fileId);
expectType(decrypted, originalType);
expectDeepEqual(decrypted, clear);
});
it('can upload a file and share with a group', async () => {
const { type: originalType, resource: clear } = args.resources.small[2]!;
const groupId = await aliceLaptop.createGroup([bobPublicIdentity]);
const fileId = await aliceLaptop.upload(clear, { shareWithGroups: [groupId] });
const decrypted = await bobLaptop.download(fileId);
expectType(decrypted, originalType);
expectDeepEqual(decrypted, clear);
});
it('can share a file after upload', async () => {
const { type: originalType, resource: clear } = args.resources.small[2]!;
const fileId = await aliceLaptop.upload(clear);
await aliceLaptop.share([fileId], { shareWithUsers: [bobPublicIdentity] });
const decrypted = await bobLaptop.download(fileId);
expectType(decrypted, originalType);
expectDeepEqual(decrypted, clear);
});
it('throws InvalidArgument if downloading a non existing file', async () => {
const nonExistingFileId = 'AAAAAAAAAAAAAAAAAAAAAA==';
await expect(aliceLaptop.download(nonExistingFileId)).to.be.rejectedWith(errors.InvalidArgument);
});
it('throws InvalidArgument if giving an obviously wrong fileId', async () => {
const promises = [undefined, null, 'not a resourceId', [], {}].map(async (invalidFileId, i) => {
// @ts-expect-error Giving invalid options
await expect(aliceLaptop.download(invalidFileId), `failed test #${i}`).to.be.rejectedWith(errors.InvalidArgument);
});
await Promise.all(promises);
});
it('throws InvalidArgument if given an invalid clearSize', async () => {
const promises = [undefined, null, 'not a clearSize', [], {}, -1].map(async (invalidClearSize, i) => {
// @ts-expect-error Giving invalid clearSize
await expect(aliceLaptop.createUploadStream(invalidClearSize), `failed test #${i}`).to.be.rejectedWith(errors.InvalidArgument);
});
await Promise.all(promises);
});
it('throws InvalidArgument if given too much data', async () => {
const clearSize = 50;
const uploadStream = await aliceLaptop.createUploadStream(clearSize);
await expect(new Promise((resolve, reject) => {
uploadStream.on('error', reject);
uploadStream.on('finish', resolve);
uploadStream.write(new Uint8Array(clearSize + 1));
uploadStream.end();
})).to.be.rejectedWith(errors.InvalidArgument);
});
// no need to check for edge with gcs (the upload ends in one request anyway)
// we chose to disable back pressure tests on s3 because they were hanging unexpectidly
// we will investigate the issue and enable them again.
const canTestBackPressure = !(isEdge() && storage === 'gcs') && !isIE() && storage !== 's3';
if (canTestBackPressure) {
const KB = 1024;
const MB = KB * KB;
describe('UploadStream', () => {
// we buffer data upload depending on the cloud provider
const maxBufferedLength = storage === 's3' ? 40 * MB : 15 * MB;
// more chunk are needed for s3 since we need one more resizer
const nbChunk = storage === 's3' ? 8 : 4;
const chunkSize = 7 * MB;
const inputSize = nbChunk * chunkSize;
it(`buffers at most ${maxBufferedLength / MB}MB when uploading ${inputSize / MB}MB split in ${nbChunk} chunks`, async function () { // eslint-disable-line func-names
this.timeout(60000);
const chunk = new Uint8Array(chunkSize);
const bufferCounter = new BufferingObserver();
const timeout = makeTimeoutPromise(50);
let prevCount = 0;
const uploadStream = await aliceLaptop.createUploadStream(inputSize, {
onProgress: progressReport => {
const newBytes = progressReport.currentBytes - prevCount;
prevCount = progressReport.currentBytes;
bufferCounter.incrementOutputAndSnapshot(newBytes);
},
});
// hijack tail write to lock upload until stream is flooded
// eslint-disable-next-line no-underscore-dangle
const write = uploadStream._tailStream._write.bind(uploadStream._tailStream);
// eslint-disable-next-line no-underscore-dangle
uploadStream._tailStream._write = async (...vals) => {
await timeout.promise;
write(...vals);
};
const continueWriting = () => {
do {
// flood every stream before unlocking writing end
timeout.reset();
bufferCounter.incrementInput(chunk.length);
} while (uploadStream.write(chunk) && bufferCounter.inputWritten < inputSize);
if (bufferCounter.inputWritten >= inputSize) {
uploadStream.end();
}
};
await new Promise((resolve, reject) => {
uploadStream.on('error', reject);
uploadStream.on('drain', continueWriting);
uploadStream.on('finish', resolve);
continueWriting();
});
bufferCounter.snapshots.forEach(bufferedLength => {
expect(bufferedLength).to.be.at.most(maxBufferedLength + encryptionV4.defaultMaxEncryptedChunkSize, `buffered data exceeds threshold max buffered size: got ${bufferedLength}, max ${maxBufferedLength})`);
});
});
});
describe('DownloadStream', () => {
const storageChunkDownloadSize = 1 * MB;
const maxBufferedLength = 2 * storageChunkDownloadSize + 5 * encryptionV4.defaultMaxEncryptedChunkSize;
const payloadSize = 30;
it(`buffers at most ${maxBufferedLength / MB}MB when downloading ${payloadSize}MB`, async function () { // eslint-disable-line func-names
this.timeout(60000);
const inputSize = payloadSize * MB;
const bufferCounter = new BufferingObserver();
const resourceId = await aliceLaptop.upload(new Uint8Array(inputSize));
const timeout = makeTimeoutPromise(700);
const downloadStream = await aliceLaptop.createDownloadStream(resourceId);
// hijack push to control size of output buffer
// eslint-disable-next-line no-underscore-dangle
const push = downloadStream._headStream.push.bind(downloadStream._headStream);
// eslint-disable-next-line no-underscore-dangle
downloadStream._headStream.push = data => {
timeout.reset();
if (data) {
bufferCounter.incrementInput(data.length);
}
return push(data);
};
const slowWritable = new Writable({
objectMode: true,
highWaterMark: 1,
write: async (buffer, _, done) => {
// flood every stream before unlocking writing end
await timeout.promise;
bufferCounter.incrementOutputAndSnapshot(buffer.length);
done();
},
});
await new Promise((resolve, reject) => {
downloadStream.on('error', reject);
downloadStream.on('end', resolve);
downloadStream.pipe(slowWritable);
});
bufferCounter.snapshots.forEach(bufferedLength => {
expect(bufferedLength).to.be.at.most(maxBufferedLength, `buffered data exceeds threshold max buffered size: got ${bufferedLength}, max buffered size ${maxBufferedLength}`);
});
});
});
}
});
});
});
}; | the_stack |
* @module WebGL
*/
import { assert } from "@itwin/core-bentley";
import { AttributeMap } from "../AttributeMap";
import { TextureUnit } from "../RenderFlags";
import {
FragmentShaderBuilder, FragmentShaderComponent, ProgramBuilder, ShaderBuilderFlags, VariableType, VertexShaderBuilder, VertexShaderComponent,
} from "../ShaderBuilder";
import { System } from "../System";
import { IsInstanced } from "../TechniqueFlags";
import { TechniqueId } from "../TechniqueId";
import { addColor } from "./Color";
import { addEdgeContrast } from "./Edge";
import { addFrustum, addShaderFlags } from "./Common";
import { unquantize2d } from "./Decode";
import { addHiliter } from "./FeatureSymbology";
import { addWhiteOnWhiteReversal } from "./Fragment";
import { addLineCode as addLineCodeUniform, addLineWeight, addModelViewMatrix, addProjectionMatrix } from "./Vertex";
import { addModelToWindowCoordinates, addViewport } from "./Viewport";
const checkForDiscard = "return discardByLineCode;";
const applyLineCode = `
if (v_texc.x >= 0.0) { // v_texc = (-1,-1) for solid lines - don't bother with any of this
vec4 texColor = TEXTURE(u_lineCodeTexture, v_texc);
discardByLineCode = (0.0 == texColor.r);
}
if (v_lnInfo.w > 0.5) { // line needs pixel trimming
// calculate pixel distance from pixel center to expected line center, opposite dir from major
vec2 dxy = gl_FragCoord.xy - v_lnInfo.xy;
if (v_lnInfo.w < 1.5) // not x-major
dxy = dxy.yx;
float dist = v_lnInfo.z * dxy.x - dxy.y;
float distA = abs(dist);
if (distA > 0.5 || (distA == 0.5 && dist < 0.0))
discardByLineCode = true; // borrow this flag to force discard
}
return baseColor;
`;
const computeTextureCoord = `
vec2 computeLineCodeTextureCoords(vec2 windowDir, vec4 projPos, float adjust) {
vec2 texc;
float lineCode = computeLineCode();
if (0.0 == lineCode) {
// Solid line - tell frag shader not to bother.
texc = vec2(-1.0, -1.0);
} else {
const float imagesPerPixel = 1.0/32.0;
const float textureCoordinateBase = 8192.0; // Temp workardound for clipping problem in perspective views (negative values don't seem to interpolate correctly).
if (abs(windowDir.x) > abs(windowDir.y))
texc.x = textureCoordinateBase + imagesPerPixel * (projPos.x + adjust * windowDir.x);
else
texc.x = textureCoordinateBase + imagesPerPixel * (projPos.y + adjust * windowDir.y);
const float numLineCodes = 16.0; // NB: Actually only 10, but texture is 16px tall because it needs to be a power of 2.
const float rowsPerCode = 1.0;
const float numRows = numLineCodes*rowsPerCode;
const float centerY = 0.5/numRows;
const float stepY = rowsPerCode/numRows;
texc.y = stepY * lineCode + centerY;
}
return texc;
}
`;
/** @internal */
export const adjustWidth = `
void adjustWidth(inout float width, vec2 d2, vec2 org) {
if (u_aaSamples > 1) {
if (width < 5.0)
width += (5.0 - width) * 0.125;
return;
}
// calculate slope based width adjustment for non-AA lines, widths 1 to 4
vec2 d2A = abs(d2);
const float s_myFltEpsilon = 0.0001; // limit test resolution to 4 digits in case 24 bit (s16e7) is used in hardware
if (d2A.y > s_myFltEpsilon && width < 4.5) {
float len = length(d2A);
float tan = d2A.x / d2A.y;
if (width < 1.5) { // width 1
if (tan <= 1.0)
width = d2A.y;
else
width = d2A.x;
// width 1 requires additional adjustment plus trimming in frag shader using v_lnInfo
width *= 1.01;
v_lnInfo.xy = org;
v_lnInfo.w = 1.0; // set flag to do trimming
// set slope in v_lnInfo.z
if (d2A.x - d2A.y > s_myFltEpsilon) {
v_lnInfo.z = d2.y / d2.x;
v_lnInfo.w += 2.0; // add in x-major flag
} else
v_lnInfo.z = d2.x / d2.y;
} else if (width < 2.5) { // width 2
if (tan <= 0.5)
width = 2.0 * d2A.y;
else
width = (d2A.y + 2.0 * d2A.x);
} else if (width < 3.5) { // width 3
if (tan <= 1.0)
width = (3.0 * d2A.y + d2A.x);
else
width = (d2A.y + 3.0 * d2A.x);
} else { // if (width < 4.5) // width 4
if (tan <= 0.5)
width = (4.0 * d2A.y + d2A.x);
else if (tan <= 2.0)
width = (3.0 * d2A.y + 3.0 * d2A.x);
else
width = (d2A.y + 4.0 * d2A.x);
}
width /= len;
}
}
`;
/** @internal */
export function addAdjustWidth(vert: VertexShaderBuilder) {
vert.addUniform("u_aaSamples", VariableType.Int, (prog) => {
prog.addGraphicUniform("u_aaSamples", (attr, params) => {
const numSamples = System.instance.frameBufferStack.currentFbMultisampled ? params.target.compositor.antialiasSamples : 1;
attr.setUniform1i(numSamples);
});
});
vert.addFunction(adjustWidth);
}
/** @internal */
export function addLineCodeTexture(frag: FragmentShaderBuilder) {
frag.addUniform("u_lineCodeTexture", VariableType.Sampler2D, (prog) => {
prog.addProgramUniform("u_lineCodeTexture", (uniform) => {
const lct = System.instance.lineCodeTexture;
assert(undefined !== lct);
if (undefined !== lct)
lct.bindSampler(uniform, TextureUnit.LineCode);
});
});
}
/** @internal */
export function addLineCode(prog: ProgramBuilder, args: string) {
const vert = prog.vert;
const frag = prog.frag;
addLineCodeUniform(vert);
const funcCall: string = `computeLineCodeTextureCoords(${args})`;
prog.addFunctionComputedVaryingWithArgs("v_texc", VariableType.Vec2, funcCall, computeTextureCoord);
addFrustum(prog);
addLineCodeTexture(prog.frag);
frag.set(FragmentShaderComponent.FinalizeBaseColor, applyLineCode);
frag.set(FragmentShaderComponent.CheckForDiscard, checkForDiscard);
frag.addGlobal("discardByLineCode", VariableType.Boolean, "false");
}
function polylineAddLineCode(prog: ProgramBuilder) {
addLineCode(prog, lineCodeArgs);
addModelViewMatrix(prog.vert);
}
function addCommon(prog: ProgramBuilder) {
const vert = prog.vert;
addModelToWindowCoordinates(vert); // adds u_mvp, u_viewportTransformation
addProjectionMatrix(vert);
addModelViewMatrix(vert);
addViewport(vert);
vert.addGlobal("g_windowPos", VariableType.Vec4);
vert.addGlobal("g_prevPos", VariableType.Vec4);
vert.addGlobal("g_nextPos", VariableType.Vec4);
vert.addGlobal("g_windowDir", VariableType.Vec2);
vert.addInitializer(decodeAdjacentPositions);
vert.addFunction(unquantize2d);
addLineWeight(vert);
vert.addGlobal("miterAdjust", VariableType.Float, "0.0");
prog.addVarying("v_eyeSpace", VariableType.Vec3);
vert.set(VertexShaderComponent.ComputePosition, computePosition);
prog.addVarying("v_lnInfo", VariableType.Vec4);
addAdjustWidth(vert);
vert.addFunction(decodePosition);
}
const decodePosition = `
vec4 decodePosition(vec3 baseIndex) {
float index = decodeUInt24(baseIndex);
vec2 tc = compute_vert_coords(index);
vec4 e0 = floor(TEXTURE(u_vertLUT, tc) * 255.0 + 0.5);
tc.x += g_vert_stepX;
vec4 e1 = floor(TEXTURE(u_vertLUT, tc) * 255.0 + 0.5);
vec3 qpos = vec3(decodeUInt16(e0.xy), decodeUInt16(e0.zw), decodeUInt16(e1.xy));
return unquantizePosition(qpos, u_qOrigin, u_qScale);
}
`;
const decodeAdjacentPositions = `
g_prevPos = decodePosition(a_prevIndex);
g_nextPos = decodePosition(a_nextIndex);
`;
const computePosition = `
const float kNone = 0.0,
kSquare = 1.0*3.0,
kMiter = 2.0*3.0,
kMiterInsideOnly = 3.0*3.0,
kJointBase = 4.0*3.0,
kNegatePerp = 8.0*3.0,
kNegateAlong = 16.0*3.0,
kNoneAdjWt = 32.0*3.0;
v_lnInfo = vec4(0.0, 0.0, 0.0, 0.0); // init and set flag to false
vec4 next = g_nextPos;
vec4 pos;
g_windowPos = modelToWindowCoordinates(rawPos, next, pos, v_eyeSpace);
if (g_windowPos.w == 0.0)
return g_windowPos;
float param = a_param;
float weight = computeLineWeight();
float scale = 1.0, directionScale = 1.0;
if (param >= kNoneAdjWt)
param -= kNoneAdjWt;
if (param >= kNegateAlong) {
directionScale = -directionScale;
param -= kNegateAlong;
}
if (param >= kNegatePerp) {
scale = -1.0;
param -= kNegatePerp;
}
vec4 otherPos;
vec3 otherMvPos;
vec4 projNext = modelToWindowCoordinates(next, rawPos, otherPos, otherMvPos);
g_windowDir = projNext.xy - g_windowPos.xy;
if (param < kJointBase) {
vec2 dir = (directionScale > 0.0) ? g_windowDir : -g_windowDir;
vec2 pos = (directionScale > 0.0) ? g_windowPos.xy : projNext.xy;
adjustWidth(weight, dir, pos);
}
if (kNone != param) {
vec2 delta = vec2(0.0);
vec4 prev = g_prevPos;
vec4 projPrev = modelToWindowCoordinates(prev, rawPos, otherPos, otherMvPos);
vec2 prevDir = g_windowPos.xy - projPrev.xy;
float thisLength = sqrt(g_windowDir.x * g_windowDir.x + g_windowDir.y * g_windowDir.y);
const float s_minNormalizeLength = 1.0E-5; // avoid normalizing zero length vectors.
float dist = weight / 2.0;
if (thisLength > s_minNormalizeLength) {
g_windowDir /= thisLength;
float prevLength = sqrt(prevDir.x * prevDir.x + prevDir.y * prevDir.y);
if (prevLength > s_minNormalizeLength) {
prevDir /= prevLength;
const float s_minParallelDot= -.9999, s_maxParallelDot = .9999;
float prevNextDot = dot(prevDir, g_windowDir);
if (prevNextDot < s_minParallelDot || prevNextDot > s_maxParallelDot) // No miter if parallel or antiparallel.
param = kSquare;
} else
param = kSquare;
} else {
g_windowDir = -normalize(prevDir);
param = kSquare;
}
vec2 perp = scale * vec2(-g_windowDir.y, g_windowDir.x);
if (param == kSquare) {
delta = perp;
} else {
vec2 bisector = normalize(prevDir - g_windowDir);
float dotP = dot (bisector, perp);
if (dotP != 0.0) { // Should never occur - but avoid divide by zero.
const float maxMiter = 3.0;
float miterDistance = 1.0/dotP;
if (param == kMiter) { // Straight miter.
delta = (abs(miterDistance) > maxMiter) ? perp : bisector * miterDistance;
} else if (param == kMiterInsideOnly) { // Miter at inside, square at outside (to make room for joint).
delta = (dotP > 0.0 || abs(miterDistance) > maxMiter) ? perp : bisector * miterDistance;
} else {
const float jointTriangleCount = 3.0;
float ratio = (param - kJointBase) / jointTriangleCount; // 3 triangles per half-joint as defined in Graphics.cpp
delta = normalize((1.0 - ratio) * bisector + (dotP < 0.0 ? -ratio : ratio) * perp); // Miter/Straight combination.
}
}
}
miterAdjust = dot(g_windowDir, delta) * dist; // Not actually used for hilite shader but meh.
pos.x += dist * delta.x * 2.0 * pos.w / u_viewport.x;
pos.y += dist * delta.y * 2.0 * pos.w / u_viewport.y;
}
return pos;
`;
const lineCodeArgs = "g_windowDir, g_windowPos, miterAdjust";
/** @internal */
export function createPolylineBuilder(instanced: IsInstanced): ProgramBuilder {
const builder = new ProgramBuilder(AttributeMap.findAttributeMap(TechniqueId.Polyline, IsInstanced.Yes === instanced), instanced ? ShaderBuilderFlags.InstancedVertexTable : ShaderBuilderFlags.VertexTable);
addShaderFlags(builder);
addCommon(builder);
polylineAddLineCode(builder);
addColor(builder);
addEdgeContrast(builder.vert);
addWhiteOnWhiteReversal(builder.frag);
return builder;
}
/** @internal */
export function createPolylineHiliter(instanced: IsInstanced): ProgramBuilder {
const builder = new ProgramBuilder(AttributeMap.findAttributeMap(TechniqueId.Polyline, IsInstanced.Yes === instanced), instanced ? ShaderBuilderFlags.InstancedVertexTable : ShaderBuilderFlags.VertexTable);
addCommon(builder);
addFrustum(builder);
addHiliter(builder, true);
return builder;
} | the_stack |
declare namespace GoogleAppsScript {
namespace Gmail {
namespace Collection {
namespace Users {
namespace Messages {
interface AttachmentsCollection {
// Gets the specified message attachment.
get(userId: string, messageId: string, id: string): Gmail.Schema.MessagePartBody;
}
}
namespace Settings {
namespace SendAs {
interface SmimeInfoCollection {
// Gets the specified S/MIME config for the specified send-as alias.
get(userId: string, sendAsEmail: string, id: string): Gmail.Schema.SmimeInfo;
// Insert (upload) the given S/MIME config for the specified send-as alias. Note that pkcs12 format is required for the key.
insert(resource: Schema.SmimeInfo, userId: string, sendAsEmail: string): Gmail.Schema.SmimeInfo;
// Lists S/MIME configs for the specified send-as alias.
list(userId: string, sendAsEmail: string): Gmail.Schema.ListSmimeInfoResponse;
// Deletes the specified S/MIME config for the specified send-as alias.
remove(userId: string, sendAsEmail: string, id: string): void;
// Sets the default S/MIME config for the specified send-as alias.
setDefault(userId: string, sendAsEmail: string, id: string): void;
}
}
interface DelegatesCollection {
// Adds a delegate with its verification status set directly to accepted, without sending any verification email. The delegate user must be a member of the same G Suite organization as the delegator user.
// Gmail imposes limtations on the number of delegates and delegators each user in a G Suite organization can have. These limits depend on your organization, but in general each user can have up to 25 delegates and up to 10 delegators.
// Note that a delegate user must be referred to by their primary email address, and not an email alias.
// Also note that when a new delegate is created, there may be up to a one minute delay before the new delegate is available for use.
// This method is only available to service account clients that have been delegated domain-wide authority.
create(resource: Schema.Delegate, userId: string): Gmail.Schema.Delegate;
// Gets the specified delegate.
// Note that a delegate user must be referred to by their primary email address, and not an email alias.
// This method is only available to service account clients that have been delegated domain-wide authority.
get(userId: string, delegateEmail: string): Gmail.Schema.Delegate;
// Lists the delegates for the specified account.
// This method is only available to service account clients that have been delegated domain-wide authority.
list(userId: string): Gmail.Schema.ListDelegatesResponse;
// Removes the specified delegate (which can be of any verification status), and revokes any verification that may have been required for using it.
// Note that a delegate user must be referred to by their primary email address, and not an email alias.
// This method is only available to service account clients that have been delegated domain-wide authority.
remove(userId: string, delegateEmail: string): void;
}
interface FiltersCollection {
// Creates a filter.
create(resource: Schema.Filter, userId: string): Gmail.Schema.Filter;
// Gets a filter.
get(userId: string, id: string): Gmail.Schema.Filter;
// Lists the message filters of a Gmail user.
list(userId: string): Gmail.Schema.ListFiltersResponse;
// Deletes a filter.
remove(userId: string, id: string): void;
}
interface ForwardingAddressesCollection {
// Creates a forwarding address. If ownership verification is required, a message will be sent to the recipient and the resource's verification status will be set to pending; otherwise, the resource will be created with verification status set to accepted.
// This method is only available to service account clients that have been delegated domain-wide authority.
create(resource: Schema.ForwardingAddress, userId: string): Gmail.Schema.ForwardingAddress;
// Gets the specified forwarding address.
get(userId: string, forwardingEmail: string): Gmail.Schema.ForwardingAddress;
// Lists the forwarding addresses for the specified account.
list(userId: string): Gmail.Schema.ListForwardingAddressesResponse;
// Deletes the specified forwarding address and revokes any verification that may have been required.
// This method is only available to service account clients that have been delegated domain-wide authority.
remove(userId: string, forwardingEmail: string): void;
}
interface SendAsCollection {
SmimeInfo?: Gmail.Collection.Users.Settings.SendAs.SmimeInfoCollection;
// Creates a custom "from" send-as alias. If an SMTP MSA is specified, Gmail will attempt to connect to the SMTP service to validate the configuration before creating the alias. If ownership verification is required for the alias, a message will be sent to the email address and the resource's verification status will be set to pending; otherwise, the resource will be created with verification status set to accepted. If a signature is provided, Gmail will sanitize the HTML before saving it with the alias.
// This method is only available to service account clients that have been delegated domain-wide authority.
create(resource: Schema.SendAs, userId: string): Gmail.Schema.SendAs;
// Gets the specified send-as alias. Fails with an HTTP 404 error if the specified address is not a member of the collection.
get(userId: string, sendAsEmail: string): Gmail.Schema.SendAs;
// Lists the send-as aliases for the specified account. The result includes the primary send-as address associated with the account as well as any custom "from" aliases.
list(userId: string): Gmail.Schema.ListSendAsResponse;
// Updates a send-as alias. If a signature is provided, Gmail will sanitize the HTML before saving it with the alias.
// Addresses other than the primary address for the account can only be updated by service account clients that have been delegated domain-wide authority. This method supports patch semantics.
patch(resource: Schema.SendAs, userId: string, sendAsEmail: string): Gmail.Schema.SendAs;
// Deletes the specified send-as alias. Revokes any verification that may have been required for using it.
// This method is only available to service account clients that have been delegated domain-wide authority.
remove(userId: string, sendAsEmail: string): void;
// Updates a send-as alias. If a signature is provided, Gmail will sanitize the HTML before saving it with the alias.
// Addresses other than the primary address for the account can only be updated by service account clients that have been delegated domain-wide authority.
update(resource: Schema.SendAs, userId: string, sendAsEmail: string): Gmail.Schema.SendAs;
// Sends a verification email to the specified send-as alias address. The verification status must be pending.
// This method is only available to service account clients that have been delegated domain-wide authority.
verify(userId: string, sendAsEmail: string): void;
}
}
interface DraftsCollection {
// Creates a new draft with the DRAFT label.
create(resource: Schema.Draft, userId: string): Gmail.Schema.Draft;
// Creates a new draft with the DRAFT label.
create(resource: Schema.Draft, userId: string, mediaData: any): Gmail.Schema.Draft;
// Gets the specified draft.
get(userId: string, id: string): Gmail.Schema.Draft;
// Gets the specified draft.
get(userId: string, id: string, optionalArgs: object): Gmail.Schema.Draft;
// Lists the drafts in the user's mailbox.
list(userId: string): Gmail.Schema.ListDraftsResponse;
// Lists the drafts in the user's mailbox.
list(userId: string, optionalArgs: object): Gmail.Schema.ListDraftsResponse;
// Immediately and permanently deletes the specified draft. Does not simply trash it.
remove(userId: string, id: string): void;
// Sends the specified, existing draft to the recipients in the To, Cc, and Bcc headers.
send(resource: Schema.Draft, userId: string): Gmail.Schema.Message;
// Sends the specified, existing draft to the recipients in the To, Cc, and Bcc headers.
send(resource: Schema.Draft, userId: string, mediaData: any): Gmail.Schema.Message;
// Replaces a draft's content.
update(resource: Schema.Draft, userId: string, id: string): Gmail.Schema.Draft;
// Replaces a draft's content.
update(resource: Schema.Draft, userId: string, id: string, mediaData: any): Gmail.Schema.Draft;
}
interface HistoryCollection {
// Lists the history of all changes to the given mailbox. History results are returned in chronological order (increasing historyId).
list(userId: string): Gmail.Schema.ListHistoryResponse;
// Lists the history of all changes to the given mailbox. History results are returned in chronological order (increasing historyId).
list(userId: string, optionalArgs: object): Gmail.Schema.ListHistoryResponse;
}
interface LabelsCollection {
// Creates a new label.
create(resource: Schema.Label, userId: string): Gmail.Schema.Label;
// Gets the specified label.
get(userId: string, id: string): Gmail.Schema.Label;
// Lists all labels in the user's mailbox.
list(userId: string): Gmail.Schema.ListLabelsResponse;
// Updates the specified label. This method supports patch semantics.
patch(resource: Schema.Label, userId: string, id: string): Gmail.Schema.Label;
// Immediately and permanently deletes the specified label and removes it from any messages and threads that it is applied to.
remove(userId: string, id: string): void;
// Updates the specified label.
update(resource: Schema.Label, userId: string, id: string): Gmail.Schema.Label;
}
interface MessagesCollection {
Attachments?: Gmail.Collection.Users.Messages.AttachmentsCollection;
// Deletes many messages by message ID. Provides no guarantees that messages were not already deleted or even existed at all.
batchDelete(resource: Schema.BatchDeleteMessagesRequest, userId: string): void;
// Modifies the labels on the specified messages.
batchModify(resource: Schema.BatchModifyMessagesRequest, userId: string): void;
// Gets the specified message.
get(userId: string, id: string): Gmail.Schema.Message;
// Gets the specified message.
get(userId: string, id: string, optionalArgs: object): Gmail.Schema.Message;
// Imports a message into only this user's mailbox, with standard email delivery scanning and classification similar to receiving via SMTP. Does not send a message.
import(resource: Schema.Message, userId: string): Gmail.Schema.Message;
// Imports a message into only this user's mailbox, with standard email delivery scanning and classification similar to receiving via SMTP. Does not send a message.
import(resource: Schema.Message, userId: string, mediaData: any): Gmail.Schema.Message;
// Imports a message into only this user's mailbox, with standard email delivery scanning and classification similar to receiving via SMTP. Does not send a message.
import(resource: Schema.Message, userId: string, mediaData: any, optionalArgs: object): Gmail.Schema.Message;
// Directly inserts a message into only this user's mailbox similar to IMAP APPEND, bypassing most scanning and classification. Does not send a message.
insert(resource: Schema.Message, userId: string): Gmail.Schema.Message;
// Directly inserts a message into only this user's mailbox similar to IMAP APPEND, bypassing most scanning and classification. Does not send a message.
insert(resource: Schema.Message, userId: string, mediaData: any): Gmail.Schema.Message;
// Directly inserts a message into only this user's mailbox similar to IMAP APPEND, bypassing most scanning and classification. Does not send a message.
insert(resource: Schema.Message, userId: string, mediaData: any, optionalArgs: object): Gmail.Schema.Message;
// Lists the messages in the user's mailbox.
list(userId: string): Gmail.Schema.ListMessagesResponse;
// Lists the messages in the user's mailbox.
list(userId: string, optionalArgs: object): Gmail.Schema.ListMessagesResponse;
// Modifies the labels on the specified message.
modify(resource: Schema.ModifyMessageRequest, userId: string, id: string): Gmail.Schema.Message;
// Immediately and permanently deletes the specified message. This operation cannot be undone. Prefer messages.trash instead.
remove(userId: string, id: string): void;
// Sends the specified message to the recipients in the To, Cc, and Bcc headers.
send(resource: Schema.Message, userId: string): Gmail.Schema.Message;
// Sends the specified message to the recipients in the To, Cc, and Bcc headers.
send(resource: Schema.Message, userId: string, mediaData: any): Gmail.Schema.Message;
// Moves the specified message to the trash.
trash(userId: string, id: string): Gmail.Schema.Message;
// Removes the specified message from the trash.
untrash(userId: string, id: string): Gmail.Schema.Message;
}
interface SettingsCollection {
Delegates?: Gmail.Collection.Users.Settings.DelegatesCollection;
Filters?: Gmail.Collection.Users.Settings.FiltersCollection;
ForwardingAddresses?: Gmail.Collection.Users.Settings.ForwardingAddressesCollection;
SendAs?: Gmail.Collection.Users.Settings.SendAsCollection;
// Gets the auto-forwarding setting for the specified account.
getAutoForwarding(userId: string): Gmail.Schema.AutoForwarding;
// Gets IMAP settings.
getImap(userId: string): Gmail.Schema.ImapSettings;
// Gets POP settings.
getPop(userId: string): Gmail.Schema.PopSettings;
// Gets vacation responder settings.
getVacation(userId: string): Gmail.Schema.VacationSettings;
// Updates the auto-forwarding setting for the specified account. A verified forwarding address must be specified when auto-forwarding is enabled.
// This method is only available to service account clients that have been delegated domain-wide authority.
updateAutoForwarding(resource: Schema.AutoForwarding, userId: string): Gmail.Schema.AutoForwarding;
// Updates IMAP settings.
updateImap(resource: Schema.ImapSettings, userId: string): Gmail.Schema.ImapSettings;
// Updates POP settings.
updatePop(resource: Schema.PopSettings, userId: string): Gmail.Schema.PopSettings;
// Updates vacation responder settings.
updateVacation(resource: Schema.VacationSettings, userId: string): Gmail.Schema.VacationSettings;
}
interface ThreadsCollection {
// Gets the specified thread.
get(userId: string, id: string): Gmail.Schema.Thread;
// Gets the specified thread.
get(userId: string, id: string, optionalArgs: object): Gmail.Schema.Thread;
// Lists the threads in the user's mailbox.
list(userId: string): Gmail.Schema.ListThreadsResponse;
// Lists the threads in the user's mailbox.
list(userId: string, optionalArgs: object): Gmail.Schema.ListThreadsResponse;
// Modifies the labels applied to the thread. This applies to all messages in the thread.
modify(resource: Schema.ModifyThreadRequest, userId: string, id: string): Gmail.Schema.Thread;
// Immediately and permanently deletes the specified thread. This operation cannot be undone. Prefer threads.trash instead.
remove(userId: string, id: string): void;
// Moves the specified thread to the trash.
trash(userId: string, id: string): Gmail.Schema.Thread;
// Removes the specified thread from the trash.
untrash(userId: string, id: string): Gmail.Schema.Thread;
}
}
interface UsersCollection {
Drafts?: Gmail.Collection.Users.DraftsCollection;
History?: Gmail.Collection.Users.HistoryCollection;
Labels?: Gmail.Collection.Users.LabelsCollection;
Messages?: Gmail.Collection.Users.MessagesCollection;
Settings?: Gmail.Collection.Users.SettingsCollection;
Threads?: Gmail.Collection.Users.ThreadsCollection;
// Gets the current user's Gmail profile.
getProfile(userId: string): Gmail.Schema.Profile;
// Stop receiving push notifications for the given user mailbox.
stop(userId: string): void;
// Set up or update a push notification watch on the given user mailbox.
watch(resource: Schema.WatchRequest, userId: string): Gmail.Schema.WatchResponse;
}
}
namespace Schema {
interface AutoForwarding {
disposition?: string;
emailAddress?: string;
enabled?: boolean;
}
interface BatchDeleteMessagesRequest {
ids?: string[];
}
interface BatchModifyMessagesRequest {
addLabelIds?: string[];
ids?: string[];
removeLabelIds?: string[];
}
interface Delegate {
delegateEmail?: string;
verificationStatus?: string;
}
interface Draft {
id?: string;
message?: Gmail.Schema.Message;
}
interface Filter {
action?: Gmail.Schema.FilterAction;
criteria?: Gmail.Schema.FilterCriteria;
id?: string;
}
interface FilterAction {
addLabelIds?: string[];
forward?: string;
removeLabelIds?: string[];
}
interface FilterCriteria {
excludeChats?: boolean;
from?: string;
hasAttachment?: boolean;
negatedQuery?: string;
query?: string;
size?: number;
sizeComparison?: string;
subject?: string;
to?: string;
}
interface ForwardingAddress {
forwardingEmail?: string;
verificationStatus?: string;
}
interface History {
id?: string;
labelsAdded?: Gmail.Schema.HistoryLabelAdded[];
labelsRemoved?: Gmail.Schema.HistoryLabelRemoved[];
messages?: Gmail.Schema.Message[];
messagesAdded?: Gmail.Schema.HistoryMessageAdded[];
messagesDeleted?: Gmail.Schema.HistoryMessageDeleted[];
}
interface HistoryLabelAdded {
labelIds?: string[];
message?: Gmail.Schema.Message;
}
interface HistoryLabelRemoved {
labelIds?: string[];
message?: Gmail.Schema.Message;
}
interface HistoryMessageAdded {
message?: Gmail.Schema.Message;
}
interface HistoryMessageDeleted {
message?: Gmail.Schema.Message;
}
interface ImapSettings {
autoExpunge?: boolean;
enabled?: boolean;
expungeBehavior?: string;
maxFolderSize?: number;
}
interface Label {
color?: Gmail.Schema.LabelColor;
id?: string;
labelListVisibility?: string;
messageListVisibility?: string;
messagesTotal?: number;
messagesUnread?: number;
name?: string;
threadsTotal?: number;
threadsUnread?: number;
type?: string;
}
interface LabelColor {
backgroundColor?: string;
textColor?: string;
}
interface ListDelegatesResponse {
delegates?: Gmail.Schema.Delegate[];
}
interface ListDraftsResponse {
drafts?: Gmail.Schema.Draft[];
nextPageToken?: string;
resultSizeEstimate?: number;
}
interface ListFiltersResponse {
filter?: Gmail.Schema.Filter[];
}
interface ListForwardingAddressesResponse {
forwardingAddresses?: Gmail.Schema.ForwardingAddress[];
}
interface ListHistoryResponse {
history?: Gmail.Schema.History[];
historyId?: string;
nextPageToken?: string;
}
interface ListLabelsResponse {
labels?: Gmail.Schema.Label[];
}
interface ListMessagesResponse {
messages?: Gmail.Schema.Message[];
nextPageToken?: string;
resultSizeEstimate?: number;
}
interface ListSendAsResponse {
sendAs?: Gmail.Schema.SendAs[];
}
interface ListSmimeInfoResponse {
smimeInfo?: Gmail.Schema.SmimeInfo[];
}
interface ListThreadsResponse {
nextPageToken?: string;
resultSizeEstimate?: number;
threads?: Gmail.Schema.Thread[];
}
interface Message {
historyId?: string;
id?: string;
internalDate?: string;
labelIds?: string[];
payload?: Gmail.Schema.MessagePart;
raw?: string;
sizeEstimate?: number;
snippet?: string;
threadId?: string;
}
interface MessagePart {
body?: Gmail.Schema.MessagePartBody;
filename?: string;
headers?: Gmail.Schema.MessagePartHeader[];
mimeType?: string;
partId?: string;
parts?: Gmail.Schema.MessagePart[];
}
interface MessagePartBody {
attachmentId?: string;
data?: string;
size?: number;
}
interface MessagePartHeader {
name?: string;
value?: string;
}
interface ModifyMessageRequest {
addLabelIds?: string[];
removeLabelIds?: string[];
}
interface ModifyThreadRequest {
addLabelIds?: string[];
removeLabelIds?: string[];
}
interface PopSettings {
accessWindow?: string;
disposition?: string;
}
interface Profile {
emailAddress?: string;
historyId?: string;
messagesTotal?: number;
threadsTotal?: number;
}
interface SendAs {
displayName?: string;
isDefault?: boolean;
isPrimary?: boolean;
replyToAddress?: string;
sendAsEmail?: string;
signature?: string;
smtpMsa?: Gmail.Schema.SmtpMsa;
treatAsAlias?: boolean;
verificationStatus?: string;
}
interface SmimeInfo {
encryptedKeyPassword?: string;
expiration?: string;
id?: string;
isDefault?: boolean;
issuerCn?: string;
pem?: string;
pkcs12?: string;
}
interface SmtpMsa {
host?: string;
password?: string;
port?: number;
securityMode?: string;
username?: string;
}
interface Thread {
historyId?: string;
id?: string;
messages?: Gmail.Schema.Message[];
snippet?: string;
}
interface VacationSettings {
enableAutoReply?: boolean;
endTime?: string;
responseBodyHtml?: string;
responseBodyPlainText?: string;
responseSubject?: string;
restrictToContacts?: boolean;
restrictToDomain?: boolean;
startTime?: string;
}
interface WatchRequest {
labelFilterAction?: string;
labelIds?: string[];
topicName?: string;
}
interface WatchResponse {
expiration?: string;
historyId?: string;
}
}
}
interface Gmail {
Users?: Gmail.Collection.UsersCollection;
// Create a new instance of AutoForwarding
newAutoForwarding(): Gmail.Schema.AutoForwarding;
// Create a new instance of BatchDeleteMessagesRequest
newBatchDeleteMessagesRequest(): Gmail.Schema.BatchDeleteMessagesRequest;
// Create a new instance of BatchModifyMessagesRequest
newBatchModifyMessagesRequest(): Gmail.Schema.BatchModifyMessagesRequest;
// Create a new instance of Delegate
newDelegate(): Gmail.Schema.Delegate;
// Create a new instance of Draft
newDraft(): Gmail.Schema.Draft;
// Create a new instance of Filter
newFilter(): Gmail.Schema.Filter;
// Create a new instance of FilterAction
newFilterAction(): Gmail.Schema.FilterAction;
// Create a new instance of FilterCriteria
newFilterCriteria(): Gmail.Schema.FilterCriteria;
// Create a new instance of ForwardingAddress
newForwardingAddress(): Gmail.Schema.ForwardingAddress;
// Create a new instance of ImapSettings
newImapSettings(): Gmail.Schema.ImapSettings;
// Create a new instance of Label
newLabel(): Gmail.Schema.Label;
// Create a new instance of LabelColor
newLabelColor(): Gmail.Schema.LabelColor;
// Create a new instance of Message
newMessage(): Gmail.Schema.Message;
// Create a new instance of MessagePart
newMessagePart(): Gmail.Schema.MessagePart;
// Create a new instance of MessagePartBody
newMessagePartBody(): Gmail.Schema.MessagePartBody;
// Create a new instance of MessagePartHeader
newMessagePartHeader(): Gmail.Schema.MessagePartHeader;
// Create a new instance of ModifyMessageRequest
newModifyMessageRequest(): Gmail.Schema.ModifyMessageRequest;
// Create a new instance of ModifyThreadRequest
newModifyThreadRequest(): Gmail.Schema.ModifyThreadRequest;
// Create a new instance of PopSettings
newPopSettings(): Gmail.Schema.PopSettings;
// Create a new instance of SendAs
newSendAs(): Gmail.Schema.SendAs;
// Create a new instance of SmimeInfo
newSmimeInfo(): Gmail.Schema.SmimeInfo;
// Create a new instance of SmtpMsa
newSmtpMsa(): Gmail.Schema.SmtpMsa;
// Create a new instance of VacationSettings
newVacationSettings(): Gmail.Schema.VacationSettings;
// Create a new instance of WatchRequest
newWatchRequest(): Gmail.Schema.WatchRequest;
}
}
declare var Gmail: GoogleAppsScript.Gmail; | the_stack |
import * as React from 'react';
import { ISPFieldLookupValue, ITerm, IPrincipal } from '../SPEntities';
import { FieldTextRenderer } from '../../controls/fields/fieldTextRenderer/FieldTextRenderer';
import { FieldDateRenderer } from '../../controls/fields/fieldDateRenderer/FieldDateRenderer';
import { ListItemAccessor } from '@microsoft/sp-listview-extensibility';
import { SPHelper } from './SPHelper';
import { FieldTitleRenderer } from '../../controls/fields/fieldTitleRenderer/FieldTitleRenderer';
import { SPField } from '@microsoft/sp-page-context';
import { IContext } from '../Interfaces';
import { GeneralHelper } from './GeneralHelper';
import { FieldLookupRenderer, IFieldLookupClickEventArgs } from '../../controls/fields/fieldLookupRenderer/FieldLookupRenderer';
import { FieldUrlRenderer } from '../../controls/fields/fieldUrlRenderer/FieldUrlRenderer';
import { FieldTaxonomyRenderer } from '../../controls/fields/fieldTaxonomyRenderer/FieldTaxonomyRenderer';
import { IFieldRendererProps } from '../../controls/fields/fieldCommon/IFieldRendererProps';
import { FieldUserRenderer } from '../../controls/fields/fieldUserRenderer/FieldUserRenderer';
import { FieldFileTypeRenderer } from '../../controls/fields/fieldFileTypeRenderer/FieldFileTypeRenderer';
import { FieldAttachmentsRenderer } from '../../controls/fields/fieldAttachmentsRenderer/FieldAttachmentsRenderer';
import { FieldNameRenderer } from '../../controls/fields/fieldNameRenderer/FieldNameRenderer';
/**
* Field Renderer Helper.
* Helps to render fields similarly to OOTB SharePoint rendering
*/
export class FieldRendererHelper {
/**
* Returns JSX.Element with OOTB rendering and applied additional props
* @param fieldValue Value of the field
* @param props IFieldRendererProps (CSS classes and CSS styles)
* @param listItem Current list item
* @param context Customizer context
*/
public static getFieldRenderer(fieldValue: any, props: IFieldRendererProps, listItem: ListItemAccessor, context: IContext): Promise<JSX.Element> {
return new Promise<JSX.Element>(resolve => {
const field: SPField = context.field;
const listId: string = context.pageContext.list.id.toString();
const fieldType: string = field.fieldType;
const fieldName: string = field.internalName; //SPHelper.getFieldNameById(field.id.toString());
let result: JSX.Element = null;
const fieldValueAsEncodedText: string = fieldValue ? GeneralHelper.encodeText(fieldValue.toString()) : '';
switch (fieldType) {
case 'Text':
case 'Choice':
case 'Boolean':
case 'MultiChoice':
case 'Computed':
const fieldStoredName: string = SPHelper.getStoredFieldName(fieldName);
if (fieldStoredName === 'Title') {
resolve(React.createElement(FieldTitleRenderer, {
text: fieldValueAsEncodedText,
isLink: fieldName === 'LinkTitle' || fieldName === 'LinkTitleNoMenu',
listId: listId,
id: listItem.getValueByName('ID'),
baseUrl: context.pageContext.web.absoluteUrl,
...props
}));
}
else if (fieldStoredName === 'DocIcon') {
const path: string = listItem.getValueByName('FileLeafRef');
resolve(React.createElement(FieldFileTypeRenderer, {
path: path,
isFolder: SPHelper.getRowItemValueByName(listItem, 'FSObjType') === '1',
...props
}));
}
else if (fieldStoredName === 'FileLeafRef') {
resolve(React.createElement(FieldNameRenderer, {
text: fieldValueAsEncodedText,
isLink: true,
filePath: SPHelper.getRowItemValueByName(listItem, 'FileRef'),
isNew: SPHelper.getRowItemValueByName(listItem, 'Created_x0020_Date.ifnew') === '1',
hasPreview: true,
...props
}));
}
else if (fieldStoredName === 'URL') {
resolve(React.createElement(FieldUrlRenderer, {
isImageUrl: false,
url: fieldValue.toString(),
text: SPHelper.getRowItemValueByName(listItem, `URL.desc`) || fieldValueAsEncodedText,
...props
}));
}
else {
resolve(React.createElement(FieldTextRenderer, {
text: fieldValueAsEncodedText,
isSafeForInnerHTML: false,
isTruncated: false,
...props
}));
}
break;
case 'Integer':
case 'Counter':
case 'Number':
case 'Currency':
resolve(React.createElement(FieldTextRenderer, {
text: fieldValueAsEncodedText,
isSafeForInnerHTML: true,
isTruncated: false,
...props
}));
break;
case 'Note':
SPHelper.getFieldProperty(field.id.toString(), "RichText", context, false).then(richText => {
const isRichText: boolean = richText === true || richText === 'TRUE';
let html: string = '';
if (isRichText) {
html = fieldValue.toString();
}
else {
html = fieldValueAsEncodedText.replace(/\n/g, "<br>");
}
// text is truncated if its length is more that 255 symbols or it has more than 4 lines
let isTruncated: boolean = html.length > 255 || html.split(/\r|\r\n|\n|<br>/).length > 4;
resolve(React.createElement(FieldTextRenderer, {
text: html,
isSafeForInnerHTML: true,
isTruncated: isTruncated,
...props
}));
});
break;
case 'DateTime':
const friendlyDisplay: string = SPHelper.getRowItemValueByName(listItem, `${fieldName}.FriendlyDisplay`);
resolve(React.createElement(FieldDateRenderer, {
text: friendlyDisplay ? GeneralHelper.getRelativeDateTimeString(friendlyDisplay) : fieldValueAsEncodedText,
...props
}));
break;
case "Lookup":
case "LookupMulti":
//
// we're providing fieldId and context. In that case Lookup values will be rendered right away
// without additional lag of waiting of response to get dispUrl.
// The request for DispUrl will be sent only if user click on the value
//
const lookupValues = fieldValue as ISPFieldLookupValue[];
resolve(React.createElement(FieldLookupRenderer, {
lookups: lookupValues,
fieldId: field.id.toString(),
context: context,
...props
}));
break;
case 'URL':
SPHelper.getFieldProperty(field.id.toString(), 'Format', context, true).then(format => {
const isImage: boolean = format === 'Image';
const text: string = SPHelper.getRowItemValueByName(listItem, `${fieldName}.desc`);
resolve(React.createElement(FieldUrlRenderer, {
isImageUrl: isImage,
url: fieldValue.toString(),
text: text,
...props
}));
});
break;
case 'Taxonomy':
case 'TaxonomyFieldType':
case 'TaxonomyFieldTypeMulti':
const terms: ITerm[] = Array.isArray(fieldValue) ? <ITerm[]>fieldValue : <ITerm[]>[fieldValue];
resolve(React.createElement(FieldTaxonomyRenderer, {
terms: terms,
...props
}));
break;
case 'User':
case 'UserMulti':
resolve(React.createElement(FieldUserRenderer, {
users: <IPrincipal[]>fieldValue,
context: context,
...props
}));
break;
case 'Attachments':
resolve(React.createElement(FieldAttachmentsRenderer, {
count: parseInt(fieldValue),
...props
}));
break;
default:
resolve(React.createElement(FieldTextRenderer, {
text: fieldValueAsEncodedText,
isSafeForInnerHTML: false,
isTruncated: false,
...props
}));
break;
}
});
}
} | the_stack |
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import { ConnectionService } from 'ng-connection-service';
// firebase
// import * as firebase from 'firebase/app';
import firebase from "firebase/app";
import 'firebase/messaging';
import 'firebase/database';
import 'firebase/auth';
// services
import { MessagingAuthService } from '../abstract/messagingAuth.service';
// import { ImageRepoService } from '../abstract/image-repo.service';
// import { FirebaseImageRepoService } from './firebase-image-repo';
// models
import { UserModel } from '../../models/user';
// utils
import {
avatarPlaceholder,
getColorBck,
} from '../../utils/utils-user';
import { resolve } from 'url';
import { CustomLogger } from '../logger/customLogger';
import { AppStorageService } from '../abstract/app-storage.service';
import { LoggerInstance } from '../logger/loggerInstance';
import { LoggerService } from '../abstract/logger.service';
import { Observable, Observer, fromEvent, merge } from 'rxjs';
import { map } from 'rxjs/operators'
import { Network } from '@ionic-native/network/ngx';
// @Injectable({ providedIn: 'root' })
@Injectable()
export class FirebaseAuthService extends MessagingAuthService {
// BehaviorSubject
BSAuthStateChanged: BehaviorSubject<any>;
BSSignOut: BehaviorSubject<any>;
// firebaseSignInWithCustomToken: BehaviorSubject<any>;
// public params
// private persistence: string;
public SERVER_BASE_URL: string;
// private
private URL_TILEDESK_SIGNIN: string;
private URL_TILEDESK_SIGNIN_ANONYMOUSLY: string;
private URL_TILEDESK_CREATE_CUSTOM_TOKEN: string;
private URL_TILEDESK_SIGNIN_WITH_CUSTOM_TOKEN: string;
//TODO-GAB
// private imageRepo: ImageRepoService = new FirebaseImageRepoService();
private firebaseToken: string;
private logger: LoggerService = LoggerInstance.getInstance()
status = 'ONLINE';
isConnected = true;
constructor(
public http: HttpClient,
private network: Network,
private connectionService: ConnectionService
) {
super();
}
/**
*
*/
initialize() {
this.SERVER_BASE_URL = this.getBaseUrl();
this.URL_TILEDESK_CREATE_CUSTOM_TOKEN = this.SERVER_BASE_URL + 'chat21/firebase/auth/createCustomToken';
this.logger.info('[FIREBASEAuthSERVICE] - initialize URL_TILEDESK_CREATE_CUSTOM_TOKEN ', this.URL_TILEDESK_CREATE_CUSTOM_TOKEN)
// this.URL_TILEDESK_SIGNIN = this.SERVER_BASE_URL + 'auth/signin';
// this.URL_TILEDESK_SIGNIN_ANONYMOUSLY = this.SERVER_BASE_URL + 'auth/signinAnonymously'
// this.URL_TILEDESK_SIGNIN_WITH_CUSTOM_TOKEN = this.SERVER_BASE_URL + 'auth/signinWithCustomToken';
// this.checkIsAuth();
// this.createOnline$().subscribe((isOnline) =>{
// console.log('FIREBASEAuthSERVICE] isOnline ', isOnline);
// if (isOnline === true ) {
// this.onAuthStateChanged();
// }
// })
// this.checkInternetConnection()
this.onAuthStateChanged();
}
checkInternetConnection () {
this.logger.log('[FIREBASEAuthSERVICE] - checkInternetConnection');
// let connectSubscription = this.network.onConnect().subscribe(() => {
// this.logger.log('[FIREBASEAuthSERVICE] - network connected!');
// // We just got a connection but we need to wait briefly
// // before we determine the connection type. Might need to wait.
// // prior to doing any api requests as well.
// setTimeout(() => {
// if (this.network.type === 'wifi') {
// this.logger.log('[FIREBASEAuthSERVICE] - we got a wifi connection, woohoo!');
// }
// }, 3000);
// });
this.connectionService.monitor().subscribe(isConnected => {
this.isConnected = isConnected;
this.logger.log('[FIREBASEAuthSERVICE] - checkInternetConnection isConnected', isConnected);
if (this.isConnected) {
this.status = "ONLINE";
// this.onAuthStateChanged();
firebase.auth().onAuthStateChanged(user => {
this.logger.log('[FIREBASEAuthSERVICE] checkInternetConnection onAuthStateChanged', user)
})
}
else {
this.status = "OFFLINE";
// this.onAuthStateChanged();
firebase.auth().onAuthStateChanged(user => {
this.logger.log('[FIREBASEAuthSERVICE] checkInternetConnection onAuthStateChanged', user)
})
}
})
}
// createOnline$() {
// return merge<boolean>(
// fromEvent(window, 'offline').pipe(map(() => false)),
// fromEvent(window, 'online').pipe(map(() => true)),
// new Observable((sub: Observer<boolean>) => {
// sub.next(navigator.onLine);
// sub.complete();
// }));
// }
/**
* checkIsAuth
*/
// checkIsAuth() {
// this.logger.printDebug(' ---------------- AuthService checkIsAuth ---------------- ')
// this.tiledeskToken = this.appStorage.getItem('tiledeskToken')
// this.currentUser = JSON.parse(this.appStorage.getItem('currentUser'));
// if (this.tiledeskToken) {
// this.logger.printDebug(' ---------------- MI LOGGO CON UN TOKEN ESISTENTE NEL LOCAL STORAGE O PASSATO NEI PARAMS URL ---------------- ')
// this.createFirebaseCustomToken();
// } else {
// this.logger.printDebug(' ---------------- NON sono loggato ---------------- ')
// // this.BSAuthStateChanged.next('offline');
// }
// // da rifattorizzare il codice seguente!!!
// // const that = this;
// // this.route.queryParams.subscribe(params => {
// // if (params.tiledeskToken) {
// // that.tiledeskToken = params.tiledeskToken;
// // }
// // });
// }
/** */
getToken(): string {
return this.firebaseToken;
}
// ********************* START FIREBASE AUTH ********************* //
/**
* FIREBASE: onAuthStateChanged
*/
onAuthStateChanged() {
const that = this;
firebase.auth().onAuthStateChanged(user => {
this.logger.log('initialize FROM [APP-COMP] - [FIREBASEAuthSERVICE] onAuthStateChanged', user)
if (!user) {
this.logger.log('[FIREBASEAuthSERVICE] 1 - PASSO OFFLINE AL CHAT MANAGER')
// this.logger.info('initialize FROM [APP-COMP] - [APP-COMP] - [FIREBASEAuthSERVICE] onAuthStateChanged user ', user)
that.BSAuthStateChanged.next('offline');
} else {
this.logger.log('[FIREBASEAuthSERVICE] 2 - PASSO ONLINE AL CHAT MANAGER')
// this.logger.info('initialize FROM [APP-COMP] - [APP-COMP] - [FIREBASEAuthSERVICE] onAuthStateChanged user ', user)
that.BSAuthStateChanged.next('online');
}
});
}
/**
* FIREBASE: signInWithCustomToken
* @param token
*/
signInFirebaseWithCustomToken(token: string): Promise<any> {
const that = this;
let firebasePersistence;
// console.log('FB-AUTH firebasePersistence', this.getPersistence())
switch (this.getPersistence()) {
case 'SESSION': {
firebasePersistence = firebase.auth.Auth.Persistence.SESSION;
break;
}
case 'LOCAL': {
firebasePersistence = firebase.auth.Auth.Persistence.LOCAL;
break;
}
case 'NONE': {
firebasePersistence = firebase.auth.Auth.Persistence.NONE;
break;
}
default: {
firebasePersistence = firebase.auth.Auth.Persistence.NONE;
break;
}
}
return firebase.auth().setPersistence(firebasePersistence).then(async () => {
return firebase.auth().signInWithCustomToken(token).then(async (user) => {
// that.firebaseSignInWithCustomToken.next(response);
}).catch((error) => {
that.logger.error('[FIREBASEAuthSERVICE] signInFirebaseWithCustomToken Error: ', error);
// that.firebaseSignInWithCustomToken.next(null);
});
}).catch((error) => {
that.logger.error('[FIREBASEAuthSERVICE] signInFirebaseWithCustomToken Error: ', error);
});
}
/**
* FIREBASE: createUserWithEmailAndPassword
* @param email
* @param password
* @param firstname
* @param lastname
*/
createUserWithEmailAndPassword(email: string, password: string): any {
const that = this;
return firebase.auth().createUserWithEmailAndPassword(email, password).then((response) => {
that.logger.debug('[FIREBASEAuthSERVICE] CRATE USER WITH EMAIL: ', email, ' & PSW: ', password);
// that.firebaseCreateUserWithEmailAndPassword.next(response);
return response;
}).catch((error) => {
that.logger.error('[FIREBASEAuthSERVICE] createUserWithEmailAndPassword error: ', error.message);
return error;
});
}
/**
* FIREBASE: sendPasswordResetEmail
*/
sendPasswordResetEmail(email: string): any {
const that = this;
return firebase.auth().sendPasswordResetEmail(email).then(() => {
that.logger.debug('[FIREBASEAuthSERVICE] firebase-send-password-reset-email');
// that.firebaseSendPasswordResetEmail.next(email);
}).catch((error) => {
that.logger.error('[FIREBASEAuthSERVICE] sendPasswordResetEmail error: ', error);
});
}
/**
* FIREBASE: signOut
*/
private signOut() {
const that = this;
firebase.auth().signOut().then(() => {
that.logger.log('[FIREBASEAuthSERVICE] signOut firebase-sign-out');
// cancello token
// this.appStorage.removeItem('tiledeskToken');
//localStorage.removeItem('firebaseToken');
that.BSSignOut.next(true);
}).catch((error) => {
that.logger.error('[FIREBASEAuthSERVICE] signOut error: ', error);
});
}
/**
* FIREBASE: currentUser delete
*/
delete() {
const that = this;
firebase.auth().currentUser.delete().then(() => {
that.logger.debug('[FIREBASEAuthSERVICE] firebase-current-user-delete');
// that.firebaseCurrentUserDelete.next();
}).catch((error) => {
that.logger.error('[FIREBASEAuthSERVICE] delete error: ', error);
});
}
// ********************* END FIREBASE AUTH ********************* //
/**
*
* @param token
*/
createCustomToken(tiledeskToken: string) {
const headers = new HttpHeaders({
'Content-type': 'application/json',
Authorization: tiledeskToken
});
const responseType = 'text';
const postData = {};
const that = this;
this.http.post(this.URL_TILEDESK_CREATE_CUSTOM_TOKEN, postData, { headers, responseType }).subscribe(data => {
that.firebaseToken = data;
//localStorage.setItem('firebaseToken', that.firebaseToken);
that.signInFirebaseWithCustomToken(data)
}, error => {
that.logger.error('[FIREBASEAuthSERVICE] createFirebaseCustomToken ERR ', error)
});
}
logout() {
this.logger.log('[FIREBASEAuthSERVICE] logout');
this.BSAuthStateChanged.next(null);
// cancello token firebase dal local storage e da firebase
// dovrebbe scattare l'evento authchangeStat
this.signOut();
}
} | the_stack |
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export const CloudError = CloudErrorMapper;
export const BaseResource = BaseResourceMapper;
export const Resource: msRest.CompositeMapper = {
serializedName: "Resource",
type: {
name: "Composite",
className: "Resource",
modelProperties: {
id: {
readOnly: true,
serializedName: "id",
type: {
name: "String"
}
},
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
type: {
readOnly: true,
serializedName: "type",
type: {
name: "String"
}
}
}
}
};
export const TrackedResource: msRest.CompositeMapper = {
serializedName: "TrackedResource",
type: {
name: "Composite",
className: "TrackedResource",
modelProperties: {
...Resource.type.modelProperties,
tags: {
serializedName: "tags",
type: {
name: "Dictionary",
value: {
type: {
name: "String"
}
}
}
},
location: {
serializedName: "location",
type: {
name: "String"
}
}
}
}
};
export const PrivateZone: msRest.CompositeMapper = {
serializedName: "PrivateZone",
type: {
name: "Composite",
className: "PrivateZone",
modelProperties: {
...TrackedResource.type.modelProperties,
etag: {
serializedName: "etag",
type: {
name: "String"
}
},
maxNumberOfRecordSets: {
readOnly: true,
serializedName: "properties.maxNumberOfRecordSets",
type: {
name: "Number"
}
},
numberOfRecordSets: {
readOnly: true,
serializedName: "properties.numberOfRecordSets",
type: {
name: "Number"
}
},
maxNumberOfVirtualNetworkLinks: {
readOnly: true,
serializedName: "properties.maxNumberOfVirtualNetworkLinks",
type: {
name: "Number"
}
},
numberOfVirtualNetworkLinks: {
readOnly: true,
serializedName: "properties.numberOfVirtualNetworkLinks",
type: {
name: "Number"
}
},
maxNumberOfVirtualNetworkLinksWithRegistration: {
readOnly: true,
serializedName: "properties.maxNumberOfVirtualNetworkLinksWithRegistration",
type: {
name: "Number"
}
},
numberOfVirtualNetworkLinksWithRegistration: {
readOnly: true,
serializedName: "properties.numberOfVirtualNetworkLinksWithRegistration",
type: {
name: "Number"
}
},
provisioningState: {
readOnly: true,
serializedName: "properties.provisioningState",
type: {
name: "String"
}
}
}
}
};
export const SubResource: msRest.CompositeMapper = {
serializedName: "SubResource",
type: {
name: "Composite",
className: "SubResource",
modelProperties: {
id: {
serializedName: "id",
type: {
name: "String"
}
}
}
}
};
export const VirtualNetworkLink: msRest.CompositeMapper = {
serializedName: "VirtualNetworkLink",
type: {
name: "Composite",
className: "VirtualNetworkLink",
modelProperties: {
...TrackedResource.type.modelProperties,
etag: {
serializedName: "etag",
type: {
name: "String"
}
},
virtualNetwork: {
serializedName: "properties.virtualNetwork",
type: {
name: "Composite",
className: "SubResource"
}
},
registrationEnabled: {
serializedName: "properties.registrationEnabled",
type: {
name: "Boolean"
}
},
virtualNetworkLinkState: {
readOnly: true,
serializedName: "properties.virtualNetworkLinkState",
type: {
name: "String"
}
},
provisioningState: {
readOnly: true,
serializedName: "properties.provisioningState",
type: {
name: "String"
}
}
}
}
};
export const ARecord: msRest.CompositeMapper = {
serializedName: "ARecord",
type: {
name: "Composite",
className: "ARecord",
modelProperties: {
ipv4Address: {
serializedName: "ipv4Address",
type: {
name: "String"
}
}
}
}
};
export const AaaaRecord: msRest.CompositeMapper = {
serializedName: "AaaaRecord",
type: {
name: "Composite",
className: "AaaaRecord",
modelProperties: {
ipv6Address: {
serializedName: "ipv6Address",
type: {
name: "String"
}
}
}
}
};
export const CnameRecord: msRest.CompositeMapper = {
serializedName: "CnameRecord",
type: {
name: "Composite",
className: "CnameRecord",
modelProperties: {
cname: {
serializedName: "cname",
type: {
name: "String"
}
}
}
}
};
export const MxRecord: msRest.CompositeMapper = {
serializedName: "MxRecord",
type: {
name: "Composite",
className: "MxRecord",
modelProperties: {
preference: {
serializedName: "preference",
type: {
name: "Number"
}
},
exchange: {
serializedName: "exchange",
type: {
name: "String"
}
}
}
}
};
export const PtrRecord: msRest.CompositeMapper = {
serializedName: "PtrRecord",
type: {
name: "Composite",
className: "PtrRecord",
modelProperties: {
ptrdname: {
serializedName: "ptrdname",
type: {
name: "String"
}
}
}
}
};
export const SoaRecord: msRest.CompositeMapper = {
serializedName: "SoaRecord",
type: {
name: "Composite",
className: "SoaRecord",
modelProperties: {
host: {
serializedName: "host",
type: {
name: "String"
}
},
email: {
serializedName: "email",
type: {
name: "String"
}
},
serialNumber: {
serializedName: "serialNumber",
type: {
name: "Number"
}
},
refreshTime: {
serializedName: "refreshTime",
type: {
name: "Number"
}
},
retryTime: {
serializedName: "retryTime",
type: {
name: "Number"
}
},
expireTime: {
serializedName: "expireTime",
type: {
name: "Number"
}
},
minimumTtl: {
serializedName: "minimumTtl",
type: {
name: "Number"
}
}
}
}
};
export const SrvRecord: msRest.CompositeMapper = {
serializedName: "SrvRecord",
type: {
name: "Composite",
className: "SrvRecord",
modelProperties: {
priority: {
serializedName: "priority",
type: {
name: "Number"
}
},
weight: {
serializedName: "weight",
type: {
name: "Number"
}
},
port: {
serializedName: "port",
type: {
name: "Number"
}
},
target: {
serializedName: "target",
type: {
name: "String"
}
}
}
}
};
export const TxtRecord: msRest.CompositeMapper = {
serializedName: "TxtRecord",
type: {
name: "Composite",
className: "TxtRecord",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
}
}
}
};
export const ProxyResource: msRest.CompositeMapper = {
serializedName: "ProxyResource",
type: {
name: "Composite",
className: "ProxyResource",
modelProperties: {
...Resource.type.modelProperties
}
}
};
export const RecordSet: msRest.CompositeMapper = {
serializedName: "RecordSet",
type: {
name: "Composite",
className: "RecordSet",
modelProperties: {
...ProxyResource.type.modelProperties,
etag: {
serializedName: "etag",
type: {
name: "String"
}
},
metadata: {
serializedName: "properties.metadata",
type: {
name: "Dictionary",
value: {
type: {
name: "String"
}
}
}
},
ttl: {
serializedName: "properties.ttl",
type: {
name: "Number"
}
},
fqdn: {
readOnly: true,
serializedName: "properties.fqdn",
type: {
name: "String"
}
},
isAutoRegistered: {
readOnly: true,
serializedName: "properties.isAutoRegistered",
type: {
name: "Boolean"
}
},
aRecords: {
serializedName: "properties.aRecords",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ARecord"
}
}
}
},
aaaaRecords: {
serializedName: "properties.aaaaRecords",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "AaaaRecord"
}
}
}
},
cnameRecord: {
serializedName: "properties.cnameRecord",
type: {
name: "Composite",
className: "CnameRecord"
}
},
mxRecords: {
serializedName: "properties.mxRecords",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "MxRecord"
}
}
}
},
ptrRecords: {
serializedName: "properties.ptrRecords",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "PtrRecord"
}
}
}
},
soaRecord: {
serializedName: "properties.soaRecord",
type: {
name: "Composite",
className: "SoaRecord"
}
},
srvRecords: {
serializedName: "properties.srvRecords",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SrvRecord"
}
}
}
},
txtRecords: {
serializedName: "properties.txtRecords",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "TxtRecord"
}
}
}
}
}
}
};
export const PrivateZoneListResult: msRest.CompositeMapper = {
serializedName: "PrivateZoneListResult",
type: {
name: "Composite",
className: "PrivateZoneListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "PrivateZone"
}
}
}
},
nextLink: {
readOnly: true,
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const VirtualNetworkLinkListResult: msRest.CompositeMapper = {
serializedName: "VirtualNetworkLinkListResult",
type: {
name: "Composite",
className: "VirtualNetworkLinkListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "VirtualNetworkLink"
}
}
}
},
nextLink: {
readOnly: true,
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const RecordSetListResult: msRest.CompositeMapper = {
serializedName: "RecordSetListResult",
type: {
name: "Composite",
className: "RecordSetListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "RecordSet"
}
}
}
},
nextLink: {
readOnly: true,
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
}; | the_stack |
import { IconButton } from "office-ui-fabric-react/lib/Button";
import { initializeIcons } from '@uifabric/icons';
initializeIcons();
import * as React from "react";
import styles from "./Carousel.module.scss";
import { ICarouselProps, ICarouselState, CarouselButtonsDisplay, CarouselButtonsLocation, CarouselIndicatorShape } from ".";
import { css, ICssInput } from "@uifabric/utilities/lib";
import { ProcessingState } from "./ICarouselState";
import { Spinner } from "office-ui-fabric-react/lib/Spinner";
import { isArray } from "@pnp/common";
import * as telemetry from '../../common/telemetry';
import CarouselImage from "./CarouselImage";
import { CarouselIndicatorsDisplay } from "./ICarouselProps";
export class Carousel extends React.Component<ICarouselProps, ICarouselState> {
private _intervalId: number | undefined;
constructor(props: ICarouselProps) {
super(props);
const currentIndex = props.startIndex ? props.startIndex : 0;
telemetry.track('ReactCarousel', {});
this.state = {
currentIndex,
processingState: ProcessingState.idle
};
}
/**
* Handles component update lifecycle method.
* @param prevProps
*/
public componentDidUpdate(prevProps: ICarouselProps) {
const currProps = this.props;
const prevPropsElementKey = prevProps.triggerPageEvent && prevProps.element ? (prevProps.element as JSX.Element).key : null;
const nextPropsElementKey = currProps.triggerPageEvent && currProps.element ? (currProps.element as JSX.Element).key : null;
// Checking if component is in processing state and the key of the current element has been changed
if (this.state.processingState === ProcessingState.processing && nextPropsElementKey != null && prevPropsElementKey != nextPropsElementKey) {
this.setState({
processingState: ProcessingState.idle
});
this.startCycle(); // restarting cycle when new slide is available
}
}
public componentDidMount() {
// starting auto cycling
this.startCycle();
}
public render(): React.ReactElement<ICarouselProps> {
const { currentIndex, processingState } = this.state;
const {
containerStyles,
contentContainerStyles,
containerButtonsStyles,
prevButtonStyles,
nextButtonStyles,
loadingComponentContainerStyles,
prevButtonIconName = 'ChevronLeft',
nextButtonIconName = 'ChevronRight',
loadingComponent = <Spinner />,
pauseOnHover,
interval,
indicatorsDisplay,
rootStyles,
indicatorsContainerStyles
} = this.props;
const processing = processingState === ProcessingState.processing;
const prevButtonDisabled = processing || this.isCarouselButtonDisabled(false);
const nextButtonDisabled = processing || this.isCarouselButtonDisabled(true);
const element = this.getElementToDisplay(currentIndex);
return (
<div className={this.getMergedStyles(styles.root, rootStyles)}>
<div className={this.getMergedStyles(styles.container, containerStyles)}>
<div className={this.getMergedStyles(this.getButtonContainerStyles(), containerButtonsStyles)}
onClick={() => { if (!prevButtonDisabled) { this.onCarouselButtonClicked(false); } }} >
<IconButton
className={this.getMergedStyles(this.getButtonStyles(false), prevButtonStyles)}
iconProps={{ iconName: prevButtonIconName }}
disabled={prevButtonDisabled}
onClick={() => { this.onCarouselButtonClicked(false); }} />
</div>
<div
className={this.getMergedStyles(styles.contentContainer, contentContainerStyles)}
onMouseOver={pauseOnHover && interval !== null ? this.pauseCycle : undefined}
onTouchStart={pauseOnHover && interval !== null ? this.pauseCycle : undefined}
onMouseLeave={pauseOnHover && interval !== null ? this.startCycle : undefined}
onTouchEnd={pauseOnHover && interval !== null ? this.startCycle : undefined}>
{
processing &&
<div className={this.getMergedStyles(styles.loadingComponent, loadingComponentContainerStyles)}>
{loadingComponent}
</div>
}
{
!processing && this.renderSlide(element)
}
{indicatorsDisplay !== CarouselIndicatorsDisplay.block && this.getIndicatorsElement()}
</div>
<div className={this.getMergedStyles(this.getButtonContainerStyles(), containerButtonsStyles)}
onClick={() => { if (!nextButtonDisabled) { this.onCarouselButtonClicked(true); } }}>
<IconButton
className={this.getMergedStyles(this.getButtonStyles(true), nextButtonStyles)}
iconProps={{ iconName: nextButtonIconName }}
disabled={nextButtonDisabled}
onClick={() => { this.onCarouselButtonClicked(true); }} />
</div>
</div>
{indicatorsDisplay === CarouselIndicatorsDisplay.block &&
<div className={this.getMergedStyles(styles.indicatorsContainer, indicatorsContainerStyles)}>
{this.getIndicatorsElement()}
</div>}
</div>
);
}
private renderSlide = (element: JSX.Element): JSX.Element[] => {
const isAnimated = this.props.slide !== false && !this.props.triggerPageEvent;
const {
currentIndex,
previousIndex,
slideRight
} = this.state;
if (!isAnimated || previousIndex === undefined) {
return [<div className={styles.slideWrapper}>
{element}
</div>];
}
const previousElement = this.getElementToDisplay(previousIndex);
const result: JSX.Element[] = [];
result.push(<div key={currentIndex} className={css(styles.slideWrapper, {
[styles.slideFromLeft]: slideRight,
[styles.slideFromRight]: !slideRight
})}>{element}</div>);
if (slideRight) {
result.push(<div key={previousIndex} className={css(styles.slideWrapper, styles.slideRight, styles.right)}>{previousElement}</div>);
}
else {
result.unshift(<div key={previousIndex} className={css(styles.slideWrapper, styles.slideLeft, styles.left)}>{previousElement}</div>);
}
return result;
}
private getIndicatorsElement = (): JSX.Element | null => {
const {
indicators,
indicatorShape = CarouselIndicatorShape.rectangle,
onRenderIndicator,
triggerPageEvent,
indicatorClassName,
indicatorStyle
} = this.props;
const {
currentIndex = 0
} = this.state;
if (indicators === false) {
return null;
}
const elementsCount = triggerPageEvent ? this.props.elementsCount : isArray(this.props.element) ? (this.props.element as any[]).length : 1;
const indicatorElements: JSX.Element[] = [];
for (let i = 0; i < elementsCount; i++) {
if (onRenderIndicator) {
indicatorElements.push(onRenderIndicator(i, this.onIndicatorClick));
}
else {
indicatorElements.push(<li
className={css(indicatorClassName, {
[styles.active]: i === currentIndex
})}
style={indicatorStyle}
onClick={e => this.onIndicatorClick(e, i)}
/>);
}
}
if (onRenderIndicator) {
return <div className={styles.indicators}>
{indicatorElements}
</div>;
}
else {
return <ol className={css({
[styles.indicators]: true,
[styles.circle]: indicatorShape === CarouselIndicatorShape.circle,
[styles.rectangle]: indicatorShape === CarouselIndicatorShape.rectangle,
[styles.square]: indicatorShape === CarouselIndicatorShape.square
})}>
{indicatorElements}
</ol>;
}
}
private onIndicatorClick = (e: React.MouseEvent<HTMLElement> | React.TouchEvent<HTMLElement>, index: number): void => {
this.startCycle();
if (this.props.onSelect) {
this.props.onSelect(index);
}
const {
currentIndex
} = this.state;
this.setState({
currentIndex: index,
previousIndex: currentIndex,
slideRight: index < currentIndex
});
}
/**
* Return merged styles for Button containers.
*/
private getButtonContainerStyles(): string {
const buttonsDisplayMode = this.props.buttonsDisplay ? this.props.buttonsDisplay : CarouselButtonsDisplay.block;
let buttonDisplayModeCss = "";
switch (buttonsDisplayMode) {
case CarouselButtonsDisplay.block:
buttonDisplayModeCss = styles.blockButtonsContainer;
break;
case CarouselButtonsDisplay.buttonsOnly:
buttonDisplayModeCss = styles.buttonsOnlyContainer;
break;
case CarouselButtonsDisplay.hidden:
buttonDisplayModeCss = styles.hiddenButtonsContainer;
break;
default:
return "";
}
const buttonsLocation = this.props.buttonsLocation ? this.props.buttonsLocation : CarouselButtonsLocation.top;
let buttonsLocationCss = "";
switch (buttonsLocation) {
case CarouselButtonsLocation.top:
buttonsLocationCss = styles.blockButtonsContainer;
break;
case CarouselButtonsLocation.center:
buttonsLocationCss = styles.centralButtonsContainer;
break;
case CarouselButtonsLocation.bottom:
buttonsLocationCss = styles.bottomButtonsContainer;
break;
default:
return "";
}
const result = css(buttonDisplayModeCss, buttonsLocationCss);
return result;
}
/**
* Return merged styles for Buttons.
* @param nextButton
*/
private getButtonStyles(nextButton: boolean) {
const buttonsDisplayMode = this.props.buttonsDisplay ? this.props.buttonsDisplay : CarouselButtonsDisplay.block;
let result = "";
if (buttonsDisplayMode === CarouselButtonsDisplay.buttonsOnly) {
result = nextButton ? styles.buttonsOnlyNextButton : styles.buttonsOnlyPrevButton;
}
return css(result);
}
/**
* Merges the styles of the components.
*/
private getMergedStyles = (componentStyles: string, userStyles?: ICssInput): string => {
const mergedStyles = userStyles ? css(componentStyles, userStyles) : css(componentStyles);
return mergedStyles;
}
/**
* Determines if the carousel button can be clicked.
*/
private isCarouselButtonDisabled = (nextButton: boolean): boolean => {
// false by default
const isInfinite = this.props.isInfinite != undefined ? this.props.isInfinite : false;
const currentIndex = this.state.currentIndex;
let result = false;
// Use validation from parent control or calcualte it based on the current index
if (nextButton) {
result = this.props.canMoveNext != undefined ?
!this.props.canMoveNext :
(currentIndex === (this.props.element as JSX.Element[]).length - 1) && !isInfinite;
} else {
result = this.props.canMovePrev != undefined ?
!this.props.canMovePrev :
(0 === currentIndex) && !isInfinite;
}
return result;
}
/**
* Handles carousel button click.
*/
private onCarouselButtonClicked = (nextButtonClicked: boolean): void => {
this.startCycle();
const currentIndex = this.state.currentIndex;
let nextIndex = this.state.currentIndex;
let processingState = ProcessingState.processing;
// Trigger parent control to update provided element
if (this.props.triggerPageEvent) {
const canMove = nextButtonClicked ? this.props.canMoveNext !== false : this.props.canMovePrev !== false;
if (canMove) {
// Index validation needs to be done by the parent control specyfing canMove Next|Prev
nextIndex = nextButtonClicked ? (currentIndex + 1) : (currentIndex - 1);
// Trigger parent to provide new data
this.props.triggerPageEvent(nextIndex);
processingState = ProcessingState.processing;
}
} else {
nextIndex = this.getNextIndex(nextButtonClicked);
if (nextIndex !== currentIndex) {
if (nextButtonClicked && this.props.onMoveNextClicked) {
this.props.onMoveNextClicked(nextIndex);
}
else if (this.props.onMovePrevClicked) {
this.props.onMovePrevClicked(nextIndex);
}
}
processingState = ProcessingState.idle;
}
if (nextIndex !== currentIndex) {
if (this.props.onSelect) {
this.props.onSelect(nextIndex);
}
this.setState({
currentIndex: nextIndex,
previousIndex: currentIndex,
slideRight: !nextButtonClicked,
processingState
});
}
}
/**
* Returns next index after carousel button is clicked.
*/
private getNextIndex = (nextButtonClicked: boolean): number => {
const currentIndex = this.state.currentIndex;
let nextIndex = currentIndex;
const isInfinite = this.props.isInfinite !== undefined ? this.props.isInfinite : false;
const length = (this.props.element as JSX.Element[]).length;
// Next Button clicked
if (nextButtonClicked) {
// If there is next element
if (currentIndex < length - 1) {
nextIndex = currentIndex + 1;
}
// In no more elements are available but it isInfiniteLoop -> reset index to the first element
else if (isInfinite) {
nextIndex = 0;
}
}
// Prev Button clicked
else {
if (currentIndex - 1 >= 0) {
// If there is previous element
nextIndex = currentIndex - 1;
} else if (isInfinite) {
// If there is no previous element but isInfitineLoop -> reset index to the last element
nextIndex = length - 1;
}
}
return nextIndex;
}
/**
* Returns current element to be displayed.
*/
private getElementToDisplay = (currentIndex: number): JSX.Element => {
const { element } = this.props;
let result: JSX.Element = null;
let arrayLen: number;
// If no element has been provided.
if (!element) {
result = null;
}
else if (isArray(element) && (arrayLen = (element as any[]).length) > 0) {
// Retrieve proper element from the array
if (currentIndex >= 0 && arrayLen > currentIndex) {
const arrayEl = element[currentIndex];
result = 'props' in arrayEl ? arrayEl as JSX.Element :
<CarouselImage {...arrayEl} />;
}
}
else {
result = element as JSX.Element;
}
return result;
}
private startCycle = (): void => {
const {
interval,
triggerPageEvent
} = this.props;
if (this._intervalId) {
if (triggerPageEvent) {
clearTimeout(this._intervalId);
}
else {
clearInterval(this._intervalId);
}
}
if (interval !== null) {
const intervalValue = interval || 5000;
if (!triggerPageEvent) {
this._intervalId = window.setInterval(this.moveNext, intervalValue);
} else {
this._intervalId = window.setTimeout(this.moveNext, intervalValue);
}
}
}
private moveNext = (): void => {
if (!this.isCarouselButtonDisabled(true)) {
this.onCarouselButtonClicked(true);
}
else {
if (this._intervalId) {
if (this.props.triggerPageEvent) {
clearTimeout(this._intervalId);
}
else {
clearInterval(this._intervalId);
}
}
}
}
private pauseCycle = (): void => {
if (this._intervalId) {
if (this.props.triggerPageEvent) {
clearTimeout(this._intervalId);
}
else {
clearInterval(this._intervalId);
}
}
}
} | the_stack |
import * as qlog from '@/data/QlogSchema';
import { PacketizationLane, PacketizationRange, LightweightRange, PacketizationPreprocessor, PacketizationDirection } from './PacketizationDiagramModels';
import QlogConnection from '@/data/Connection';
import PacketizationDiagramDataHelper from './PacketizationDiagramDataHelper';
export default class PacketizationQUICPreProcessor {
public static process( connection:QlogConnection, direction:PacketizationDirection ):Array<PacketizationLane> {
const output = new Array<PacketizationLane>();
PacketizationQUICPreProcessor.frameSizeErrorShown = false;
// clients receive data, servers send it
let QUICEventType = qlog.TransportEventType.packet_received;
let HTTPEventType = qlog.HTTP3EventType.frame_parsed;
// if ( connection.vantagePoint && connection.vantagePoint.type === qlog.VantagePointType.server ){
if ( direction === PacketizationDirection.sending ) {
QUICEventType = qlog.TransportEventType.packet_sent;
HTTPEventType = qlog.HTTP3EventType.frame_created;
}
let HTTPHeadersSentEventType;
if ( connection.vantagePoint && connection.vantagePoint.type === qlog.VantagePointType.server ) {
HTTPHeadersSentEventType = qlog.HTTP3EventType.frame_parsed; // server receives request
}
else if ( connection.vantagePoint && connection.vantagePoint.type === qlog.VantagePointType.client ) {
HTTPHeadersSentEventType = qlog.HTTP3EventType.frame_created; // client sends request
}
let max_packet_size_local = 65527;
let max_packet_size_remote = 65527;
const QUICPacketData:Array<PacketizationRange> = [];
const QUICFrameData:Array<PacketizationRange> = [];
const HTTPData:Array<PacketizationRange> = [];
const StreamData:Array<PacketizationRange> = [];
let QUICPacketIndex = 0;
let QUICFrameIndex = 0;
let HTTPindex = 0;
let QUICmax = 0;
// these two need to be the same, or there is a problem with the trace
let DEBUG_QUICpayloadSize:number = 0;
let DEBUG_HTTPtotalSize:number = 0;
// these two are used to calculate "efficiency" (how much of the QUIC bytes are actually used to transport application-level data)
let QUICtotalSize:number = 0;
let HTTPpayloadSize:number = 0;
const QUICPayloadRangesPerStream:Map<string, Array<LightweightRange>> = new Map<string, Array<LightweightRange>>();
const HTTP3OutstandingFramesPerStream:Map<string, Array<qlog.IEventH3FrameCreated>> = new Map<string, Array<qlog.IEventH3FrameCreated>>();
const HTTPStreamInfo:Map<number,any> = new Map<number,any>();
// this is extracted into a separate function because we want to call it not just when an H3 frame event is discovered,
// but also when we find a QUIC Data frame for a given stream
const processHTTP3Frames = (outstandingFrames:Array<qlog.IEventH3FrameCreated>, payloadRangesForStream:Array<LightweightRange>) => {
while ( outstandingFrames.length > 0 ) {
const frameEvt = outstandingFrames.shift()!;
// HTTP3 header is always the VLIE-encoded frame_type, followed by the VLIE-encoded payload length. The rest depends on the frame.
// for now, we see all frame-specific stuff as the payload (even though that's probably not the best way to look at things... but it's consistent with HTTP2 for now)
const framePayloadLength = parseInt(frameEvt.byte_length!, 10);
const frameHeaderLength = PacketizationPreprocessor.VLIELength( PacketizationPreprocessor.H3FrameTypeToNumber(frameEvt.frame) ) + PacketizationPreprocessor.VLIELength( framePayloadLength );
const totalAvailablePayloadSize = payloadRangesForStream.reduce( (prev, cur) => prev + cur.size, 0 );
if ( totalAvailablePayloadSize < frameHeaderLength + framePayloadLength ) {
// console.log("HTTP3 frame wasn't fully received yet, delaying for a while", frameEvt.stream_id, totalAvailablePayloadSize, " < ", frameHeaderLength + framePayloadLength, JSON.stringify(outstandingFrames));
outstandingFrames.unshift( frameEvt );
break;
}
// else {
// console.log("HTTP3 frame was fully received, adding to the lane!", frameEvt.stream_id, totalAvailablePayloadSize, " >= ", frameHeaderLength + framePayloadLength, JSON.stringify(outstandingFrames));
// }
// console.log("About to extract", frameHeaderLength, frameEvt.stream_id, JSON.stringify(payloadRangesForStream) );
const headerRanges = PacketizationPreprocessor.extractRanges( payloadRangesForStream, frameHeaderLength );
for ( const headerRange of headerRanges ) {
HTTPData.push({
isPayload: false,
contentType: frameEvt.frame.frame_type,
index: HTTPindex,
lowerLayerIndex: QUICFrameIndex - 1,
start: headerRange!.start,
size: headerRange!.size,
color: ( HTTPindex % 2 === 0 ) ? "blue" : "lightblue",
extra: {
frame_length: frameHeaderLength + framePayloadLength,
},
rawPacket: frameEvt,
});
if ( frameEvt.stream_id !== undefined ) {
const streamID = parseInt( frameEvt.stream_id, 10 );
StreamData.push({
isPayload: true,
contentType: frameEvt.frame.frame_type,
index: HTTPindex,
lowerLayerIndex: QUICFrameIndex - 1,
start: headerRange!.start,
size: headerRange!.size,
color: PacketizationDiagramDataHelper.StreamIDToColor( "" + streamID, "HTTP3" )[0],
extra: {
frame_length: frameHeaderLength + framePayloadLength,
},
rawPacket: frameEvt,
});
}
}
DEBUG_HTTPtotalSize += frameHeaderLength;
if ( framePayloadLength > 0 ) {
// console.log("About to extract", framePayloadLength, frameEvt.stream_id, JSON.stringify(payloadRangesForStream) );
const payloadRanges = PacketizationPreprocessor.extractRanges( payloadRangesForStream, framePayloadLength );
for ( const payloadRange of payloadRanges ) {
HTTPData.push({
isPayload: true,
contentType: frameEvt.frame.frame_type,
index: HTTPindex,
lowerLayerIndex: QUICFrameIndex, // belongs to the "previous" TLS record // TODO: this is probably wrong...
start: payloadRange!.start,
size: payloadRange!.size,
color: ( HTTPindex % 2 === 0 ) ? "blue" : "lightblue",
extra: {
frame_length: frameHeaderLength + framePayloadLength,
},
rawPacket: frameEvt,
});
if ( frameEvt.stream_id !== undefined ) {
const streamID = parseInt( frameEvt.stream_id, 10 );
StreamData.push({
isPayload: true,
contentType: frameEvt.frame.frame_type,
index: HTTPindex,
lowerLayerIndex: QUICFrameIndex, // belongs to the "previous" TLS record // TODO: this is probably wrong...
start: payloadRange!.start,
size: payloadRange!.size,
color: PacketizationDiagramDataHelper.StreamIDToColor( "" + streamID, "HTTP3" )[0],
extra: {
frame_length: frameHeaderLength + framePayloadLength,
},
rawPacket: frameEvt,
});
}
}
if ( frameEvt.frame && frameEvt.frame.frame_type === qlog.HTTP3FrameTypeName.data ) {
const streamID = parseInt( frameEvt.stream_id, 10 );
if ( streamID !== 0 ) {
if ( !HTTPStreamInfo.has(streamID) ) {
console.error("PacketizationDiagram: trying to increase payload size sum, but streamID not yet known! Potentially Server Push (which we don't support yet)", streamID, HTTPStreamInfo);
}
else {
HTTPStreamInfo.get( streamID ).total_size += framePayloadLength;
}
}
}
if ( frameEvt.frame &&
(frameEvt.frame.frame_type === qlog.HTTP3FrameTypeName.data ||
frameEvt.frame.frame_type === qlog.HTTP3FrameTypeName.headers) ) {
HTTPpayloadSize += framePayloadLength;
}
DEBUG_HTTPtotalSize += framePayloadLength;
}
++HTTPindex;
}
}; // end processHTTP3frames
for ( const eventRaw of connection.getEvents() ) {
const event = connection.parseEvent( eventRaw );
const rawdata = event.data;
if ( event.name === QUICEventType ){ // packet_sent or _received
const data = rawdata as qlog.IEventPacket;
if ( !data.raw ) {
continue;
}
if ( !data.header || !data.header.packet_type ) {
console.error("PacketizationQUICPreProcessor: packet without header.packet_type set... ignoring", QUICEventType, eventRaw);
continue;
}
if ( !data.raw.length ) {
if ( data.raw.data !== undefined ) {
data.raw.length = data.raw.data.length;
}
else {
console.error("PacketizationQUICPreProcessor: packet without raw.length set... ignoring", QUICEventType, eventRaw);
continue;
}
}
const totalPacketLength = parseInt( "" + data.raw.length, 10 );
const trailerLength = 16; // default authentication tag size is 16 bytes // TODO: support GCM8?
let payloadLength = (data.raw.payload_length ? data.raw.payload_length : 0) - trailerLength;
let headerLength = totalPacketLength - payloadLength;
// lane 1 : QUIC packets
// if not set/known explicitly: try to derive from header type
if ( !data.raw.payload_length ) {
if ( data.header.packet_type === qlog.PacketType.onertt ) {
headerLength = Math.min(4, totalPacketLength); // TODO: actually calculate
}
else {
headerLength = Math.min(4, totalPacketLength); // TODO: actually calculate
}
payloadLength = totalPacketLength - headerLength - trailerLength;
}
// QUIC packet header
QUICPacketData.push({
index: QUICPacketIndex,
isPayload: false,
start: QUICmax,
size: headerLength,
color: ( QUICPacketIndex % 2 === 0 ) ? "black" : "grey",
contentType: data.header.packet_type,
lowerLayerIndex: -1,
rawPacket: data,
});
// QUIC packet payload
QUICPacketData.push({
index: QUICPacketIndex,
isPayload: true,
start: QUICmax + headerLength,
size: payloadLength,
color: ( QUICPacketIndex % 2 === 0 ) ? "black" : "grey",
contentType: data.header.packet_type,
lowerLayerIndex: -1,
rawPacket: data,
});
// QUIC tailer (authentication tag)
QUICPacketData.push({
index: QUICPacketIndex,
isPayload: false,
start: QUICmax + headerLength + payloadLength,
size: trailerLength,
color: ( QUICPacketIndex % 2 === 0 ) ? "black" : "grey",
contentType: data.header.packet_type,
lowerLayerIndex: -1,
rawPacket: data,
});
// lane 2 : QUIC frames
if ( data.frames ) {
let frameStart = QUICmax + headerLength;
const offset = PacketizationQUICPreProcessor.backfillFrameSizes( payloadLength, data.frames );
// offset is needed when we try to guesstimate the frame sizes ourselves (if frame.frame_size isn't set)
// if offset != 0, we've guesstimated wrong
// deal with this by adding a bogus frame
if ( offset !== 0 ) {
const bogus:any = {
header_size: offset,
payload_size: 0,
frame_type: "qvis-injected FILLER (deal with incorrectly guesstimated frame size)",
qvis: { sequence: { hide: true } }, // make sure these don't show up in the sequence diagram
};
data.frames.unshift( bogus as qlog.QuicFrame );
// frameStart += offset; // no longer needed now we add the bogus frame
}
for ( const rawframe of data.frames ) {
const frame = rawframe as any;
if ( frame.header_size > 0 ){
// QUIC frame header
QUICFrameData.push({
index: (frame.frame_type.indexOf("qvis") >= 0 ? -1 : QUICFrameIndex),
isPayload: false,
start: frameStart,
size: frame.header_size,
color: (frame.frame_type.indexOf("qvis") >= 0 ? "yellow" : ( QUICFrameIndex % 2 === 0 ) ? "red" : "pink" ),
contentType: frame.frame_type,
lowerLayerIndex: QUICPacketIndex,
rawPacket: frame,
});
}
if ( frame.payload_size > 0 ) {
// QUIC frame payload
QUICFrameData.push({
index: QUICFrameIndex,
isPayload: true,
start: frameStart + frame.header_size,
size: frame.payload_size,
color: ( QUICFrameIndex % 2 === 0 ) ? "red" : "pink",
contentType: frame.frame_type,
lowerLayerIndex: QUICPacketIndex,
rawPacket: frame,
});
if ( frame.frame_type === qlog.QUICFrameTypeName.stream ) {
DEBUG_QUICpayloadSize += frame.payload_size;
let ranges = QUICPayloadRangesPerStream.get( "" + frame.stream_id );
if ( !ranges ) {
ranges = new Array<LightweightRange>();
QUICPayloadRangesPerStream.set( "" + frame.stream_id, ranges );
}
ranges.push( {start: frameStart + frame.header_size, size: frame.payload_size} );
// if H3 frames are longer than their first QUIC frame, we don't get additional events for them in many logs
// (proper form would be to log data_moved for them, but no-one is doing this correctly yet)
// so... simply re-check everytime we add more payload ranges if H3 frames we were holding back can be processed now
const outstandingFrames = HTTP3OutstandingFramesPerStream.get( "" + frame.stream_id );
if ( outstandingFrames && outstandingFrames.length > 0 ) {
processHTTP3Frames( outstandingFrames, ranges );
}
if ( frame.stream_id !== undefined && frame.stream_id % 2 !== 0 ) {
// unidirectional stream
console.log("PacketizationPreProcessor: data seen on unidirectional stream: ", frame.stream_id, frame, data );
}
}
}
frameStart += frame.header_size + frame.payload_size;
if ( frame.frame_type.indexOf("qvis") < 0 ) {
++QUICFrameIndex;
}
}
}
QUICmax += totalPacketLength;
++QUICPacketIndex;
QUICtotalSize += totalPacketLength;
} // end checking for QUIC events
else if ( event.name === HTTPEventType ) { // frame_created or _parsed
const data = rawdata as qlog.IEventH3Frame;
if ( !data.byte_length ) {
console.error("H3 frame didn't have byte_length set! skipping...", data);
continue;
}
const payloadRangesForStream = QUICPayloadRangesPerStream.get( "" + data.stream_id );
let skipProcessing = false;
if ( !payloadRangesForStream ) {
if ( direction === PacketizationDirection.sending ) {
// when sending, frames are created before they are sent, so frame_created events happen before packet_sent and so also before QUICPayloadRangesPerStream is filled for this stream
// since we already had the setup with the HTTP3OutstandingFramesPerStream to deal with frame_parsed only happening once, even if the full frame hadn't been received yet
// we re-use this here for "too early" frame_created events as well
// the frames are added to outstandingFrames, but not yet processed, which is called when the packet_sent actually happens above
skipProcessing = true;
}
else {
console.error("No payload ranges known for this stream_id, skipping...", payloadRangesForStream, data.stream_id, JSON.stringify(QUICPayloadRangesPerStream) );
continue;
}
}
let outstandingFrames = HTTP3OutstandingFramesPerStream.get( "" + data.stream_id );
if ( !outstandingFrames ) {
outstandingFrames = new Array<qlog.IEventH3FrameCreated>();
HTTP3OutstandingFramesPerStream.set( "" + data.stream_id, outstandingFrames );
}
// H3 frames can be much longer than 1 QUIC packet, but are typically logged after the first QUIC packet they appear in (where the frame header is in)
// so, we hold back frames until they can be fully filled in the payload ranges
outstandingFrames.push( data );
if ( !skipProcessing ) {
processHTTP3Frames( outstandingFrames, payloadRangesForStream! );
}
} // end checking for HTTP3 events
if ( event.name === HTTPHeadersSentEventType && event.data && event.data.frame && event.data.frame.frame_type === qlog.HTTP3FrameTypeName.headers ) {
// want to link HTTP stream IDs to resource URLs that are transported over the stream
const streamID = parseInt( event.data.stream_id, 10 );
if ( !HTTPStreamInfo.has(streamID) ) {
HTTPStreamInfo.set( streamID, { headers: event.data.frame.headers, total_size: 0 } );
}
else {
console.error("PacketizationQUICPreprocessor: HTTPStreamInfo already had an entry for this stream", streamID, HTTPStreamInfo, event.data);
}
}
if ( event.name === qlog.TransportEventType.parameters_set ) {
const data = rawdata as qlog.IEventTransportParametersSet;
if ( data.owner && data.owner === "local" ) {
if ( data.max_packet_size ) {
max_packet_size_local = data.max_packet_size;
}
}
else if ( data.owner && data.owner === "remote" ) {
if ( data.max_packet_size ) {
max_packet_size_remote = data.max_packet_size;
}
}
}
} // end looping over all events
let controlStreamData = 0;
for ( const entry of QUICPayloadRangesPerStream.entries() ) {
// 0, 4, 8 and 1, 5, 9, etc. are normal bidirectional data streams
// 3, 7, 11 and 2,6,10 etc. are typically unidirectional control streams and implementations don't always log frames for them (e.g., QPACK control messages)
// so for these, it's "normal" to have leftover data, we check for that below with DEBUG_HTTPTotalSize
const streamID = parseInt(entry[0], 10);
if ( (streamID + 1) % 4 === 0 ) { // 3, 7, 11, ...
for ( const range of entry[1] ) {
controlStreamData += range.size;
}
}
else if ( (streamID + 2) % 4 === 0 ) { // 2, 6, 10, ...
for ( const range of entry[1] ) {
controlStreamData += range.size;
}
}
else {
if ( entry[1].length !== 0 ) {
console.error( "PacketizationQUICPreprocessor: Not all QUIC payload ranges were used up!", entry[0], JSON.stringify(entry[1]), HTTP3OutstandingFramesPerStream.get("" + entry[0]) );
}
}
}
for ( const entry of HTTP3OutstandingFramesPerStream.entries() ) {
if ( entry[1].length !== 0 ) {
console.error( "PacketizationQUICPreprocessor: Not all HTTP3 frames found a home!", entry[0], JSON.stringify(entry[1]) );
}
}
if ( DEBUG_QUICpayloadSize !== DEBUG_HTTPtotalSize ) {
const adjustedHTTPsizeForControlStreams = DEBUG_HTTPtotalSize + controlStreamData;
if ( DEBUG_QUICpayloadSize !== adjustedHTTPsizeForControlStreams ) {
console.error("QUIC payload size != HTTP3 payload size", "QUIC: ", DEBUG_QUICpayloadSize,
"HTTP: ", DEBUG_HTTPtotalSize,
"HTTP leftover on control streams: ", controlStreamData,
"Diff : ", Math.abs(DEBUG_QUICpayloadSize - DEBUG_HTTPtotalSize) );
}
}
// else {
// console.log("QUIC and HTTP3 payload sizes were equal! as they should be!", DEBUG_QUICpayloadSize, DEBUG_HTTPtotalSize);
// }
const efficiency = HTTPpayloadSize / QUICtotalSize;
output.push( { name: "QUIC packets", CSSClassName: "quicpacket", ranges: QUICPacketData, rangeToString: PacketizationQUICPreProcessor.quicRangeToString, max_size_local: max_packet_size_local, max_size_remote: max_packet_size_remote, efficiency: efficiency } );
output.push( { name: "QUIC frames", CSSClassName: "quicframe", ranges: QUICFrameData, rangeToString: PacketizationQUICPreProcessor.quicFrameRangeToString } );
output.push( { name: "HTTP/3", CSSClassName: "httpframe", ranges: HTTPData, rangeToString: (r:PacketizationRange) => { return PacketizationQUICPreProcessor.httpFrameRangeToString(r, HTTPStreamInfo); } } );
output.push( { name: "Stream IDs", CSSClassName: "streampacket", ranges: StreamData, rangeToString: (r:PacketizationRange) => { return PacketizationQUICPreProcessor.streamRangeToString(r, HTTPStreamInfo); }, heightModifier: 0.6 } );
return output;
}
public static quicRangeToString(data:PacketizationRange) {
let text = "QUIC ";
text += ( data.isPayload ? "Payload #" : (data.size === 16 ? "Trailer (authentication tag) #" : "Header #")) + data.index + " : size " + data.size + "<br/>";
text += "Packet type : " + data.contentType + ", Packet nr : " + data.rawPacket.header.packet_number + "<br/>";
return text;
};
public static quicFrameRangeToString(data:PacketizationRange) {
let text = "QUIC Frame #" + data.index + " : size " + data.size + "<br/>";
text += "Frame type : " + data.contentType + ", stream ID: " + (data.rawPacket && data.rawPacket.stream_id !== undefined ? data.rawPacket.stream_id : "none") + "<br/>";
if ( data.rawPacket && data.rawPacket.fin === true ) {
text += "<b>FIN BIT SET</b>";
}
return text;
};
public static httpFrameRangeToString(data:PacketizationRange, HTTPStreamInfo:Map<number, any>) {
let text = "H3 ";
text += ( data.isPayload ? "Payload #" : "Header #") + data.index + " (QUIC frame index: " + data.lowerLayerIndex + ") : frame size " + data.extra.frame_length + ", partial size : " + data.size + "<br/>";
text += "frame type: " + data.rawPacket.frame.frame_type + ", streamID: " + data.rawPacket.stream_id;
const streamInfo = HTTPStreamInfo.get( parseInt(data.rawPacket.stream_id, 10) );
if ( streamInfo ) {
text += "<br/>";
let method = "";
let path = "";
for ( const header of streamInfo.headers ) {
if ( header.name === ":method" ) {
method = header.value;
}
else if ( header.name === ":path" ) {
path = header.value;
}
}
text += "" + method + ": " + path + "<br/>";
text += "total resource size: " + streamInfo.total_size + "<br/>";
}
return text;
};
public static streamRangeToString(data:PacketizationRange, HTTPStreamInfo:Map<number, any>) {
let text = "H3 ";
text += "streamID: " + data.rawPacket.stream_id;
const streamInfo = HTTPStreamInfo.get( parseInt(data.rawPacket.stream_id, 10) );
if ( streamInfo ) {
text += "<br/>";
let method = "";
let path = "";
for ( const header of streamInfo.headers ) {
if ( header.name === ":method" ) {
method = header.value;
}
else if ( header.name === ":path" ) {
path = header.value;
}
}
text += "" + method + ": " + path + "<br/>";
text += "total resource size: " + streamInfo.total_size + "<br/>";
}
return text;
};
protected static frameSizeErrorShown:boolean = false;
// payloadLength : amount of bytes to distributed across the frames
protected static backfillFrameSizes( payloadLength:number, frames:Array<any> ):number {
let offset = 0;
// before draft-02, the .frame_size field wasn't specced in qlog... so try to backfill it if it isn't there, but use it if it is
// (we assume that if one frame has frame_size set, they all have)
if ( frames[0].frame_size ) { // normal case
let totalFrameLength = 0;
for ( const frame of frames ) {
totalFrameLength += frame.frame_size;
}
offset += (payloadLength - totalFrameLength);
if ( offset !== 0 ){
console.error("PacketizationQUICPreProcessor: frame_sizes don't fill the entire packet payload!", offset);
}
}
else {
if ( !PacketizationQUICPreProcessor.frameSizeErrorShown ) {
console.error("PacketizationQUICPreProcessor: qlog trace does not have frame_size fields set properly. We -guesstimate- them here, so exact frame sizes are expected to be off!");
PacketizationQUICPreProcessor.frameSizeErrorShown = true;
}
let simulatedPayloadLength = 0;
const fakeFrameHeaderSize = 1; // pretend all (STREAM) frames have a header of size 1 (totally wrong, but ok for now)
// set the new frame.frame_size property on all frames, representing the TOTAL frame size (so header + payload)
// we don't know the actual size of the frames, so we start with the ones that we do know (STREAM) and then distribute the leftover size over the rest
let otherFrameCount = 0;
for ( const frame of frames ) {
if ( frame.frame_type === qlog.QUICFrameTypeName.stream ) {
if ( frame.length !== undefined ) {
frame.frame_size = fakeFrameHeaderSize + parseInt(frame.length, 10);// TODO: consider re-transmissions/overlapping data/etc. with .offset
simulatedPayloadLength += frame.frame_size;
}
else {
console.error("PacketizationQUICPreProcessor: stream frame with no length attribute! skipping...", frame);
}
}
if ( frame.frame_type === qlog.QUICFrameTypeName.max_streams ) {
// did strange things to googlevideo endpoint, so hack something that looks more plausible here
frame.frame_size = fakeFrameHeaderSize + 4;
}
else {
otherFrameCount++;
}
}
const leftoverLength = payloadLength - simulatedPayloadLength;
if ( leftoverLength < 0 ) {
console.error("PacketizationQUICPreProcessor: something went wrong calculating frame sizes!", payloadLength, simulatedPayloadLength, frames);
return 0;
}
const lengthPerOtherFrame = Math.floor(leftoverLength / otherFrameCount);
for ( const frame of frames ) {
if ( frame.frame_type !== qlog.QUICFrameTypeName.stream ) {
frame.frame_size = lengthPerOtherFrame;
simulatedPayloadLength += frame.frame_size;
}
}
if ( payloadLength - simulatedPayloadLength < 0 ) {
console.error("PacketizationQUICPreProcessor: payload is longer than payload! Shouldn't happen!", payloadLength, simulatedPayloadLength, lengthPerOtherFrame, frames );
}
offset += (payloadLength - simulatedPayloadLength); // have some rounding errors potentially from the Math.floor, so account for that here
}
// header_size and payload_size aren't in qlog, but we calculate it here for ease of use below
for ( const frame of frames ) {
if ( frame.length ) { // STREAM and CRYPTO for now
frame.header_size = frame.frame_size - frame.length;
frame.payload_size = parseInt( frame.length, 10 );
}
else {
frame.header_size = frame.frame_size;
frame.payload_size = 0;
}
}
return offset;
}
} | the_stack |
import * as t from 'io-ts';
import { RTTI_id } from '../Scalar/RTTI_id';
import { RTTI_Meta, IMeta } from './RTTI_Meta';
import { RTTI_uri } from '../Scalar/RTTI_uri';
import { RTTI_Element, IElement } from './RTTI_Element';
import { RTTI_code } from '../Scalar/RTTI_code';
import { RTTI_Narrative, INarrative } from './RTTI_Narrative';
import { RTTI_ResourceList, IResourceList } from '../Union/RTTI_ResourceList';
import { RTTI_Extension, IExtension } from './RTTI_Extension';
import { RTTI_Identifier, IIdentifier } from './RTTI_Identifier';
import { RTTI_dateTime } from '../Scalar/RTTI_dateTime';
import { RTTI_ContactDetail, IContactDetail } from './RTTI_ContactDetail';
import { RTTI_markdown } from '../Scalar/RTTI_markdown';
import { RTTI_UsageContext, IUsageContext } from './RTTI_UsageContext';
import { RTTI_CodeableConcept, ICodeableConcept } from './RTTI_CodeableConcept';
import { RTTI_canonical } from '../Scalar/RTTI_canonical';
import { RTTI_unsignedInt } from '../Scalar/RTTI_unsignedInt';
import {
RTTI_CodeSystem_Filter,
ICodeSystem_Filter
} from './RTTI_CodeSystem_Filter';
import {
RTTI_CodeSystem_Property,
ICodeSystem_Property
} from './RTTI_CodeSystem_Property';
import {
RTTI_CodeSystem_Concept,
ICodeSystem_Concept
} from './RTTI_CodeSystem_Concept';
export enum CodeSystemStatusKind {
_draft = 'draft',
_active = 'active',
_retired = 'retired',
_unknown = 'unknown'
}
export enum CodeSystemHierarchyMeaningKind {
_groupedBy = 'grouped-by',
_isA = 'is-a',
_partOf = 'part-of',
_classifiedWith = 'classified-with'
}
export enum CodeSystemContentKind {
_notPresent = 'not-present',
_example = 'example',
_fragment = 'fragment',
_complete = 'complete',
_supplement = 'supplement'
}
import { createEnumType } from '../../EnumType';
import { IDomainResource } from './IDomainResource';
export interface ICodeSystem extends IDomainResource {
/**
* This is a CodeSystem resource
*/
resourceType: 'CodeSystem';
/**
* The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes.
*/
id?: string;
/**
* The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content might not always be associated with version changes to the resource.
*/
meta?: IMeta;
/**
* A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content. Often, this is a reference to an implementation guide that defines the special rules along with other profiles etc.
*/
implicitRules?: string;
/**
* Extensions for implicitRules
*/
_implicitRules?: IElement;
/**
* The base language in which the resource is written.
*/
language?: string;
/**
* Extensions for language
*/
_language?: IElement;
/**
* A human-readable narrative that contains a summary of the resource and can be used to represent the content of the resource to a human. The narrative need not encode all the structured data, but is required to contain sufficient detail to make it "clinically safe" for a human to just read the narrative. Resource definitions may define what content should be represented in the narrative to ensure clinical safety.
*/
text?: INarrative;
/**
* These resources do not have an independent existence apart from the resource that contains them - they cannot be identified independently, and nor can they have their own independent transaction scope.
*/
contained?: IResourceList[];
/**
* May be used to represent additional information that is not part of the basic definition of the resource. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension.
*/
extension?: IExtension[];
/**
* May be used to represent additional information that is not part of the basic definition of the resource and that modifies the understanding of the element that contains it and/or the understanding of the containing element's descendants. Usually modifier elements provide negation or qualification. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.
Modifier extensions SHALL NOT change the meaning of any elements on Resource or DomainResource (including cannot change the meaning of modifierExtension itself).
*/
modifierExtension?: IExtension[];
/**
* An absolute URI that is used to identify this code system when it is referenced in a specification, model, design or an instance; also called its canonical identifier. This SHOULD be globally unique and SHOULD be a literal address at which at which an authoritative instance of this code system is (or will be) published. This URL can be the target of a canonical reference. It SHALL remain the same when the code system is stored on different servers. This is used in [Coding](datatypes.html#Coding).system.
*/
url?: string;
/**
* Extensions for url
*/
_url?: IElement;
/**
* A formal identifier that is used to identify this code system when it is represented in other formats, or referenced in a specification, model, design or an instance.
*/
identifier?: IIdentifier[];
/**
* The identifier that is used to identify this version of the code system when it is referenced in a specification, model, design or instance. This is an arbitrary value managed by the code system author and is not expected to be globally unique. For example, it might be a timestamp (e.g. yyyymmdd) if a managed version is not available. There is also no expectation that versions can be placed in a lexicographical sequence. This is used in [Coding](datatypes.html#Coding).version.
*/
version?: string;
/**
* Extensions for version
*/
_version?: IElement;
/**
* A natural language name identifying the code system. This name should be usable as an identifier for the module by machine processing applications such as code generation.
*/
name?: string;
/**
* Extensions for name
*/
_name?: IElement;
/**
* A short, descriptive, user-friendly title for the code system.
*/
title?: string;
/**
* Extensions for title
*/
_title?: IElement;
/**
* The date (and optionally time) when the code system resource was created or revised.
*/
status?: CodeSystemStatusKind;
/**
* Extensions for status
*/
_status?: IElement;
/**
* A Boolean value to indicate that this code system is authored for testing purposes (or education/evaluation/marketing) and is not intended to be used for genuine usage.
*/
experimental?: boolean;
/**
* Extensions for experimental
*/
_experimental?: IElement;
/**
* The date (and optionally time) when the code system was published. The date must change when the business version changes and it must change if the status code changes. In addition, it should change when the substantive content of the code system changes.
*/
date?: string;
/**
* Extensions for date
*/
_date?: IElement;
/**
* The name of the organization or individual that published the code system.
*/
publisher?: string;
/**
* Extensions for publisher
*/
_publisher?: IElement;
/**
* Contact details to assist a user in finding and communicating with the publisher.
*/
contact?: IContactDetail[];
/**
* A free text natural language description of the code system from a consumer's perspective.
*/
description?: string;
/**
* Extensions for description
*/
_description?: IElement;
/**
* The content was developed with a focus and intent of supporting the contexts that are listed. These contexts may be general categories (gender, age, ...) or may be references to specific programs (insurance plans, studies, ...) and may be used to assist with indexing and searching for appropriate code system instances.
*/
useContext?: IUsageContext[];
/**
* A legal or geographic region in which the code system is intended to be used.
*/
jurisdiction?: ICodeableConcept[];
/**
* Explanation of why this code system is needed and why it has been designed as it has.
*/
purpose?: string;
/**
* Extensions for purpose
*/
_purpose?: IElement;
/**
* A copyright statement relating to the code system and/or its contents. Copyright statements are generally legal restrictions on the use and publishing of the code system.
*/
copyright?: string;
/**
* Extensions for copyright
*/
_copyright?: IElement;
/**
* If code comparison is case sensitive when codes within this system are compared to each other.
*/
caseSensitive?: boolean;
/**
* Extensions for caseSensitive
*/
_caseSensitive?: IElement;
/**
* Canonical reference to the value set that contains the entire code system.
*/
valueSet?: string;
/**
* The meaning of the hierarchy of concepts as represented in this resource.
*/
hierarchyMeaning?: CodeSystemHierarchyMeaningKind;
/**
* Extensions for hierarchyMeaning
*/
_hierarchyMeaning?: IElement;
/**
* The code system defines a compositional (post-coordination) grammar.
*/
compositional?: boolean;
/**
* Extensions for compositional
*/
_compositional?: IElement;
/**
* This flag is used to signify that the code system does not commit to concept permanence across versions. If true, a version must be specified when referencing this code system.
*/
versionNeeded?: boolean;
/**
* Extensions for versionNeeded
*/
_versionNeeded?: IElement;
/**
* The extent of the content of the code system (the concepts and codes it defines) are represented in this resource instance.
*/
content?: CodeSystemContentKind;
/**
* Extensions for content
*/
_content?: IElement;
/**
* The canonical URL of the code system that this code system supplement is adding designations and properties to.
*/
supplements?: string;
/**
* The total number of concepts defined by the code system. Where the code system has a compositional grammar, the basis of this count is defined by the system steward.
*/
count?: number;
/**
* Extensions for count
*/
_count?: IElement;
/**
* A filter that can be used in a value set compose statement when selecting concepts using a filter.
*/
filter?: ICodeSystem_Filter[];
/**
* A property defines an additional slot through which additional information can be provided about a concept.
*/
property?: ICodeSystem_Property[];
/**
* Concepts that are in the code system. The concept definitions are inherently hierarchical, but the definitions must be consulted to determine what the meanings of the hierarchical relationships are.
*/
concept?: ICodeSystem_Concept[];
}
export const RTTI_CodeSystem: t.Type<ICodeSystem> = t.recursion(
'ICodeSystem',
() =>
t.intersection([
t.type({
resourceType: t.literal('CodeSystem')
}),
t.partial({
id: RTTI_id,
meta: RTTI_Meta,
implicitRules: RTTI_uri,
_implicitRules: RTTI_Element,
language: RTTI_code,
_language: RTTI_Element,
text: RTTI_Narrative,
contained: t.array(RTTI_ResourceList),
extension: t.array(RTTI_Extension),
modifierExtension: t.array(RTTI_Extension),
url: RTTI_uri,
_url: RTTI_Element,
identifier: t.array(RTTI_Identifier),
version: t.string,
_version: RTTI_Element,
name: t.string,
_name: RTTI_Element,
title: t.string,
_title: RTTI_Element,
status: createEnumType<CodeSystemStatusKind>(
CodeSystemStatusKind,
'CodeSystemStatusKind'
),
_status: RTTI_Element,
experimental: t.boolean,
_experimental: RTTI_Element,
date: RTTI_dateTime,
_date: RTTI_Element,
publisher: t.string,
_publisher: RTTI_Element,
contact: t.array(RTTI_ContactDetail),
description: RTTI_markdown,
_description: RTTI_Element,
useContext: t.array(RTTI_UsageContext),
jurisdiction: t.array(RTTI_CodeableConcept),
purpose: RTTI_markdown,
_purpose: RTTI_Element,
copyright: RTTI_markdown,
_copyright: RTTI_Element,
caseSensitive: t.boolean,
_caseSensitive: RTTI_Element,
valueSet: RTTI_canonical,
hierarchyMeaning: createEnumType<CodeSystemHierarchyMeaningKind>(
CodeSystemHierarchyMeaningKind,
'CodeSystemHierarchyMeaningKind'
),
_hierarchyMeaning: RTTI_Element,
compositional: t.boolean,
_compositional: RTTI_Element,
versionNeeded: t.boolean,
_versionNeeded: RTTI_Element,
content: createEnumType<CodeSystemContentKind>(
CodeSystemContentKind,
'CodeSystemContentKind'
),
_content: RTTI_Element,
supplements: RTTI_canonical,
count: RTTI_unsignedInt,
_count: RTTI_Element,
filter: t.array(RTTI_CodeSystem_Filter),
property: t.array(RTTI_CodeSystem_Property),
concept: t.array(RTTI_CodeSystem_Concept)
})
])
); | the_stack |
import { TypeAssertion,
ValidationContext } from '../types';
import { validate,
getType } from '../validator';
import { compile } from '../compiler';
import { serialize,
deserialize } from '../serializer';
describe("compiler-2", function() {
it("compiler-interface-1", function() {
const schema = compile(`
type X = string;
interface Foo {
a1: number;
a2: bigint;
a3: string;
a4: boolean;
a5: null;
a6: undefined;
a7: X;
a8: integer;
}
`);
{
expect(Array.from(schema.keys())).toEqual([
'X', 'Foo',
]);
}
{
const rhs: TypeAssertion = {
name: 'Foo',
typeName: 'Foo',
kind: 'object',
members: [
['a1', {
name: 'a1',
kind: 'primitive',
primitiveName: 'number',
}],
['a2', {
name: 'a2',
kind: 'primitive',
primitiveName: 'bigint',
}],
['a3', {
name: 'a3',
kind: 'primitive',
primitiveName: 'string',
}],
['a4', {
name: 'a4',
kind: 'primitive',
primitiveName: 'boolean',
}],
['a5', {
name: 'a5',
kind: 'primitive',
primitiveName: 'null',
}],
['a6', {
name: 'a6',
kind: 'primitive',
primitiveName: 'undefined',
}],
['a7', {
name: 'a7',
typeName: 'X',
kind: 'primitive',
primitiveName: 'string',
}],
['a8', {
name: 'a8',
kind: 'primitive',
primitiveName: 'integer',
}],
],
};
// const ty = getType(schema, 'Foo');
for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) {
expect(ty).toEqual(rhs);
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 'C',
a4: true,
a5: null,
a6: void 0,
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual({value: v});
}
{
const v = {
// a1
a2: BigInt(5),
a3: 'C',
a4: true,
a5: null,
a6: void 0,
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
// a2
a3: 'C',
a4: true,
a5: null,
a6: void 0,
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
a2: BigInt(5),
// a3
a4: true,
a5: null,
a6: void 0,
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 'C',
// a4
a5: null,
a6: void 0,
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 'C',
a4: true,
// a5
a6: void 0,
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 'C',
a4: true,
a5: null,
// a6
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 'C',
a4: true,
a5: null,
a6: void 0,
// a7
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 'C',
a4: true,
a5: null,
a6: void 0,
a7: '',
// a8
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: BigInt(99), // wrong
a2: BigInt(5),
a3: 'C',
a4: true,
a5: null,
a6: void 0,
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
a2: 99, // wrong
a3: 'C',
a4: true,
a5: null,
a6: void 0,
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 7, // wrong
a4: true,
a5: null,
a6: void 0,
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 'C',
a4: '', // wrong
a5: null,
a6: void 0,
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 'C',
a4: true,
a5: void 0, // wrong
a6: void 0,
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 'C',
a4: true,
a5: null,
a6: null, // wrong
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 'C',
a4: true,
a5: null,
a6: void 0,
a7: 99, // wrong
a8: 5,
};
expect(validate<any>(v, ty)).toEqual(null);
}
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 'C',
a4: true,
a5: null,
a6: void 0,
a7: '',
a8: 5.5, // wrong
};
expect(validate<any>(v, ty)).toEqual(null);
}
}
}
});
it("compiler-interface-2 (optional types)", function() {
const schemas = [compile(`
type X = string;
interface Foo {
a1?: number;
a2?: bigint;
a3?: string;
a4?: boolean;
a5?: null;
a6?: undefined;
a7?: X;
a8?: integer;
}
`), compile(`
type X = string;
type Foo = Partial<{
a1: number,
a2: bigint,
a3: string,
a4: boolean,
a5: null,
a6: undefined,
a7: X,
a8: integer,
}>;
`), compile(`
type X = string;
type Foo = Partial<{
a1?: number,
a2?: bigint,
a3?: string,
a4?: boolean,
a5?: null,
a6?: undefined,
a7?: X,
a8?: integer,
}>;
`), compile(`
type X = string;
interface Y {
a1: number;
a2: bigint;
a3: string;
a4: boolean;
a5: null;
a6: undefined;
a7: X;
a8: integer;
}
type Foo = Partial<Y>;
`), compile(`
type X = string;
interface Y {
a1?: number;
a2?: bigint;
a3?: string;
a4?: boolean;
a5?: null;
a6?: undefined;
a7?: X;
a8?: integer;
}
type Foo = Partial<Y>;
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X', 'Foo',
]);
expect(Array.from(schemas[1].keys())).toEqual([
'X', 'Foo',
]);
expect(Array.from(schemas[2].keys())).toEqual([
'X', 'Foo',
]);
expect(Array.from(schemas[3].keys())).toEqual([
'X', 'Y', 'Foo',
]);
expect(Array.from(schemas[4].keys())).toEqual([
'X', 'Y', 'Foo',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'Foo',
typeName: 'Foo',
kind: 'object',
members: [
['a1', {
name: 'a1',
kind: 'optional',
optional: {
kind: 'primitive',
primitiveName: 'number',
}
}],
['a2', {
name: 'a2',
kind: 'optional',
optional: {
kind: 'primitive',
primitiveName: 'bigint',
}
}],
['a3', {
name: 'a3',
kind: 'optional',
optional: {
kind: 'primitive',
primitiveName: 'string',
}
}],
['a4', {
name: 'a4',
kind: 'optional',
optional: {
kind: 'primitive',
primitiveName: 'boolean',
}
}],
['a5', {
name: 'a5',
kind: 'optional',
optional: {
kind: 'primitive',
primitiveName: 'null',
}
}],
['a6', {
name: 'a6',
kind: 'optional',
optional: {
kind: 'primitive',
primitiveName: 'undefined',
}
}],
['a7', {
name: 'a7',
typeName: 'X',
kind: 'optional',
optional: {
name: 'X',
typeName: 'X',
kind: 'primitive',
primitiveName: 'string',
}
}],
['a8', {
name: 'a8',
kind: 'optional',
optional: {
kind: 'primitive',
primitiveName: 'integer',
}
}],
],
};
// const ty = getType(schema, 'Foo');
for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) {
expect(ty).toEqual(rhs);
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 'C',
a4: true,
a5: null,
a6: void 0,
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual({value: v});
}
{
const v = {};
expect(validate<any>(v, ty)).toEqual({value: v});
}
}
}
}
});
it("compiler-interface-3 (extends)", function() {
const schemas = [compile(`
type X = string;
interface P {
a1: number;
a2: bigint;
}
interface Q {
a3: string;
a4: boolean;
}
interface R extends Q {
a5: null;
a6: undefined;
}
interface Foo extends P, R {
a7: X;
a8: integer;
}
`), compile(`
interface Foo extends P, R {
a7: X;
a8: integer;
}
interface R extends Q {
a5: null;
a6: undefined;
}
interface Q {
a3: string;
a4: boolean;
}
interface P {
a1: number;
a2: bigint;
}
type X = string;
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X', 'P', 'Q', 'R', 'Foo',
]);
}
{
expect(Array.from(schemas[1].keys())).toEqual([
'Foo', 'R', 'Q', 'P', 'X',
]);
}
for (const schema of schemas) {
{
const tyP: TypeAssertion = {
name: 'P',
typeName: 'P',
kind: 'object',
members: [
['a1', {
name: 'a1',
kind: 'primitive',
primitiveName: 'number',
}],
['a2', {
name: 'a2',
kind: 'primitive',
primitiveName: 'bigint',
}],
],
};
const tyQ: TypeAssertion = {
name: 'Q',
typeName: 'Q',
kind: 'object',
members: [
['a3', {
name: 'a3',
kind: 'primitive',
primitiveName: 'string',
}],
['a4', {
name: 'a4',
kind: 'primitive',
primitiveName: 'boolean',
}],
],
};
const tyR: TypeAssertion = {
name: 'R',
typeName: 'R',
kind: 'object',
baseTypes: [tyQ],
members: [
...([
['a5', {
name: 'a5',
kind: 'primitive',
primitiveName: 'null',
}],
['a6', {
name: 'a6',
kind: 'primitive',
primitiveName: 'undefined',
}],
] as any[]),
...tyQ.members.map(x => [x[0], x[1], true]),
],
};
const rhs: TypeAssertion = {
name: 'Foo',
typeName: 'Foo',
kind: 'object',
baseTypes: [tyP, tyR],
members: [
...([
['a7', {
name: 'a7',
typeName: 'X',
kind: 'primitive',
primitiveName: 'string',
}],
['a8', {
name: 'a8',
kind: 'primitive',
primitiveName: 'integer',
}],
] as any[]),
...tyP.members.map(x => [x[0], x[1], true]),
...tyR.members.map(x => [x[0], x[1], true]),
],
};
// const ty = getType(schema, 'Foo');
for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) {
expect(ty).toEqual(rhs);
{
const v = {
a1: 3,
a2: BigInt(5),
a3: 'C',
a4: true,
a5: null,
a6: void 0,
a7: '',
a8: 5,
};
expect(validate<any>(v, ty)).toEqual({value: v});
}
}
}
}
});
it("compiler-interface-4 (recursive members (repeated))", function() {
const schema = compile(`
interface EntryBase {
name: string;
}
interface File extends EntryBase {
type: 'file';
}
interface Folder extends EntryBase {
type: 'folder';
entries: Entry[];
}
type Entry = File | Folder;
`);
{
expect(Array.from(schema.keys())).toEqual([
'EntryBase', 'File', 'Folder', 'Entry',
]);
}
{
const tyBase: TypeAssertion = {
name: 'EntryBase',
typeName: 'EntryBase',
kind: 'object',
members: [
['name', {
name: 'name',
kind: 'primitive',
primitiveName: 'string',
}],
],
};
const tyEntry: TypeAssertion = {
name: 'Entry',
typeName: 'Entry',
kind: 'one-of',
oneOf: [{
name: 'File',
typeName: 'File',
kind: 'object',
baseTypes: [tyBase],
members: [
['type', {
name: 'type',
kind: 'primitive-value',
value: 'file',
}],
['name', {
name: 'name',
kind: 'primitive',
primitiveName: 'string',
}, true],
],
}, { // replace it by 'rhs' later
name: 'Folder',
typeName: 'Folder',
kind: 'symlink',
symlinkTargetName: 'Folder',
}],
};
const rhs: TypeAssertion = {
name: 'Folder',
typeName: 'Folder',
kind: 'object',
baseTypes: [tyBase],
members: [
['type', {
name: 'type',
kind: 'primitive-value',
value: 'folder',
}],
['entries', {
name: 'entries',
kind: 'repeated',
min: null,
max: null,
repeated: {
name: 'Entry',
typeName: 'Entry',
kind: 'symlink',
symlinkTargetName: 'Entry',
}
}],
['name', {
name: 'name',
kind: 'primitive',
primitiveName: 'string',
}, true],
],
};
tyEntry.oneOf[1] = rhs;
let cnt = 0;
for (const ty of [getType(deserialize(serialize(schema)), 'Entry'), getType(schema, 'Entry')]) {
if (cnt !== 0) {
expect(ty).toEqual(tyEntry);
}
cnt++;
}
// const ty = getType(schema, 'Folder');
cnt = 0;
for (const ty of [getType(deserialize(serialize(schema)), 'Folder'), getType(schema, 'Folder')]) {
if (cnt !== 0) {
expect(ty).toEqual(rhs);
}
{
const v = {
type: 'folder',
name: '/',
entries: [{
type: 'file',
name: 'a',
}, {
type: 'folder',
name: 'b',
entries: [{
type: 'file',
name: 'c',
}],
}],
};
try {
validate<any>(v, ty);
expect(0).toEqual(1);
} catch (e) {
if (cnt === 0) {
expect(e.message).toEqual('Unresolved symbol \'Folder\' is appeared.');
} else {
expect(e.message).toEqual('Unresolved symbol \'Entry\' is appeared.');
}
}
const ctx1: Partial<ValidationContext> = {};
expect(() => validate<any>(v, ty, ctx1)).toThrow(); // unresolved symlink 'Entry'
expect(ctx1.errors).toEqual([...(cnt === 0 ? [{
code: 'ValueUnmatched',
message: '"type" of "File" value should be "file".',
dataPath: 'Folder:entries.(1:repeated).Entry:File:type',
value: 'folder',
constraints: {},
}] : []), {
code: 'InvalidDefinition',
message: cnt === 0 ?
'"Folder" of "Entry" type definition is invalid.' :
'"entries" of "Folder" type definition is invalid.',
dataPath: cnt === 0 ?
'Folder:entries.(1:repeated).Entry:Folder' :
'Folder:entries.(0:repeated).Entry',
constraints: {}
}]);
expect(validate<any>(v, ty, {schema})).toEqual({value: v});
}
cnt++;
}
}
});
it("compiler-interface-5 (recursive members (spread))", function() {
const schema = compile(`
interface EntryBase {
name: string;
}
interface File extends EntryBase {
type: 'file';
}
interface Folder extends EntryBase {
type: 'folder';
entries: [...<Entry>];
}
type Entry = File | Folder;
`);
{
expect(Array.from(schema.keys())).toEqual([
'EntryBase', 'File', 'Folder', 'Entry',
]);
}
{
const tyBase: TypeAssertion = {
name: 'EntryBase',
typeName: 'EntryBase',
kind: 'object',
members: [
['name', {
name: 'name',
kind: 'primitive',
primitiveName: 'string',
}],
],
};
const tyEntry: TypeAssertion = {
name: 'Entry',
typeName: 'Entry',
kind: 'one-of',
oneOf: [{
name: 'File',
typeName: 'File',
kind: 'object',
baseTypes: [tyBase],
members: [
['type', {
name: 'type',
kind: 'primitive-value',
value: 'file',
}],
['name', {
name: 'name',
kind: 'primitive',
primitiveName: 'string',
}, true],
],
}, { // replace it by 'rhs' later
name: 'Folder',
typeName: 'Folder',
kind: 'symlink',
symlinkTargetName: 'Folder',
}],
};
const rhs: TypeAssertion = {
name: 'Folder',
typeName: 'Folder',
kind: 'object',
baseTypes: [tyBase],
members: [
['type', {
name: 'type',
kind: 'primitive-value',
value: 'folder',
}],
['entries', {
name: 'entries',
kind: 'sequence',
sequence: [{
kind: 'spread',
min: null,
max: null,
spread: {
name: 'Entry',
typeName: 'Entry',
kind: 'symlink',
symlinkTargetName: 'Entry',
},
}]
}],
['name', {
name: 'name',
kind: 'primitive',
primitiveName: 'string',
}, true],
],
};
tyEntry.oneOf[1] = rhs;
let cnt = 0;
for (const ty of [getType(deserialize(serialize(schema)), 'Entry'), getType(schema, 'Entry')]) {
if (cnt !== 0) {
expect(ty).toEqual(tyEntry);
}
cnt++;
}
// const ty = getType(schema, 'Folder');
cnt = 0;
for (const ty of [getType(deserialize(serialize(schema)), 'Folder'), getType(schema, 'Folder')]) {
if (cnt !== 0) {
expect(ty).toEqual(rhs);
}
{
const v = {
type: 'folder',
name: '/',
entries: [{
type: 'file',
name: 'a',
}, {
type: 'folder',
name: 'b',
entries: [{
type: 'file',
name: 'c',
}],
}],
};
try {
validate<any>(v, ty);
expect(0).toEqual(1);
} catch (e) {
if (cnt === 0) {
expect(e.message).toEqual('Unresolved symbol \'Folder\' is appeared.');
} else {
expect(e.message).toEqual('Unresolved symbol \'Entry\' is appeared.');
}
}
const ctx1: Partial<ValidationContext> = {};
expect(() => validate<any>(v, ty, ctx1)).toThrow(); // unresolved symlink 'Entry'
expect(ctx1.errors).toEqual([...(cnt === 0 ? [{
code: 'ValueUnmatched',
message: '"type" of "File" value should be "file".',
dataPath: 'Folder:entries.(1:sequence).Entry:File:type',
value: 'folder',
constraints: {},
}] : []), {
code: 'InvalidDefinition',
message: cnt === 0 ?
'"Folder" of "Entry" type definition is invalid.' :
'"entries" of "Folder" type definition is invalid.',
dataPath: cnt === 0 ?
'Folder:entries.(1:sequence).Entry:Folder' :
'Folder:entries.(0:sequence).Entry',
constraints: {}
}]);
expect(validate<any>(v, ty, {schema})).toEqual({value: v});
}
cnt++;
}
}
});
}); | the_stack |
/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable react/button-has-type */
import React, { cloneElement, Component, ReactElement } from 'react';
import * as inputUsageTypes from './types/inputUsageTypes';
import * as dataTypes from './types/dataTypes';
import * as deltaTypes from './types/deltaTypes';
import { getObjectType, isComponentWillChange } from './utils/objectTypes';
interface JsonAddValueState {
inputRefKey: any;
inputRefValue: any;
}
export class JsonAddValue extends Component<JsonAddValueProps, JsonAddValueState> {
constructor(props: JsonAddValueProps) {
super(props);
this.state = {
inputRefKey: null,
inputRefValue: null,
};
// Bind
this.refInputValue = this.refInputValue.bind(this);
this.refInputKey = this.refInputKey.bind(this);
this.onKeydown = this.onKeydown.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
componentDidMount() {
const { inputRefKey, inputRefValue } = this.state;
const { onlyValue } = this.props;
if (inputRefKey && typeof inputRefKey.focus === 'function') {
inputRefKey.focus();
}
if (onlyValue && inputRefValue && typeof inputRefValue.focus === 'function') {
inputRefValue.focus();
}
document.addEventListener('keydown', this.onKeydown);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.onKeydown);
}
onKeydown(event: KeyboardEvent) {
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.repeat) return;
if (event.code === 'Enter' || event.key === 'Enter') {
event.preventDefault();
this.onSubmit();
}
if (event.code === 'Escape' || event.key === 'Escape') {
event.preventDefault();
this.props.handleCancel();
}
}
onSubmit() {
const { handleAdd, onlyValue, onSubmitValueParser, keyPath, deep } = this.props;
const { inputRefKey, inputRefValue } = this.state;
const result: any = {};
// Check if we have the key
if (!onlyValue) {
// Check that there is a key
if (!inputRefKey.value) {
// Empty key => Not authorized
return;
}
result.key = inputRefKey.value;
}
result.newValue = onSubmitValueParser(false, keyPath, deep, result.key, inputRefValue.value);
handleAdd(result);
}
refInputKey(node: any) {
// @ts-ignore
this.state.inputRefKey = node;
}
refInputValue(node: any) {
// @ts-ignore
this.state.inputRefValue = node;
}
render() {
const {
handleCancel,
onlyValue,
addButtonElement,
cancelButtonElement,
inputElementGenerator,
keyPath,
deep,
} = this.props;
const addButtonElementLayout = cloneElement(addButtonElement, {
onClick: this.onSubmit,
});
const cancelButtonElementLayout = cloneElement(cancelButtonElement, {
onClick: handleCancel,
});
const inputElementValue = inputElementGenerator(inputUsageTypes.VALUE, keyPath, deep);
const inputElementValueLayout = cloneElement(inputElementValue, {
placeholder: 'Value',
ref: this.refInputValue,
});
let inputElementKeyLayout = null;
if (!onlyValue) {
const inputElementKey = inputElementGenerator(inputUsageTypes.KEY, keyPath, deep);
inputElementKeyLayout = cloneElement(inputElementKey, {
placeholder: 'Key',
ref: this.refInputKey,
});
}
return (
<span className="rejt-add-value-node">
{inputElementKeyLayout}
{inputElementValueLayout}
{cancelButtonElementLayout}
{addButtonElementLayout}
</span>
);
}
}
interface JsonAddValueProps {
handleAdd: (...args: any) => any;
handleCancel: (...args: any) => any;
onlyValue?: boolean;
addButtonElement?: ReactElement;
cancelButtonElement?: ReactElement;
inputElementGenerator: (...args: any) => any;
keyPath?: string[];
deep?: number;
onSubmitValueParser: (...args: any) => any;
}
// @ts-ignore
JsonAddValue.defaultProps = {
onlyValue: false,
addButtonElement: <button>+</button>,
cancelButtonElement: <button>c</button>,
};
interface JsonArrayState {
data: JsonArrayProps['data'];
name: JsonArrayProps['name'];
keyPath: string[];
deep: JsonArrayProps['deep'];
nextDeep: JsonArrayProps['deep'];
collapsed: any;
addFormVisible: boolean;
}
export class JsonArray extends Component<JsonArrayProps, JsonArrayState> {
constructor(props: JsonArrayProps) {
super(props);
const keyPath = [...props.keyPath, props.name];
this.state = {
data: props.data,
name: props.name,
keyPath,
deep: props.deep,
nextDeep: props.deep + 1,
collapsed: props.isCollapsed(keyPath, props.deep, props.data),
addFormVisible: false,
};
// Bind
this.handleCollapseMode = this.handleCollapseMode.bind(this);
this.handleRemoveItem = this.handleRemoveItem.bind(this);
this.handleAddMode = this.handleAddMode.bind(this);
this.handleAddValueAdd = this.handleAddValueAdd.bind(this);
this.handleAddValueCancel = this.handleAddValueCancel.bind(this);
this.handleEditValue = this.handleEditValue.bind(this);
this.onChildUpdate = this.onChildUpdate.bind(this);
this.renderCollapsed = this.renderCollapsed.bind(this);
this.renderNotCollapsed = this.renderNotCollapsed.bind(this);
}
static getDerivedStateFromProps(props: JsonArrayProps, state: JsonArrayState) {
return props.data !== state.data ? { data: props.data } : null;
}
onChildUpdate(childKey: string, childData: any) {
const { data, keyPath } = this.state;
// Update data
// @ts-ignore
data[childKey] = childData;
// Put new data
this.setState({
data,
});
// Spread
const { onUpdate } = this.props;
const size = keyPath.length;
onUpdate(keyPath[size - 1], data);
}
handleAddMode() {
this.setState({
addFormVisible: true,
});
}
handleCollapseMode() {
this.setState((state) => ({
collapsed: !state.collapsed,
}));
}
handleRemoveItem(index: number) {
return () => {
const { beforeRemoveAction, logger } = this.props;
const { data, keyPath, nextDeep: deep } = this.state;
const oldValue = data[index];
// Before Remove Action
beforeRemoveAction(index, keyPath, deep, oldValue)
.then(() => {
const deltaUpdateResult = {
keyPath,
deep,
key: index,
oldValue,
type: deltaTypes.REMOVE_DELTA_TYPE,
};
data.splice(index, 1);
this.setState({ data });
// Spread new update
const { onUpdate, onDeltaUpdate } = this.props;
onUpdate(keyPath[keyPath.length - 1], data);
// Spread delta update
onDeltaUpdate(deltaUpdateResult);
})
.catch(logger.error);
};
}
handleAddValueAdd({ newValue }: any) {
const { data, keyPath, nextDeep: deep } = this.state;
const { beforeAddAction, logger } = this.props;
beforeAddAction(data.length, keyPath, deep, newValue)
.then(() => {
// Update data
const newData = [...data, newValue];
this.setState({
data: newData,
});
// Cancel add to close
this.handleAddValueCancel();
// Spread new update
const { onUpdate, onDeltaUpdate } = this.props;
onUpdate(keyPath[keyPath.length - 1], newData);
// Spread delta update
onDeltaUpdate({
type: deltaTypes.ADD_DELTA_TYPE,
keyPath,
deep,
key: newData.length - 1,
newValue,
});
})
.catch(logger.error);
}
handleAddValueCancel() {
this.setState({
addFormVisible: false,
});
}
handleEditValue({ key, value }: any) {
return new Promise((resolve, reject) => {
const { beforeUpdateAction } = this.props;
const { data, keyPath, nextDeep: deep } = this.state;
// Old value
const oldValue = data[key];
// Before update action
beforeUpdateAction(key, keyPath, deep, oldValue, value)
.then(() => {
// Update value
data[key] = value;
// Set state
this.setState({
data,
});
// Spread new update
const { onUpdate, onDeltaUpdate } = this.props;
onUpdate(keyPath[keyPath.length - 1], data);
// Spread delta update
onDeltaUpdate({
type: deltaTypes.UPDATE_DELTA_TYPE,
keyPath,
deep,
key,
newValue: value,
oldValue,
});
// Resolve
resolve(undefined);
})
.catch(reject);
});
}
renderCollapsed() {
const { name, data, keyPath, deep } = this.state;
const { handleRemove, readOnly, getStyle, dataType, minusMenuElement } = this.props;
const { minus, collapsed } = getStyle(name, data, keyPath, deep, dataType);
const isReadOnly = readOnly(name, data, keyPath, deep, dataType);
const removeItemButton = cloneElement(minusMenuElement, {
onClick: handleRemove,
className: 'rejt-minus-menu',
style: minus,
});
return (
<span className="rejt-collapsed">
<span className="rejt-collapsed-text" style={collapsed} onClick={this.handleCollapseMode}>
[...] {data.length} {data.length === 1 ? 'item' : 'items'}
</span>
{!isReadOnly && removeItemButton}
</span>
);
}
renderNotCollapsed() {
const { name, data, keyPath, deep, addFormVisible, nextDeep } = this.state;
const {
isCollapsed,
handleRemove,
onDeltaUpdate,
readOnly,
getStyle,
dataType,
addButtonElement,
cancelButtonElement,
editButtonElement,
inputElementGenerator,
textareaElementGenerator,
minusMenuElement,
plusMenuElement,
beforeRemoveAction,
beforeAddAction,
beforeUpdateAction,
logger,
onSubmitValueParser,
} = this.props;
const { minus, plus, delimiter, ul, addForm } = getStyle(name, data, keyPath, deep, dataType);
const isReadOnly = readOnly(name, data, keyPath, deep, dataType);
const addItemButton = cloneElement(plusMenuElement, {
onClick: this.handleAddMode,
className: 'rejt-plus-menu',
style: plus,
});
const removeItemButton = cloneElement(minusMenuElement, {
onClick: handleRemove,
className: 'rejt-minus-menu',
style: minus,
});
const onlyValue = true;
const startObject = '[';
const endObject = ']';
return (
<span className="rejt-not-collapsed">
<span className="rejt-not-collapsed-delimiter" style={delimiter}>
{startObject}
</span>
{!addFormVisible && addItemButton}
<ul className="rejt-not-collapsed-list" style={ul}>
{data.map((item, index) => (
<JsonNode
key={index}
name={`${index}`}
data={item}
keyPath={keyPath}
deep={nextDeep}
isCollapsed={isCollapsed}
handleRemove={this.handleRemoveItem(index)}
handleUpdateValue={this.handleEditValue}
onUpdate={this.onChildUpdate}
onDeltaUpdate={onDeltaUpdate}
readOnly={readOnly}
getStyle={getStyle}
addButtonElement={addButtonElement}
cancelButtonElement={cancelButtonElement}
editButtonElement={editButtonElement}
inputElementGenerator={inputElementGenerator}
textareaElementGenerator={textareaElementGenerator}
minusMenuElement={minusMenuElement}
plusMenuElement={plusMenuElement}
beforeRemoveAction={beforeRemoveAction}
beforeAddAction={beforeAddAction}
beforeUpdateAction={beforeUpdateAction}
logger={logger}
onSubmitValueParser={onSubmitValueParser}
/>
))}
</ul>
{!isReadOnly && addFormVisible && (
<div className="rejt-add-form" style={addForm}>
<JsonAddValue
handleAdd={this.handleAddValueAdd}
handleCancel={this.handleAddValueCancel}
onlyValue={onlyValue}
addButtonElement={addButtonElement}
cancelButtonElement={cancelButtonElement}
inputElementGenerator={inputElementGenerator}
keyPath={keyPath}
deep={deep}
onSubmitValueParser={onSubmitValueParser}
/>
</div>
)}
<span className="rejt-not-collapsed-delimiter" style={delimiter}>
{endObject}
</span>
{!isReadOnly && removeItemButton}
</span>
);
}
render() {
const { name, collapsed, data, keyPath, deep } = this.state;
const { dataType, getStyle } = this.props;
const value = collapsed ? this.renderCollapsed() : this.renderNotCollapsed();
const style = getStyle(name, data, keyPath, deep, dataType);
return (
<div className="rejt-array-node">
<span onClick={this.handleCollapseMode}>
<span className="rejt-name" style={style.name}>
{name} :{' '}
</span>
</span>
{value}
</div>
);
}
}
interface JsonArrayProps {
data: any[];
name: string;
isCollapsed: (...args: any) => any;
keyPath?: string[];
deep?: number;
handleRemove?: (...args: any) => any;
onUpdate: (...args: any) => any;
onDeltaUpdate: (...args: any) => any;
readOnly: (...args: any) => any;
dataType?: string;
getStyle: (...args: any) => any;
addButtonElement?: ReactElement;
cancelButtonElement?: ReactElement;
editButtonElement?: ReactElement;
inputElementGenerator: (...args: any) => any;
textareaElementGenerator: (...args: any) => any;
minusMenuElement?: ReactElement;
plusMenuElement?: ReactElement;
beforeRemoveAction?: (...args: any) => any;
beforeAddAction?: (...args: any) => any;
beforeUpdateAction?: (...args: any) => any;
logger: any;
onSubmitValueParser: (...args: any) => any;
}
// @ts-ignore
JsonArray.defaultProps = {
keyPath: [],
deep: 0,
minusMenuElement: <span> - </span>,
plusMenuElement: <span> + </span>,
};
interface JsonFunctionValueState {
value: JsonFunctionValueProps['value'];
name: JsonFunctionValueProps['name'];
keyPath: string[];
deep: JsonFunctionValueProps['deep'];
editEnabled: boolean;
inputRef: any;
}
export class JsonFunctionValue extends Component<JsonFunctionValueProps, JsonFunctionValueState> {
constructor(props: JsonFunctionValueProps) {
super(props);
const keyPath = [...props.keyPath, props.name];
this.state = {
value: props.value,
name: props.name,
keyPath,
deep: props.deep,
editEnabled: false,
inputRef: null,
};
// Bind
this.handleEditMode = this.handleEditMode.bind(this);
this.refInput = this.refInput.bind(this);
this.handleCancelEdit = this.handleCancelEdit.bind(this);
this.handleEdit = this.handleEdit.bind(this);
this.onKeydown = this.onKeydown.bind(this);
}
static getDerivedStateFromProps(props: JsonFunctionValueProps, state: JsonFunctionValueState) {
return props.value !== state.value ? { value: props.value } : null;
}
componentDidUpdate() {
const { editEnabled, inputRef, name, value, keyPath, deep } = this.state;
const { readOnly, dataType } = this.props;
const readOnlyResult = readOnly(name, value, keyPath, deep, dataType);
if (editEnabled && !readOnlyResult && typeof inputRef.focus === 'function') {
inputRef.focus();
}
}
componentDidMount() {
document.addEventListener('keydown', this.onKeydown);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.onKeydown);
}
onKeydown(event: KeyboardEvent) {
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.repeat) return;
if (event.code === 'Enter' || event.key === 'Enter') {
event.preventDefault();
this.handleEdit();
}
if (event.code === 'Escape' || event.key === 'Escape') {
event.preventDefault();
this.handleCancelEdit();
}
}
handleEdit() {
const { handleUpdateValue, originalValue, logger, onSubmitValueParser, keyPath } = this.props;
const { inputRef, name, deep } = this.state;
if (!inputRef) return;
const newValue = onSubmitValueParser(true, keyPath, deep, name, inputRef.value);
const result = {
value: newValue,
key: name,
};
// Run update
handleUpdateValue(result)
.then(() => {
// Cancel edit mode if necessary
if (!isComponentWillChange(originalValue, newValue)) {
this.handleCancelEdit();
}
})
.catch(logger.error);
}
handleEditMode() {
this.setState({
editEnabled: true,
});
}
refInput(node: any) {
// @ts-ignore
this.state.inputRef = node;
}
handleCancelEdit() {
this.setState({
editEnabled: false,
});
}
render() {
const { name, value, editEnabled, keyPath, deep } = this.state;
const {
handleRemove,
originalValue,
readOnly,
dataType,
getStyle,
editButtonElement,
cancelButtonElement,
textareaElementGenerator,
minusMenuElement,
keyPath: comeFromKeyPath,
} = this.props;
const style = getStyle(name, originalValue, keyPath, deep, dataType);
let result = null;
let minusElement = null;
const resultOnlyResult = readOnly(name, originalValue, keyPath, deep, dataType);
if (editEnabled && !resultOnlyResult) {
const textareaElement = textareaElementGenerator(
inputUsageTypes.VALUE,
comeFromKeyPath,
deep,
name,
originalValue,
dataType
);
const editButtonElementLayout = cloneElement(editButtonElement, {
onClick: this.handleEdit,
});
const cancelButtonElementLayout = cloneElement(cancelButtonElement, {
onClick: this.handleCancelEdit,
});
const textareaElementLayout = cloneElement(textareaElement, {
ref: this.refInput,
defaultValue: originalValue,
});
result = (
<span className="rejt-edit-form" style={style.editForm}>
{textareaElementLayout} {cancelButtonElementLayout}
{editButtonElementLayout}
</span>
);
minusElement = null;
} else {
result = (
<span
className="rejt-value"
style={style.value}
onClick={resultOnlyResult ? null : this.handleEditMode}
>
{value}
</span>
);
const minusMenuLayout = cloneElement(minusMenuElement, {
onClick: handleRemove,
className: 'rejt-minus-menu',
style: style.minus,
});
minusElement = resultOnlyResult ? null : minusMenuLayout;
}
return (
<li className="rejt-function-value-node" style={style.li}>
<span className="rejt-name" style={style.name}>
{name} :{' '}
</span>
{result}
{minusElement}
</li>
);
}
}
interface JsonFunctionValueProps {
name: string;
value: any;
originalValue?: any;
keyPath?: string[];
deep?: number;
handleRemove?: (...args: any) => any;
handleUpdateValue?: (...args: any) => any;
readOnly: (...args: any) => any;
dataType?: string;
getStyle: (...args: any) => any;
editButtonElement?: ReactElement;
cancelButtonElement?: ReactElement;
textareaElementGenerator: (...args: any) => any;
minusMenuElement?: ReactElement;
logger: any;
onSubmitValueParser: (...args: any) => any;
}
// @ts-ignore
JsonFunctionValue.defaultProps = {
keyPath: [],
deep: 0,
handleUpdateValue: () => {},
editButtonElement: <button>e</button>,
cancelButtonElement: <button>c</button>,
minusMenuElement: <span> - </span>,
};
interface JsonNodeState {
data: JsonNodeProps['data'];
name: JsonNodeProps['name'];
keyPath: JsonNodeProps['keyPath'];
deep: JsonNodeProps['deep'];
}
export class JsonNode extends Component<JsonNodeProps, JsonNodeState> {
constructor(props: JsonNodeProps) {
super(props);
this.state = {
data: props.data,
name: props.name,
keyPath: props.keyPath,
deep: props.deep,
};
}
static getDerivedStateFromProps(props: JsonNodeProps, state: JsonNodeState) {
return props.data !== state.data ? { data: props.data } : null;
}
render() {
const { data, name, keyPath, deep } = this.state;
const {
isCollapsed,
handleRemove,
handleUpdateValue,
onUpdate,
onDeltaUpdate,
readOnly,
getStyle,
addButtonElement,
cancelButtonElement,
editButtonElement,
inputElementGenerator,
textareaElementGenerator,
minusMenuElement,
plusMenuElement,
beforeRemoveAction,
beforeAddAction,
beforeUpdateAction,
logger,
onSubmitValueParser,
} = this.props;
const readOnlyTrue = () => true;
const dataType = getObjectType(data);
switch (dataType) {
case dataTypes.ERROR:
return (
<JsonObject
data={data}
name={name}
isCollapsed={isCollapsed}
keyPath={keyPath}
deep={deep}
handleRemove={handleRemove}
onUpdate={onUpdate}
onDeltaUpdate={onDeltaUpdate}
readOnly={readOnlyTrue}
dataType={dataType}
getStyle={getStyle}
addButtonElement={addButtonElement}
cancelButtonElement={cancelButtonElement}
editButtonElement={editButtonElement}
inputElementGenerator={inputElementGenerator}
textareaElementGenerator={textareaElementGenerator}
minusMenuElement={minusMenuElement}
plusMenuElement={plusMenuElement}
beforeRemoveAction={beforeRemoveAction}
beforeAddAction={beforeAddAction}
beforeUpdateAction={beforeUpdateAction}
logger={logger}
onSubmitValueParser={onSubmitValueParser}
/>
);
case dataTypes.OBJECT:
return (
<JsonObject
data={data}
name={name}
isCollapsed={isCollapsed}
keyPath={keyPath}
deep={deep}
handleRemove={handleRemove}
onUpdate={onUpdate}
onDeltaUpdate={onDeltaUpdate}
readOnly={readOnly}
dataType={dataType}
getStyle={getStyle}
addButtonElement={addButtonElement}
cancelButtonElement={cancelButtonElement}
editButtonElement={editButtonElement}
inputElementGenerator={inputElementGenerator}
textareaElementGenerator={textareaElementGenerator}
minusMenuElement={minusMenuElement}
plusMenuElement={plusMenuElement}
beforeRemoveAction={beforeRemoveAction}
beforeAddAction={beforeAddAction}
beforeUpdateAction={beforeUpdateAction}
logger={logger}
onSubmitValueParser={onSubmitValueParser}
/>
);
case dataTypes.ARRAY:
return (
<JsonArray
data={data}
name={name}
isCollapsed={isCollapsed}
keyPath={keyPath}
deep={deep}
handleRemove={handleRemove}
onUpdate={onUpdate}
onDeltaUpdate={onDeltaUpdate}
readOnly={readOnly}
dataType={dataType}
getStyle={getStyle}
addButtonElement={addButtonElement}
cancelButtonElement={cancelButtonElement}
editButtonElement={editButtonElement}
inputElementGenerator={inputElementGenerator}
textareaElementGenerator={textareaElementGenerator}
minusMenuElement={minusMenuElement}
plusMenuElement={plusMenuElement}
beforeRemoveAction={beforeRemoveAction}
beforeAddAction={beforeAddAction}
beforeUpdateAction={beforeUpdateAction}
logger={logger}
onSubmitValueParser={onSubmitValueParser}
/>
);
case dataTypes.STRING:
return (
<JsonValue
name={name}
value={`"${data}"`}
originalValue={data}
keyPath={keyPath}
deep={deep}
handleRemove={handleRemove}
handleUpdateValue={handleUpdateValue}
readOnly={readOnly}
dataType={dataType}
getStyle={getStyle}
cancelButtonElement={cancelButtonElement}
editButtonElement={editButtonElement}
inputElementGenerator={inputElementGenerator}
minusMenuElement={minusMenuElement}
logger={logger}
onSubmitValueParser={onSubmitValueParser}
/>
);
case dataTypes.NUMBER:
return (
<JsonValue
name={name}
value={data}
originalValue={data}
keyPath={keyPath}
deep={deep}
handleRemove={handleRemove}
handleUpdateValue={handleUpdateValue}
readOnly={readOnly}
dataType={dataType}
getStyle={getStyle}
cancelButtonElement={cancelButtonElement}
editButtonElement={editButtonElement}
inputElementGenerator={inputElementGenerator}
minusMenuElement={minusMenuElement}
logger={logger}
onSubmitValueParser={onSubmitValueParser}
/>
);
case dataTypes.BOOLEAN:
return (
<JsonValue
name={name}
value={data ? 'true' : 'false'}
originalValue={data}
keyPath={keyPath}
deep={deep}
handleRemove={handleRemove}
handleUpdateValue={handleUpdateValue}
readOnly={readOnly}
dataType={dataType}
getStyle={getStyle}
cancelButtonElement={cancelButtonElement}
editButtonElement={editButtonElement}
inputElementGenerator={inputElementGenerator}
minusMenuElement={minusMenuElement}
logger={logger}
onSubmitValueParser={onSubmitValueParser}
/>
);
case dataTypes.DATE:
return (
<JsonValue
name={name}
value={data.toISOString()}
originalValue={data}
keyPath={keyPath}
deep={deep}
handleRemove={handleRemove}
handleUpdateValue={handleUpdateValue}
readOnly={readOnlyTrue}
dataType={dataType}
getStyle={getStyle}
cancelButtonElement={cancelButtonElement}
editButtonElement={editButtonElement}
inputElementGenerator={inputElementGenerator}
minusMenuElement={minusMenuElement}
logger={logger}
onSubmitValueParser={onSubmitValueParser}
/>
);
case dataTypes.NULL:
return (
<JsonValue
name={name}
value="null"
originalValue="null"
keyPath={keyPath}
deep={deep}
handleRemove={handleRemove}
handleUpdateValue={handleUpdateValue}
readOnly={readOnly}
dataType={dataType}
getStyle={getStyle}
cancelButtonElement={cancelButtonElement}
editButtonElement={editButtonElement}
inputElementGenerator={inputElementGenerator}
minusMenuElement={minusMenuElement}
logger={logger}
onSubmitValueParser={onSubmitValueParser}
/>
);
case dataTypes.UNDEFINED:
return (
<JsonValue
name={name}
value="undefined"
originalValue="undefined"
keyPath={keyPath}
deep={deep}
handleRemove={handleRemove}
handleUpdateValue={handleUpdateValue}
readOnly={readOnly}
dataType={dataType}
getStyle={getStyle}
cancelButtonElement={cancelButtonElement}
editButtonElement={editButtonElement}
inputElementGenerator={inputElementGenerator}
minusMenuElement={minusMenuElement}
logger={logger}
onSubmitValueParser={onSubmitValueParser}
/>
);
case dataTypes.FUNCTION:
return (
<JsonFunctionValue
name={name}
value={data.toString()}
originalValue={data}
keyPath={keyPath}
deep={deep}
handleRemove={handleRemove}
handleUpdateValue={handleUpdateValue}
readOnly={readOnly}
dataType={dataType}
getStyle={getStyle}
cancelButtonElement={cancelButtonElement}
editButtonElement={editButtonElement}
textareaElementGenerator={textareaElementGenerator}
minusMenuElement={minusMenuElement}
logger={logger}
onSubmitValueParser={onSubmitValueParser}
/>
);
case dataTypes.SYMBOL:
return (
<JsonValue
name={name}
value={data.toString()}
originalValue={data}
keyPath={keyPath}
deep={deep}
handleRemove={handleRemove}
handleUpdateValue={handleUpdateValue}
readOnly={readOnlyTrue}
dataType={dataType}
getStyle={getStyle}
cancelButtonElement={cancelButtonElement}
editButtonElement={editButtonElement}
inputElementGenerator={inputElementGenerator}
minusMenuElement={minusMenuElement}
logger={logger}
onSubmitValueParser={onSubmitValueParser}
/>
);
default:
return null;
}
}
}
interface JsonNodeProps {
name: string;
data?: any;
isCollapsed: (...args: any) => any;
keyPath?: string[];
deep?: number;
handleRemove?: (...args: any) => any;
handleUpdateValue?: (...args: any) => any;
onUpdate: (...args: any) => any;
onDeltaUpdate: (...args: any) => any;
readOnly: (...args: any) => any;
getStyle: (...args: any) => any;
addButtonElement?: ReactElement;
cancelButtonElement?: ReactElement;
editButtonElement?: ReactElement;
inputElementGenerator: (...args: any) => any;
textareaElementGenerator: (...args: any) => any;
minusMenuElement?: ReactElement;
plusMenuElement?: ReactElement;
beforeRemoveAction?: (...args: any) => any;
beforeAddAction?: (...args: any) => any;
beforeUpdateAction?: (...args: any) => any;
logger: object;
onSubmitValueParser: (...args: any) => any;
}
/// @ts-ignore
JsonNode.defaultProps = {
keyPath: [],
deep: 0,
};
interface JsonObjectState {
name: string;
collapsed: ReturnType<JsonObjectProps['isCollapsed']>;
data: JsonObjectProps['data'];
keyPath: JsonObjectProps['keyPath'];
deep: JsonObjectProps['deep'];
nextDeep: number;
addFormVisible: boolean;
}
export class JsonObject extends Component<JsonObjectProps, JsonObjectState> {
constructor(props: JsonObjectProps) {
super(props);
const keyPath = props.deep === -1 ? [] : [...props.keyPath, props.name];
this.state = {
name: props.name,
data: props.data,
keyPath,
deep: props.deep,
nextDeep: props.deep + 1,
collapsed: props.isCollapsed(keyPath, props.deep, props.data),
addFormVisible: false,
};
// Bind
this.handleCollapseMode = this.handleCollapseMode.bind(this);
this.handleRemoveValue = this.handleRemoveValue.bind(this);
this.handleAddMode = this.handleAddMode.bind(this);
this.handleAddValueAdd = this.handleAddValueAdd.bind(this);
this.handleAddValueCancel = this.handleAddValueCancel.bind(this);
this.handleEditValue = this.handleEditValue.bind(this);
this.onChildUpdate = this.onChildUpdate.bind(this);
this.renderCollapsed = this.renderCollapsed.bind(this);
this.renderNotCollapsed = this.renderNotCollapsed.bind(this);
}
static getDerivedStateFromProps(props: JsonObjectProps, state: JsonObjectState) {
return props.data !== state.data ? { data: props.data } : null;
}
onChildUpdate(childKey: string, childData: any) {
const { data, keyPath } = this.state;
// Update data
// @ts-ignore
data[childKey] = childData;
// Put new data
this.setState({
data,
});
// Spread
const { onUpdate } = this.props;
const size = keyPath.length;
onUpdate(keyPath[size - 1], data);
}
handleAddMode() {
this.setState({
addFormVisible: true,
});
}
handleAddValueCancel() {
this.setState({
addFormVisible: false,
});
}
handleAddValueAdd({ key, newValue }: any) {
const { data, keyPath, nextDeep: deep } = this.state;
const { beforeAddAction, logger } = this.props;
beforeAddAction(key, keyPath, deep, newValue)
.then(() => {
// Update data
// @ts-ignore
data[key] = newValue;
this.setState({
data,
});
// Cancel add to close
this.handleAddValueCancel();
// Spread new update
const { onUpdate, onDeltaUpdate } = this.props;
onUpdate(keyPath[keyPath.length - 1], data);
// Spread delta update
onDeltaUpdate({
type: deltaTypes.ADD_DELTA_TYPE,
keyPath,
deep,
key,
newValue,
});
})
.catch(logger.error);
}
handleRemoveValue(key: string) {
return () => {
const { beforeRemoveAction, logger } = this.props;
const { data, keyPath, nextDeep: deep } = this.state;
// @ts-ignore
const oldValue = data[key];
// Before Remove Action
beforeRemoveAction(key, keyPath, deep, oldValue)
.then(() => {
const deltaUpdateResult = {
keyPath,
deep,
key,
oldValue,
type: deltaTypes.REMOVE_DELTA_TYPE,
};
// @ts-ignore
delete data[key];
this.setState({ data });
// Spread new update
const { onUpdate, onDeltaUpdate } = this.props;
onUpdate(keyPath[keyPath.length - 1], data);
// Spread delta update
onDeltaUpdate(deltaUpdateResult);
})
.catch(logger.error);
};
}
handleCollapseMode() {
this.setState((state) => ({
collapsed: !state.collapsed,
}));
}
handleEditValue({ key, value }: any) {
return new Promise<void>((resolve, reject) => {
const { beforeUpdateAction } = this.props;
const { data, keyPath, nextDeep: deep } = this.state;
// Old value
// @ts-ignore
const oldValue = data[key];
// Before update action
beforeUpdateAction(key, keyPath, deep, oldValue, value)
.then(() => {
// Update value
// @ts-ignore
data[key] = value;
// Set state
this.setState({
data,
});
// Spread new update
const { onUpdate, onDeltaUpdate } = this.props;
onUpdate(keyPath[keyPath.length - 1], data);
// Spread delta update
onDeltaUpdate({
type: deltaTypes.UPDATE_DELTA_TYPE,
keyPath,
deep,
key,
newValue: value,
oldValue,
});
// Resolve
resolve();
})
.catch(reject);
});
}
renderCollapsed() {
const { name, keyPath, deep, data } = this.state;
const { handleRemove, readOnly, dataType, getStyle, minusMenuElement } = this.props;
const { minus, collapsed } = getStyle(name, data, keyPath, deep, dataType);
const keyList = Object.getOwnPropertyNames(data);
const isReadOnly = readOnly(name, data, keyPath, deep, dataType);
const removeItemButton = cloneElement(minusMenuElement, {
onClick: handleRemove,
className: 'rejt-minus-menu',
style: minus,
});
return (
<span className="rejt-collapsed">
<span className="rejt-collapsed-text" style={collapsed} onClick={this.handleCollapseMode}>
{'{...}'} {keyList.length} {keyList.length === 1 ? 'key' : 'keys'}
</span>
{!isReadOnly && removeItemButton}
</span>
);
}
renderNotCollapsed() {
const { name, data, keyPath, deep, nextDeep, addFormVisible } = this.state;
const {
isCollapsed,
handleRemove,
onDeltaUpdate,
readOnly,
getStyle,
dataType,
addButtonElement,
cancelButtonElement,
editButtonElement,
inputElementGenerator,
textareaElementGenerator,
minusMenuElement,
plusMenuElement,
beforeRemoveAction,
beforeAddAction,
beforeUpdateAction,
logger,
onSubmitValueParser,
} = this.props;
const { minus, plus, addForm, ul, delimiter } = getStyle(name, data, keyPath, deep, dataType);
const keyList = Object.getOwnPropertyNames(data);
const isReadOnly = readOnly(name, data, keyPath, deep, dataType);
const addItemButton = cloneElement(plusMenuElement, {
onClick: this.handleAddMode,
className: 'rejt-plus-menu',
style: plus,
});
const removeItemButton = cloneElement(minusMenuElement, {
onClick: handleRemove,
className: 'rejt-minus-menu',
style: minus,
});
const list = keyList.map((key) => (
<JsonNode
key={key}
name={key}
data={data[key]}
keyPath={keyPath}
deep={nextDeep}
isCollapsed={isCollapsed}
handleRemove={this.handleRemoveValue(key)}
handleUpdateValue={this.handleEditValue}
onUpdate={this.onChildUpdate}
onDeltaUpdate={onDeltaUpdate}
readOnly={readOnly}
getStyle={getStyle}
addButtonElement={addButtonElement}
cancelButtonElement={cancelButtonElement}
editButtonElement={editButtonElement}
inputElementGenerator={inputElementGenerator}
textareaElementGenerator={textareaElementGenerator}
minusMenuElement={minusMenuElement}
plusMenuElement={plusMenuElement}
beforeRemoveAction={beforeRemoveAction}
beforeAddAction={beforeAddAction}
beforeUpdateAction={beforeUpdateAction}
logger={logger}
onSubmitValueParser={onSubmitValueParser}
/>
));
const startObject = '{';
const endObject = '}';
return (
<span className="rejt-not-collapsed">
<span className="rejt-not-collapsed-delimiter" style={delimiter}>
{startObject}
</span>
{!isReadOnly && addItemButton}
<ul className="rejt-not-collapsed-list" style={ul}>
{list}
</ul>
{!isReadOnly && addFormVisible && (
<div className="rejt-add-form" style={addForm}>
<JsonAddValue
handleAdd={this.handleAddValueAdd}
handleCancel={this.handleAddValueCancel}
addButtonElement={addButtonElement}
cancelButtonElement={cancelButtonElement}
inputElementGenerator={inputElementGenerator}
keyPath={keyPath}
deep={deep}
onSubmitValueParser={onSubmitValueParser}
/>
</div>
)}
<span className="rejt-not-collapsed-delimiter" style={delimiter}>
{endObject}
</span>
{!isReadOnly && removeItemButton}
</span>
);
}
render() {
const { name, collapsed, data, keyPath, deep } = this.state;
const { getStyle, dataType } = this.props;
const value = collapsed ? this.renderCollapsed() : this.renderNotCollapsed();
const style = getStyle(name, data, keyPath, deep, dataType);
return (
<div className="rejt-object-node">
<span onClick={this.handleCollapseMode}>
<span className="rejt-name" style={style.name}>
{name} :{' '}
</span>
</span>
{value}
</div>
);
}
}
interface JsonObjectProps {
data: Record<string, any>;
name: string;
isCollapsed: (...args: any) => any;
keyPath?: string[];
deep?: number;
handleRemove?: (...args: any) => any;
onUpdate: (...args: any) => any;
onDeltaUpdate: (...args: any) => any;
readOnly: (...args: any) => any;
dataType?: string;
getStyle: (...args: any) => any;
addButtonElement?: ReactElement;
cancelButtonElement?: ReactElement;
editButtonElement?: ReactElement;
inputElementGenerator: (...args: any) => any;
textareaElementGenerator: (...args: any) => any;
minusMenuElement?: ReactElement;
plusMenuElement?: ReactElement;
beforeRemoveAction?: (...args: any) => any;
beforeAddAction?: (...args: any) => any;
beforeUpdateAction?: (...args: any) => any;
logger: any;
onSubmitValueParser: (...args: any) => any;
}
// @ts-ignore
JsonObject.defaultProps = {
keyPath: [],
deep: 0,
minusMenuElement: <span> - </span>,
plusMenuElement: <span> + </span>,
};
interface JsonValueState {
value: JsonValueProps['value'];
name: JsonValueProps['name'];
keyPath: string[];
deep: JsonValueProps['deep'];
editEnabled: boolean;
inputRef: any;
}
export class JsonValue extends Component<JsonValueProps, JsonValueState> {
constructor(props: JsonValueProps) {
super(props);
const keyPath = [...props.keyPath, props.name];
this.state = {
value: props.value,
name: props.name,
keyPath,
deep: props.deep,
editEnabled: false,
inputRef: null,
};
// Bind
this.handleEditMode = this.handleEditMode.bind(this);
this.refInput = this.refInput.bind(this);
this.handleCancelEdit = this.handleCancelEdit.bind(this);
this.handleEdit = this.handleEdit.bind(this);
this.onKeydown = this.onKeydown.bind(this);
}
static getDerivedStateFromProps(props: JsonValueProps, state: JsonValueState) {
return props.value !== state.value ? { value: props.value } : null;
}
componentDidUpdate() {
const { editEnabled, inputRef, name, value, keyPath, deep } = this.state;
const { readOnly, dataType } = this.props;
const isReadOnly = readOnly(name, value, keyPath, deep, dataType);
if (editEnabled && !isReadOnly && typeof inputRef.focus === 'function') {
inputRef.focus();
}
}
componentDidMount() {
document.addEventListener('keydown', this.onKeydown);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.onKeydown);
}
onKeydown(event: KeyboardEvent) {
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.repeat) return;
if (event.code === 'Enter' || event.key === 'Enter') {
event.preventDefault();
this.handleEdit();
}
if (event.code === 'Escape' || event.key === 'Escape') {
event.preventDefault();
this.handleCancelEdit();
}
}
handleEdit() {
const { handleUpdateValue, originalValue, logger, onSubmitValueParser, keyPath } = this.props;
const { inputRef, name, deep } = this.state;
if (!inputRef) return;
const newValue = onSubmitValueParser(true, keyPath, deep, name, inputRef.value);
const result = {
value: newValue,
key: name,
};
// Run update
handleUpdateValue(result)
.then(() => {
// Cancel edit mode if necessary
if (!isComponentWillChange(originalValue, newValue)) {
this.handleCancelEdit();
}
})
.catch(logger.error);
}
handleEditMode() {
this.setState({
editEnabled: true,
});
}
refInput(node: any) {
// @ts-ignore
this.state.inputRef = node;
}
handleCancelEdit() {
this.setState({
editEnabled: false,
});
}
render() {
const { name, value, editEnabled, keyPath, deep } = this.state;
const {
handleRemove,
originalValue,
readOnly,
dataType,
getStyle,
editButtonElement,
cancelButtonElement,
inputElementGenerator,
minusMenuElement,
keyPath: comeFromKeyPath,
} = this.props;
const style = getStyle(name, originalValue, keyPath, deep, dataType);
const isReadOnly = readOnly(name, originalValue, keyPath, deep, dataType);
const isEditing = editEnabled && !isReadOnly;
const inputElement = inputElementGenerator(
inputUsageTypes.VALUE,
comeFromKeyPath,
deep,
name,
originalValue,
dataType
);
const editButtonElementLayout = cloneElement(editButtonElement, {
onClick: this.handleEdit,
});
const cancelButtonElementLayout = cloneElement(cancelButtonElement, {
onClick: this.handleCancelEdit,
});
const inputElementLayout = cloneElement(inputElement, {
ref: this.refInput,
defaultValue: JSON.stringify(originalValue),
});
const minusMenuLayout = cloneElement(minusMenuElement, {
onClick: handleRemove,
className: 'rejt-minus-menu',
style: style.minus,
});
return (
<li className="rejt-value-node" style={style.li}>
<span className="rejt-name" style={style.name}>
{name}
{' : '}
</span>
{isEditing ? (
<span className="rejt-edit-form" style={style.editForm}>
{inputElementLayout} {cancelButtonElementLayout}
{editButtonElementLayout}
</span>
) : (
<span
className="rejt-value"
style={style.value}
onClick={isReadOnly ? null : this.handleEditMode}
>
{String(value)}
</span>
)}
{!isReadOnly && !isEditing && minusMenuLayout}
</li>
);
}
}
interface JsonValueProps {
name: string;
value: any;
originalValue?: any;
keyPath?: string[];
deep?: number;
handleRemove?: (...args: any) => any;
handleUpdateValue?: (...args: any) => any;
readOnly: (...args: any) => any;
dataType?: string;
getStyle: (...args: any) => any;
editButtonElement?: ReactElement;
cancelButtonElement?: ReactElement;
inputElementGenerator: (...args: any) => any;
minusMenuElement?: ReactElement;
logger: any;
onSubmitValueParser: (...args: any) => any;
}
// @ts-ignore
JsonValue.defaultProps = {
keyPath: [],
deep: 0,
handleUpdateValue: () => Promise.resolve(),
editButtonElement: <button>e</button>,
cancelButtonElement: <button>c</button>,
minusMenuElement: <span> - </span>,
}; | the_stack |
import React, { Fragment, useCallback, FC, useState } from 'react';
import { scaleOrdinal, scaleLinear, scalePoint } from 'd3-scale';
import { range } from 'd3-array';
import { Tooltip } from 'realayers';
import { Placement } from 'rdk';
import { HiveNode } from './HiveNode';
import { HiveAxis } from './HiveAxis';
import { HiveLink } from './HiveLink';
import { HiveLabel } from './HiveLabel';
import { HiveTooltip } from './HiveTooltip';
import { Node, Link, Axis } from './types';
import classNames from 'classnames';
import { ChartContainer } from '../common/containers';
interface NodeEventData {
nativeEvent: any;
node: Node;
links: Link[];
}
interface LinkEventData {
nativeEvent: any;
link: Link;
}
export interface HivePlotProps {
axis: Axis[];
nodes: Node[];
links: Link[];
activeIds?: string[];
disabled?: boolean;
label: {
show: boolean;
padding?: number;
};
width?: number;
height?: number;
innerRadius: number;
className?: any;
onNodeClick: (data: NodeEventData) => void;
onNodeMouseOver: (data: NodeEventData) => void;
onLinkMouseOver: (data: LinkEventData) => void;
onNodeMouseOut: (data: NodeEventData) => void;
onLinkMouseOut: (data: LinkEventData) => void;
tooltip: {
show: boolean;
placement: Placement;
formatter: (
axis: Axis[],
nodes: Node[],
link?: Link,
node?: Node
) => React.ReactNode;
};
colorScheme: {
axis: string[];
domain: string[];
};
}
export const HivePlot: FC<Partial<HivePlotProps>> = ({
axis = [],
nodes = [],
links = [],
disabled = false,
activeIds = [],
label = {
show: true,
padding: 10
},
width,
height,
innerRadius = 20,
className,
onNodeClick = () => undefined,
onNodeMouseOver = () => undefined,
onLinkMouseOver = () => undefined,
onNodeMouseOut = () => undefined,
onLinkMouseOut = () => undefined,
tooltip = {
show: true,
placement: 'top',
formatter: (attr: any) => attr.value
},
colorScheme = {
axis: ['#b1b2b6'],
domain: ['#b1b2b6']
}
}) => {
const [tooltipReference, setTooltipReference] = useState<EventTarget | null>(
null
);
const [nodeTooltipData, setNodeTooltipData] = useState<Node | null>(null);
const [linkTooltipData, setLinkTooltipData] = useState<Link | null>(null);
const [active, setActive] = useState<{ [k: string]: boolean } | null>(null);
const onNodeMouseOverLocal = useCallback(
(node: Node, event: MouseEvent) => {
if (!disabled) {
const activeNodeIndex = nodes.indexOf(node);
const activeNodes = {};
for (const link of links) {
const { source, target } = link;
if (source.value === node.value || target.value === node.value) {
const next = target.value === node.value ? source : target;
const idx = nodes.indexOf(next);
activeNodes[`node-${idx}`] = true;
}
}
setTooltipReference(event.target);
setNodeTooltipData(node);
setActive({
[`node-${activeNodeIndex}`]: true,
...activeNodes,
...links.reduce((accumulator, link, i) => {
if (
link.source.value === node.value ||
link.target.value === node.value
) {
accumulator[`link-${i}`] = true;
}
return accumulator;
}, {})
});
}
onNodeMouseOver({
nativeEvent: event,
node,
links: getLinksForNode(node)
});
},
[links, nodes, onNodeMouseOver, disabled]
);
const activateAdjacentLinks = useCallback(
(links: Link[], target: Node, accumulator: {}) => {
const activeLinks: any[] = [];
links.forEach((childLink, index) => {
if (target === childLink.source) {
if (!accumulator[`link-${index}`]) {
accumulator[`link-${index}`] = true;
activeLinks.push(
childLink,
...activateAdjacentLinks(links, childLink.target, accumulator)
);
}
}
});
return activeLinks;
},
[]
);
const activateLink = useCallback(
(link: Link) => {
const activeLinkIndex = links.indexOf(link);
const activeLinksMap = {
[`link-${activeLinkIndex}`]: true
};
const activeLinks = [
link,
...activateAdjacentLinks(links, link.target, activeLinksMap)
];
setActive({
...activeLinksMap,
...nodes.reduce((accumulator, node, i) => {
for (const activeLink of activeLinks) {
const { source, target } = activeLink;
if (node === source || node === target) {
accumulator[`node-${i}`] = true;
}
}
return accumulator;
}, {})
});
},
[nodes, links]
);
const onLinkMouseOverLocal = useCallback(
(link: Link, event: MouseEvent) => {
if (!disabled) {
setTooltipReference(event.target);
setLinkTooltipData(link);
activateLink(link);
}
onLinkMouseOver({
nativeEvent: event,
link
});
},
[onLinkMouseOver, disabled]
);
const getLinksForNode = useCallback(
(node: Node): Link[] =>
links.filter(
(link) =>
link.source.value === node.value || link.target.value === node.value
),
[links]
);
const resetActive = useCallback(() => {
setActive(null);
setLinkTooltipData(null);
setNodeTooltipData(null);
setTooltipReference(null);
}, []);
const onNodeMouseOutLocal = useCallback(
(node: Node, event: MouseEvent) => {
resetActive();
onNodeMouseOut({
nativeEvent: event,
node,
links: getLinksForNode(node)
});
},
[onNodeMouseOut]
);
const onLinkMouseOutLocal = useCallback(
(link: Link, event: MouseEvent) => {
resetActive();
onLinkMouseOut({
nativeEvent: event,
link
});
},
[onLinkMouseOut]
);
const onNodeClickLocal = useCallback(
(node: Node, event: MouseEvent) => {
if (!disabled) {
onNodeClick({
nativeEvent: event,
node,
links: getLinksForNode(node)
});
}
},
[disabled, onNodeClick]
);
const prepareData = useCallback(
({ dimension, innerRadius, colorScheme, axis, label }) => {
let outerRadius = dimension / 2;
if (label.show) {
outerRadius = outerRadius - (10 + label.padding);
}
return {
angle: scalePoint()
.domain(range(axis.length + 1) as any)
.range([0, 2 * Math.PI]),
radius: scaleLinear().range([innerRadius, outerRadius]),
axisColor: scaleOrdinal(colorScheme.axis).domain(range(20) as any),
domainColor: scaleOrdinal(colorScheme.domain).domain(range(20) as any),
outerRadius
};
},
[]
);
const renderAxis = useCallback(
({ angle, radius, axisColor, outerRadius }) => (
<Fragment>
{axis.map((a, i) => (
<g key={`axis-${a.attribute}`}>
<HiveAxis
angle={angle}
index={i}
color={axisColor}
radius={radius}
/>
{label.show && (
<HiveLabel
index={i}
text={a.label}
label={label}
outerRadius={outerRadius}
angle={angle}
/>
)}
</g>
))}
</Fragment>
),
[axis, label]
);
const isActive = useCallback(
(nodeOrLink: Node | Link, index: number, type: 'node' | 'link') => {
// If no there is nothing active, then everything is active.
if (!active && !activeIds!.length) {
return true;
}
// If this node is active because it is being hovered
if (active && active[`${type}-${index}`]) {
return true;
}
// If the ID matches one of the active IDs passed in the props
if (
!!activeIds!.length &&
!!nodeOrLink.id &&
activeIds!.includes(nodeOrLink.id)
) {
return true;
}
return false;
},
[activeIds, active]
);
const renderLinks = useCallback(
({ angle, radius, domainColor }) => (
<Fragment>
{links.map((link, i) => {
return (
<HiveLink
key={`${link.value}-${i}`}
color={link.color || domainColor}
active={isActive(link, i, 'link')}
angle={angle}
radius={radius}
link={link}
onMouseOver={(event: MouseEvent) =>
onLinkMouseOverLocal(link, event)
}
onMouseOut={(event: MouseEvent) =>
onLinkMouseOutLocal(link, event)
}
/>
);
})}
</Fragment>
),
[links]
);
const renderNodes = useCallback(
({ angle, radius, domainColor }) => (
<Fragment>
{nodes.map((node, i) => (
<HiveNode
node={node}
key={`${node.value}-${i}`}
active={isActive(node, i, 'node')}
color={domainColor}
radius={radius}
angle={angle}
disabled={disabled}
onMouseOver={(event: MouseEvent) =>
onNodeMouseOverLocal(node, event)
}
onMouseOut={(event: MouseEvent) => onNodeMouseOutLocal(node, event)}
onClick={(event: MouseEvent) => onNodeClickLocal(node, event)}
/>
))}
</Fragment>
),
[nodes, disabled]
);
const renderTooltip = useCallback(() => {
const { formatter, placement, show } = tooltip;
return (
<Fragment>
{!disabled && show && (
<Tooltip
visible={!!active}
reference={tooltipReference}
placement={placement}
content={() =>
formatter(axis, nodes, linkTooltipData, nodeTooltipData) ||
(nodeTooltipData ? (
<HiveTooltip node={nodeTooltipData} nodes={nodes} axis={axis} />
) : null)
}
/>
)}
</Fragment>
);
}, [
tooltip,
disabled,
axis,
nodes,
active,
tooltipReference,
linkTooltipData,
nodeTooltipData
]);
const renderChart = useCallback(
({ height: containerHeight, width: containerWidth }) => {
const data = prepareData({
dimension: Math.min(containerHeight, containerWidth),
innerRadius,
colorScheme,
axis,
label
});
return (
<Fragment>
<svg
width={containerWidth}
height={containerHeight}
className={classNames(className)}
>
<g
transform={`translate(${containerWidth / 2}, ${
containerHeight / 2 + innerRadius
})`}
>
{renderAxis(data)}
{renderLinks(data)}
{renderNodes(data)}
</g>
</svg>
{renderTooltip()}
</Fragment>
);
},
[innerRadius, axis, colorScheme, label, className]
);
return (
<ChartContainer height={height} width={width}>
{renderChart}
</ChartContainer>
);
}; | the_stack |
import type { MarkRequired } from 'ts-essentials';
import type { AnyDevice, SendOptions } from '../client';
import {
extractResponse,
hasErrCode,
HasErrCode,
isDefinedAndNotNull,
isObjectLike,
} from '../utils';
type ScheduleDateStart = {
smin: number;
stime_opt: number;
};
type ScheduleDateEnd = {
emin: number;
etime_opt: number;
};
type WDay = [boolean, boolean, boolean, boolean, boolean, boolean, boolean];
export type ScheduleRule = {
name?: string;
enable?: number;
day?: number;
month?: number;
year?: number;
wday?: WDay;
repeat?: boolean;
etime_opt: -1;
emin: -1 | 0;
} & (ScheduleDateStart | Record<string, unknown>);
export type ScheduleRuleWithId = ScheduleRule & { id: string };
type ScheduleRules = { rule_list: ScheduleRuleWithId[] };
type ScheduleNextAction = Record<string, unknown>;
export type ScheduleRuleResponse = ScheduleRule & HasErrCode;
export type ScheduleRulesResponse = ScheduleRules & HasErrCode;
export type ScheduleNextActionResponse = ScheduleNextAction & HasErrCode;
function isScheduleNextAction(
candidate: unknown
): candidate is ScheduleNextAction {
return isObjectLike(candidate);
}
export function isScheduleNextActionResponse(
candidate: unknown
): candidate is ScheduleNextActionResponse {
return isScheduleNextAction(candidate) && hasErrCode(candidate);
}
export type HasRuleListWithRuleIds = { rule_list: { id: string }[] };
export function hasRuleListWithRuleIds(
candidate: unknown
): candidate is { rule_list: { id: string }[] } {
return (
isObjectLike(candidate) &&
'rule_list' in candidate &&
isObjectLike(candidate.rule_list) &&
Array.isArray(candidate.rule_list) &&
candidate.rule_list.every(
(rule) => 'id' in rule && typeof rule.id === 'string'
)
);
}
function isScheduleRules(candidate: unknown): candidate is ScheduleRules {
return (
isObjectLike(candidate) &&
'rule_list' in candidate &&
isObjectLike(candidate.rule_list) &&
Array.isArray(candidate.rule_list) &&
candidate.rule_list.every(
(rule) => 'id' in rule && typeof rule.id === 'string'
)
);
}
export function isScheduleRulesResponse(
candidate: unknown
): candidate is ScheduleNextActionResponse {
return isScheduleRules(candidate) && hasErrCode(candidate);
}
export type ScheduleRuleInputTime = Date | number | 'sunrise' | 'sunset';
function createScheduleDate(
date: ScheduleRuleInputTime,
startOrEnd: 'start' | 'end'
): ScheduleDateStart | ScheduleDateEnd {
let min = 0;
// eslint-disable-next-line @typescript-eslint/naming-convention
let time_opt = 0;
if (date instanceof Date) {
min = date.getHours() * 60 + date.getMinutes();
} else if (typeof date === 'number') {
min = date;
} else if (date === 'sunrise') {
min = 0;
time_opt = 1;
} else if (date === 'sunset') {
min = 0;
time_opt = 2;
}
if (startOrEnd === 'end') {
return { emin: min, etime_opt: time_opt };
}
return { smin: min, stime_opt: time_opt };
}
function createScheduleDateStart(
date: ScheduleRuleInputTime
): ScheduleDateStart {
return createScheduleDate(date, 'start') as ScheduleDateStart;
}
function createScheduleDateEnd(date: ScheduleRuleInputTime): ScheduleDateEnd {
return createScheduleDate(date, 'end') as ScheduleDateEnd;
}
function createWday(daysOfWeek: number[]): WDay {
const wday: WDay = [false, false, false, false, false, false, false];
daysOfWeek.forEach((dw) => {
wday[dw] = true;
});
return wday;
}
export function createScheduleRule({
start,
daysOfWeek,
}: {
start: ScheduleRuleInputTime;
daysOfWeek?: number[];
}): ScheduleDateStart & {
wday: WDay;
repeat: boolean;
day?: number;
month?: number;
year?: number;
} {
const sched: ScheduleDateStart &
Partial<{
wday: WDay;
repeat: boolean;
day?: number;
month?: number;
year?: number;
}> = createScheduleDateStart(start);
if (isDefinedAndNotNull(daysOfWeek) && daysOfWeek.length > 0) {
sched.wday = createWday(daysOfWeek);
sched.repeat = true;
} else {
const date = start instanceof Date ? start : new Date();
sched.day = date.getDate();
sched.month = date.getMonth() + 1;
sched.year = date.getFullYear();
sched.wday = [false, false, false, false, false, false, false];
sched.wday[date.getDay()] = true;
sched.repeat = false;
}
return sched as MarkRequired<typeof sched, 'wday' | 'repeat'>;
}
export function createRule({
start,
end,
daysOfWeek,
}: {
start: ScheduleRuleInputTime;
end?: ScheduleRuleInputTime;
daysOfWeek?: number[];
}): MarkRequired<Partial<ScheduleRule>, 'wday' | 'repeat'> & ScheduleDateStart {
const sched: Partial<ScheduleRule> &
ScheduleDateStart = createScheduleDateStart(start);
if (isDefinedAndNotNull(end)) {
Object.assign(sched, createScheduleDateEnd(end));
}
if (isDefinedAndNotNull(daysOfWeek) && daysOfWeek.length > 0) {
sched.wday = createWday(daysOfWeek);
sched.repeat = true;
} else {
const date = start instanceof Date ? start : new Date();
sched.day = date.getDate();
sched.month = date.getMonth() + 1;
sched.year = date.getFullYear();
sched.wday = [false, false, false, false, false, false, false];
sched.wday[date.getDay()] = true;
sched.repeat = false;
}
return sched as MarkRequired<typeof sched, 'wday' | 'repeat'>;
}
export default abstract class Schedule {
nextAction: ScheduleNextActionResponse | undefined;
constructor(
readonly device: AnyDevice,
readonly apiModuleName: string,
readonly childId?: string
) {}
/**
* Gets Next Schedule Rule Action.
*
* Requests `schedule.get_next_action`. Supports childId.
* @throws {@link ResponseError}
*/
async getNextAction(
sendOptions?: SendOptions
): Promise<ScheduleNextActionResponse> {
this.nextAction = extractResponse(
await this.device.sendCommand(
{
[this.apiModuleName]: { get_next_action: {} },
},
this.childId,
sendOptions
),
'',
isScheduleNextActionResponse
) as ScheduleNextActionResponse;
return this.nextAction;
}
/**
* Gets Schedule Rules.
*
* Requests `schedule.get_rules`. Supports childId.
* @throws {@link ResponseError}
*/
async getRules(sendOptions?: SendOptions): Promise<ScheduleRulesResponse> {
return extractResponse(
await this.device.sendCommand(
{
[this.apiModuleName]: { get_rules: {} },
},
this.childId,
sendOptions
),
'',
isScheduleRulesResponse
) as ScheduleRulesResponse;
}
/**
* Gets Schedule Rule.
*
* Requests `schedule.get_rules` and return rule matching Id. Supports childId.
* @throws {@link ResponseError}
* @throws {@link Error}
*/
async getRule(
id: string,
sendOptions?: SendOptions
): Promise<ScheduleRuleResponse> {
const rules = await this.getRules(sendOptions);
const rule: ScheduleRule | undefined = rules.rule_list.find(
(r) => r.id === id
);
if (rule === undefined) throw new Error(`Rule id not found: ${id}`);
return { ...rule, err_code: rules.err_code };
}
/**
* Adds Schedule rule.
*
* Sends `schedule.add_rule` command and returns rule id. Supports childId.
* @returns parsed JSON response
* @throws {@link ResponseError}
*/
async addRule(
// eslint-disable-next-line @typescript-eslint/ban-types
rule: object,
sendOptions?: SendOptions
): Promise<{ id: string }> {
return extractResponse(
await this.device.sendCommand(
{
[this.apiModuleName]: { add_rule: rule },
},
this.childId,
sendOptions
),
'',
(candidate) => {
return isObjectLike(candidate) && typeof candidate.id === 'string';
}
) as { id: string };
}
/**
* Edits Schedule Rule.
*
* Sends `schedule.edit_rule` command. Supports childId.
* @returns parsed JSON response
* @throws {@link ResponseError}
*/
async editRule(
// eslint-disable-next-line @typescript-eslint/ban-types
rule: object,
sendOptions?: SendOptions
): Promise<unknown> {
return this.device.sendCommand(
{
[this.apiModuleName]: { edit_rule: rule },
},
this.childId,
sendOptions
);
}
/**
* Deletes All Schedule Rules.
*
* Sends `schedule.delete_all_rules` command. Supports childId.
* @returns parsed JSON response
* @throws {@link ResponseError}
*/
async deleteAllRules(sendOptions?: SendOptions): Promise<unknown> {
return this.device.sendCommand(
{
[this.apiModuleName]: { delete_all_rules: {} },
},
this.childId,
sendOptions
);
}
/**
* Deletes Schedule Rule.
*
* Sends `schedule.delete_rule` command. Supports childId.
* @returns parsed JSON response
* @throws {@link ResponseError}
*/
async deleteRule(id: string, sendOptions?: SendOptions): Promise<unknown> {
return this.device.sendCommand(
{
[this.apiModuleName]: { delete_rule: { id } },
},
this.childId,
sendOptions
);
}
/**
* Enables or Disables Schedule Rules.
*
* Sends `schedule.set_overall_enable` command. Supports childId.
* @returns parsed JSON response
* @throws {@link ResponseError}
*/
async setOverallEnable(
enable: boolean,
sendOptions?: SendOptions
): Promise<unknown> {
return this.device.sendCommand(
{
[this.apiModuleName]: {
set_overall_enable: { enable: enable ? 1 : 0 },
},
},
this.childId,
sendOptions
);
}
/**
* Get Daily Usage Statistics.
*
* Sends `schedule.get_daystat` command. Supports childId.
* @returns parsed JSON response
* @throws {@link ResponseError}
*/
async getDayStats(
year: number,
month: number,
sendOptions?: SendOptions
): Promise<unknown> {
return this.device.sendCommand(
{
[this.apiModuleName]: { get_daystat: { year, month } },
},
this.childId,
sendOptions
);
}
/**
* Get Monthly Usage Statistics.
*
* Sends `schedule.get_monthstat` command. Supports childId.
* @returns parsed JSON response
* @throws {@link ResponseError}
*/
async getMonthStats(
year: number,
sendOptions?: SendOptions
): Promise<unknown> {
return this.device.sendCommand(
{
[this.apiModuleName]: { get_monthstat: { year } },
},
this.childId,
sendOptions
);
}
/**
* Erase Usage Statistics.
*
* Sends `schedule.erase_runtime_stat` command. Supports childId.
* @returns parsed JSON response
* @throws {@link ResponseError}
*/
async eraseStats(sendOptions?: SendOptions): Promise<unknown> {
return this.device.sendCommand(
{
[this.apiModuleName]: { erase_runtime_stat: {} },
},
this.childId,
sendOptions
);
}
} | the_stack |
import {assert} from '@esm-bundle/chai';
import {render as litRender} from 'lit-html';
import {prepareTemplate, render} from '../stampino.js';
suite('stampino', () => {
let container: HTMLDivElement;
setup(() => {
container = document.createElement('div');
});
test('No bindings', () => {
const template = document.createElement('template');
template.innerHTML = `<h1>Hello</h1>`;
render(template, container, {});
assert.equal(stripExpressionMarkers(container.innerHTML), `<h1>Hello</h1>`);
});
test('Text binding', () => {
const template = document.createElement('template');
template.innerHTML = `Hello {{ name }}`;
render(template, container, {name: 'World'});
assert.equal(stripExpressionMarkers(container.innerHTML), `Hello World`);
});
test('Text binding in element', () => {
const template = document.createElement('template');
template.innerHTML = `<h1>Hello {{ name.toUpperCase() }}!</h1>`;
render(template, container, {name: 'World'});
assert.equal(
stripExpressionMarkers(container.innerHTML),
`<h1>Hello WORLD!</h1>`
);
});
test('Text binding after element', () => {
const template = document.createElement('template');
template.innerHTML = `<p>A</p>{{ x }}`;
render(template, container, {x: 'B'});
assert.equal(stripExpressionMarkers(container.innerHTML), `<p>A</p>B`);
});
test('Text binding after element x 2', () => {
const template = document.createElement('template');
template.innerHTML = `<p>A</p>{{ x }}{{ y }}`;
render(template, container, {x: 'B', y: 'C'});
assert.equal(stripExpressionMarkers(container.innerHTML), `<p>A</p>BC`);
});
test('Text bindings before and after element', () => {
const template = document.createElement('template');
template.innerHTML = `<div>{{ a }}<p>{{ b }}</p>{{ c }}</div>`;
render(template, container, {a: 'A', b: 'B', c: 'C'});
assert.equal(
stripExpressionMarkers(container.innerHTML),
`<div>A<p>B</p>C</div>`
);
});
test('Attribute binding', () => {
const template = document.createElement('template');
template.innerHTML = `<p class="{{ x }}"></p>`;
render(template, container, {x: 'foo'});
assert.equal(
stripExpressionMarkers(container.innerHTML),
`<p class="foo"></p>`
);
});
test('Multiple attribute bindings', () => {
const template = document.createElement('template');
template.innerHTML = `<p class="A {{ b }} C {{ d }}"></p>`;
render(template, container, {b: 'B', d: 'D'});
assert.equal(
stripExpressionMarkers(container.innerHTML),
`<p class="A B C D"></p>`
);
});
test('Property binding', () => {
const template = document.createElement('template');
template.innerHTML = `<p .class-name="{{ x }}">`;
render(template, container, {x: 'foo'});
assert.equal(
stripExpressionMarkers(container.innerHTML),
`<p class="foo"></p>`
);
});
test('Boolean attribute binding', () => {
const template = document.createElement('template');
template.innerHTML = `<p ?disabled="{{ x }}">`;
render(template, container, {x: false});
assert.equal(stripExpressionMarkers(container.innerHTML), `<p></p>`);
render(template, container, {x: true});
assert.equal(
stripExpressionMarkers(container.innerHTML),
`<p disabled=""></p>`
);
});
test('Event binding', () => {
const template = document.createElement('template');
template.innerHTML = `<p @click="{{ handleClick }}">`;
let lastEvent: Event | undefined = undefined;
render(template, container, {
handleClick: (e: Event) => {
lastEvent = e;
},
});
const p = container.querySelector('p')!;
p.click();
assert.equal(stripExpressionMarkers(container.innerHTML), `<p></p>`);
assert.instanceOf(lastEvent, Event);
});
test('Event binding w/ dashed names', () => {
const template = document.createElement('template');
template.innerHTML = `<p @foo--bar="{{ handleClick }}">`;
let lastEvent: Event | undefined = undefined;
render(template, container, {
handleClick: (e: Event) => {
lastEvent = e;
},
});
const p = container.querySelector('p')!;
p.dispatchEvent(new Event('foo-bar'));
assert.equal(stripExpressionMarkers(container.innerHTML), `<p></p>`);
assert.instanceOf(lastEvent, Event);
});
test('Event binding w/ camelCase names', () => {
const template = document.createElement('template');
template.innerHTML = `<p @foo-bar="{{ handleClick }}">`;
let lastEvent: Event | undefined = undefined;
render(template, container, {
handleClick: (e: Event) => {
lastEvent = e;
},
});
const p = container.querySelector('p')!;
p.dispatchEvent(new Event('fooBar'));
assert.equal(stripExpressionMarkers(container.innerHTML), `<p></p>`);
assert.instanceOf(lastEvent, Event);
});
test('if template, true', () => {
const template = document.createElement('template');
template.innerHTML = `<template type="if" if="{{true}}">{{s}}</template>`;
render(template, container, {s: 'Hello'});
assert.equal(stripExpressionMarkers(container.innerHTML), `Hello`);
});
test('if template, false', () => {
const template = document.createElement('template');
template.innerHTML = `<template type="if" if="{{c}}">{{s}}</template>`;
render(template, container, {c: false, s: 'Hello'});
assert.equal(stripExpressionMarkers(container.innerHTML), ``);
});
test('repeat template', () => {
const template = document.createElement('template');
template.innerHTML = `<template type="repeat" repeat="{{ items }}"><p>{{ item }}{{ x }}</p></template>`;
render(template, container, {items: [4, 5, 6], x: 'X'});
assert.equal(
stripExpressionMarkers(container.innerHTML),
`<p>4X</p><p>5X</p><p>6X</p>`
);
});
test('nullable model access', function () {
const template = document.createElement('template');
template.innerHTML = `{{nullable.missing.property || 'none'}}`;
render(template, container, {nullable: null});
assert.equal(
stripExpressionMarkers(container.innerHTML),
`none`,
'with null model property'
);
render(template, container, {nullable: {missing: {property: 'something'}}});
assert.equal(
stripExpressionMarkers(container.innerHTML),
`something`,
'with nonnull model property'
);
});
test('named blocks with fallback', () => {
const template = document.createElement('template');
template.innerHTML = `<p>A</p><template name="B">{{ b }}</template><template name="C">C</template>`;
const templateFn = prepareTemplate(template);
litRender(templateFn({b: 'B'}), container);
assert.equal(stripExpressionMarkers(container.innerHTML), `<p>A</p>BC`);
});
// TODO: Need to figure out where passed-in renderers fit in the scope. Can
// they override block lookup, or do all declared blocks take precedence?
// If declared blocks take precedence and self-render, then do we need to
// make a separate <template call="name"> construct.
test.skip('named blocks with provided renderer', () => {
const bTemplate = document.createElement('template');
bTemplate.innerHTML = `<p>{{ b }}</p>`;
const bTemplateFn = prepareTemplate(bTemplate);
const template = document.createElement('template');
template.innerHTML = `<p>A</p><template name="B">{{ b }}</template><template name="C">C</template>`;
const templateFn = prepareTemplate(template, undefined, {
B: (model) => {
return bTemplateFn(model);
},
});
litRender(templateFn({b: 'B'}), container);
assert.equal(
stripExpressionMarkers(container.innerHTML),
`<p>A</p><p>B</p>C`
);
});
test('implicit super template call', () => {
const superTemplate = document.createElement('template');
superTemplate.innerHTML = `<p>A</p><template name="B">B</template><template name="C">C</template>`;
const subTemplate = document.createElement('template');
subTemplate.innerHTML = `<template name="C">Z</template>`;
const subTemplateFn = prepareTemplate(
subTemplate,
undefined,
undefined,
superTemplate
);
litRender(subTemplateFn({}), container);
assert.equal(stripExpressionMarkers(container.innerHTML), `<p>A</p>BZ`);
});
test('explicit super template call', () => {
const superTemplate = document.createElement('template');
superTemplate.innerHTML = `<p>A</p><template name="B">B</template><template name="C">C</template>`;
const subTemplate = document.createElement('template');
subTemplate.innerHTML = `1<template name="super"><template name="C">Z</template></template>2`;
const subTemplateFn = prepareTemplate(
subTemplate,
undefined,
undefined,
superTemplate
);
litRender(subTemplateFn({}), container);
assert.equal(stripExpressionMarkers(container.innerHTML), `1<p>A</p>BZ2`);
});
test('block inside if', () => {
const superTemplate = document.createElement('template');
superTemplate.innerHTML = `<template type="if" if="{{ true }}"><template name="A"></template></template>`;
const subTemplate = document.createElement('template');
subTemplate.innerHTML = `<template name="A">{{ a }}</template>`;
const subTemplateFn = prepareTemplate(
subTemplate,
undefined,
undefined,
superTemplate
);
litRender(subTemplateFn({a: 'A'}), container);
assert.equal(stripExpressionMarkers(container.innerHTML), `A`);
});
test('nested blocks, override inner', () => {
const superTemplate = document.createElement('template');
superTemplate.innerHTML = `<template name="A">A<template name="B">B</template>C</template>`;
const subTemplate = document.createElement('template');
subTemplate.innerHTML = `<template name="B">{{ b }}</template>`;
const subTemplateFn = prepareTemplate(
subTemplate,
undefined,
undefined,
superTemplate
);
litRender(subTemplateFn({b: 'Z'}), container);
assert.equal(stripExpressionMarkers(container.innerHTML), `AZC`);
});
// TODO: We need a way to render the super _block_ not just the super
// template. See how Jinja does this:
// https://jinja.palletsprojects.com/en/2.11.x/templates/#super-blocks
test('nested blocks, override outer', () => {
const superTemplate = document.createElement('template');
superTemplate.innerHTML = `<template name="A">A<template name="B">B</template>C</template>`;
const subTemplate = document.createElement('template');
subTemplate.innerHTML = `<template name="A">{{ a }}</template>`;
const subTemplateFn = prepareTemplate(
subTemplate,
undefined,
undefined,
superTemplate
);
litRender(subTemplateFn({a: 'Z'}), container);
assert.equal(stripExpressionMarkers(container.innerHTML), `Z`);
});
});
const stripExpressionMarkers = (html: string) =>
html.replace(/<!--\?lit\$[0-9]+\$-->|<!--\??-->|lit\$[0-9]+\$/g, ''); | the_stack |
import {
AfterViewInit, ChangeDetectionStrategy, Component, EventEmitter, Inject, Input, OnChanges, OnDestroy, OnInit,
Output, SimpleChanges
} from '@angular/core';
import Swal, { SweetAlertOptions, SweetAlertResult, SweetAlertUpdatableParameters } from 'sweetalert2';
import { dismissOnDestroyToken, fireOnInitToken } from './di';
import * as events from './swal-events';
import { SweetAlert2LoaderService } from './sweetalert2-loader.service';
/**
* <swal> component. See the README.md for usage.
*
* It contains a bunch of @Inputs that have a perfect 1:1 mapping with SweetAlert2 options.
* Their types are directly coming from SweetAlert2 types defintitions, meaning that ngx-sweetalert2 is tightly coupled
* to SweetAlert2, but also is type-safe even if both libraries do not evolve in sync.
*
* (?) If you want to use an object that declares the SweetAlert2 options all at once rather than many @Inputs,
* take a look at [swalOptions], that lets you pass a full {@link SweetAlertOptions} object.
*
* (?) If you are reading the TypeScript source of this component, you may think that it's a lot of code.
* Be sure that a lot of this code is types and Angular boilerplate. Compiled and minified code is much smaller.
* If you are really concerned about performance and/or don't care about the API and its convenient integration
* with Angular (notably change detection and transclusion), you may totally use SweetAlert2 natively as well ;)
*
* /!\ Some SweetAlert options aren't @Inputs but @Outputs: `willOpen`, `didOpen`, `didRender`, `willClose`, `didClose`
* and `didDestroy`.
* However, `preConfirm`, `preDeny` and `inputValidator` are still @Inputs because they are not event handlers,
* there can't be multiple listeners on them, and we need the values they can/must return.
*/
@Component({
selector: 'swal',
template: '',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class SwalComponent implements OnInit, AfterViewInit, OnChanges, OnDestroy {
@Input() public title: SweetAlertOptions['title'];
@Input() public titleText: SweetAlertOptions['titleText'];
@Input() public text: SweetAlertOptions['text'];
@Input() public html: SweetAlertOptions['html'];
@Input() public footer: SweetAlertOptions['footer'];
@Input() public icon: SweetAlertOptions['icon'];
@Input() public iconColor: SweetAlertOptions['iconColor'];
@Input() public iconHtml: SweetAlertOptions['iconHtml'];
@Input() public backdrop: SweetAlertOptions['backdrop'];
@Input() public toast: SweetAlertOptions['toast'];
@Input() public target: SweetAlertOptions['target'];
@Input() public input: SweetAlertOptions['input'];
@Input() public width: SweetAlertOptions['width'];
@Input() public padding: SweetAlertOptions['padding'];
@Input() public background: SweetAlertOptions['background'];
@Input() public position: SweetAlertOptions['position'];
@Input() public grow: SweetAlertOptions['grow'];
@Input() public showClass: SweetAlertOptions['showClass'];
@Input() public hideClass: SweetAlertOptions['hideClass'];
@Input() public customClass: SweetAlertOptions['customClass'];
@Input() public timer: SweetAlertOptions['timer'];
@Input() public timerProgressBar: SweetAlertOptions['timerProgressBar'];
@Input() public heightAuto: SweetAlertOptions['heightAuto'];
@Input() public allowOutsideClick: SweetAlertOptions['allowOutsideClick'];
@Input() public allowEscapeKey: SweetAlertOptions['allowEscapeKey'];
@Input() public allowEnterKey: SweetAlertOptions['allowEnterKey'];
@Input() public stopKeydownPropagation: SweetAlertOptions['stopKeydownPropagation'];
@Input() public keydownListenerCapture: SweetAlertOptions['keydownListenerCapture'];
@Input() public showConfirmButton: SweetAlertOptions['showConfirmButton'];
@Input() public showDenyButton: SweetAlertOptions['showDenyButton'];
@Input() public showCancelButton: SweetAlertOptions['showCancelButton'];
@Input() public confirmButtonText: SweetAlertOptions['confirmButtonText'];
@Input() public denyButtonText: SweetAlertOptions['denyButtonText'];
@Input() public cancelButtonText: SweetAlertOptions['cancelButtonText'];
@Input() public confirmButtonColor: SweetAlertOptions['confirmButtonColor'];
@Input() public denyButtonColor: SweetAlertOptions['denyButtonColor'];
@Input() public cancelButtonColor: SweetAlertOptions['cancelButtonColor'];
@Input() public confirmButtonAriaLabel: SweetAlertOptions['confirmButtonAriaLabel'];
@Input() public denyButtonAriaLabel: SweetAlertOptions['denyButtonAriaLabel'];
@Input() public cancelButtonAriaLabel: SweetAlertOptions['cancelButtonAriaLabel'];
@Input() public buttonsStyling: SweetAlertOptions['buttonsStyling'];
@Input() public reverseButtons: SweetAlertOptions['reverseButtons'];
@Input() public focusConfirm: SweetAlertOptions['focusConfirm'];
@Input() public focusDeny: SweetAlertOptions['focusDeny'];
@Input() public focusCancel: SweetAlertOptions['focusCancel'];
@Input() public showCloseButton: SweetAlertOptions['showCloseButton'];
@Input() public closeButtonHtml: SweetAlertOptions['closeButtonHtml'];
@Input() public closeButtonAriaLabel: SweetAlertOptions['closeButtonAriaLabel'];
@Input() public loaderHtml: SweetAlertOptions['loaderHtml'];
@Input() public showLoaderOnConfirm: SweetAlertOptions['showLoaderOnConfirm'];
@Input() public preConfirm: SweetAlertOptions['preConfirm'];
@Input() public preDeny: SweetAlertOptions['preDeny'];
@Input() public imageUrl: SweetAlertOptions['imageUrl'];
@Input() public imageWidth: SweetAlertOptions['imageWidth'];
@Input() public imageHeight: SweetAlertOptions['imageHeight'];
@Input() public imageAlt: SweetAlertOptions['imageAlt'];
@Input() public inputLabel: SweetAlertOptions['inputLabel'];
@Input() public inputPlaceholder: SweetAlertOptions['inputPlaceholder'];
@Input() public inputValue: SweetAlertOptions['inputValue'];
@Input() public inputOptions: SweetAlertOptions['inputOptions'];
@Input() public inputAutoTrim: SweetAlertOptions['inputAutoTrim'];
@Input() public inputAttributes: SweetAlertOptions['inputAttributes'];
@Input() public inputValidator: SweetAlertOptions['inputValidator'];
@Input() public returnInputValueOnDeny: SweetAlertOptions['returnInputValueOnDeny'];
@Input() public validationMessage: SweetAlertOptions['validationMessage'];
@Input() public progressSteps: SweetAlertOptions['progressSteps'];
@Input() public currentProgressStep: SweetAlertOptions['currentProgressStep'];
@Input() public progressStepsDistance: SweetAlertOptions['progressStepsDistance'];
@Input() public scrollbarPadding: SweetAlertOptions['scrollbarPadding'];
/**
* An object of SweetAlert2 native options, useful if:
* - you don't want to use the @Inputs for practical/philosophical reasons ;
* - there are missing @Inputs because ngx-sweetalert2 isn't up-to-date with SweetAlert2's latest changes.
*
* /!\ Please note that setting this property does NOT erase what has been set before unless you specify the
* previous properties you want to erase again.
* Ie. setting { title: 'Title' } and then { text: 'Text' } will give { title: 'Title', text: 'Text' }.
*
* /!\ Be aware that the options defined in this object will override the @Inputs of the same name.
*/
@Input()
public set swalOptions(options: SweetAlertOptions) {
//=> Update properties
Object.assign(this, options);
//=> Mark changed properties as touched
const touchedKeys = Object.keys(options) as Array<keyof SweetAlertOptions>;
touchedKeys.forEach(this.markTouched);
}
/**
* Computes the options object that will get passed to SweetAlert2.
* Only the properties that have been set at least once on this component will be returned.
* Mostly for internal usage.
*/
public get swalOptions(): SweetAlertOptions {
//=> We will compute the options object based on the option keys that are known to have changed.
// That avoids passing a gigantic object to SweetAlert2, making debugging easier and potentially
// avoiding side effects.
return [...this.touchedProps].reduce<SweetAlertOptions>(
(obj, key) => ({ ...obj, [key]: this[key as keyof this] }),
{});
}
/**
* Whether to fire the modal as soon as the <swal> component is created and initialized in the view.
* When left undefined (default), the value will be inherited from the module configuration, which is `false`.
*
* Example:
* <swal *ngIf="error" [title]="error.title" [text]="error.text" icon="error" [swalFireOnInit]="true"></swal>
*/
@Input()
public swalFireOnInit?: boolean;
/**
* Whether to dismiss the modal when the <swal> component is destroyed by Angular (for any reason) or not.
* When left undefined (default), the value will be inherited from the module configuration, which is `true`.
*/
@Input()
public swalDismissOnDestroy?: boolean;
@Input()
public set swalVisible(visible: boolean) {
visible ? this.fire() : this.close();
}
public get swalVisible(): boolean {
return this.isCurrentlyShown;
}
/**
* Modal lifecycle hook. Synchronously runs before the modal is shown on screen.
*/
@Output()
public readonly willOpen = new EventEmitter<events.WillOpenEvent>();
/**
* Modal lifecycle hook. Synchronously runs before the modal is shown on screen.
*/
@Output()
public readonly didOpen = new EventEmitter<events.DidOpenEvent>();
/**
* Modal lifecycle hook. Synchronously runs after the popup DOM has been updated (ie. just before the modal is
* repainted on the screen).
* Typically, this will happen after `Swal.fire()` or `Swal.update()`.
* If you want to perform changes in the popup's DOM, that survive `Swal.update()`, prefer {@link didRender} over
* {@link willOpen}.
*/
@Output()
public readonly didRender = new EventEmitter<events.DidRenderEvent>();
/**
* Modal lifecycle hook. Synchronously runs when the popup closes by user interaction (and not due to another popup
* being fired).
*/
@Output()
public readonly willClose = new EventEmitter<events.WillCloseEvent>();
/**
* Modal lifecycle hook. Asynchronously runs after the popup has been disposed by user interaction (and not due to
* another popup being fired).
*/
@Output()
public readonly didClose = new EventEmitter<void>();
/**
* Modal lifecycle hook. Synchronously runs after popup has been destroyed either by user interaction or by another
* popup.
* If you have cleanup operations that you need to reliably execute each time a modal is closed, prefer
* {@link didDestroy} over {@link didClose}.
*/
@Output()
public readonly didDestroy = new EventEmitter<void>();
/**
* Emits when the user clicks "Confirm".
* The event value ($event) can be either:
* - by default, just `true`,
* - when using {@link input}, the input value,
* - when using {@link preConfirm}, the return value of this function.
*
* Example:
* <swal (confirm)="handleConfirm($event)"></swal>
*
* public handleConfirm(email: string): void {
* // ... save user email
* }
*/
@Output()
public readonly confirm = new EventEmitter<any>();
/**
* Emits when the user clicks "Deny".
* This event bears no value.
* Use `(deny)` (along with {@link showDenyButton}) when you want a modal with three buttons (confirm, deny and
* cancel), and/or when you want to handle clear refusal in a separate way than simple dismissal.
*
* Example:
* <swal (deny)="handleDeny()"></swal>
*
* public handleDeny(): void {
* }
*/
@Output()
public readonly deny = new EventEmitter<void>();
/**
* Emits when the user clicks "Cancel", or dismisses the modal by any other allowed way.
* The event value ($event) is a string that explains how the modal was dismissed. It is `undefined` when
* the modal was programmatically closed (through {@link close} for example).
*
* Example:
* <swal (dismiss)="handleDismiss($event)"></swal>
*
* public handleDismiss(reason: DismissReason | undefined): void {
* // reason can be 'cancel', 'overlay', 'close', 'timer' or undefined.
* // ... do something
* }
*/
@Output()
public readonly dismiss = new EventEmitter<Swal.DismissReason | undefined>();
/**
* This Set retains the properties that have been changed from @Inputs, so we can know precisely
* what options we have to send to {@link Swal.fire}.
*/
private readonly touchedProps = new Set<keyof SweetAlertOptions>();
/**
* A function of signature `(propName: string): void` that adds a given property name to the list of
* touched properties, ie. {@link touchedProps}.
*/
private readonly markTouched = this.touchedProps.add.bind(this.touchedProps);
/**
* Is the SweetAlert2 modal represented by this component currently opened?
*/
private isCurrentlyShown = false;
public constructor(
private readonly sweetAlert2Loader: SweetAlert2LoaderService,
@Inject(fireOnInitToken) private readonly moduleLevelFireOnInit: boolean,
@Inject(dismissOnDestroyToken) private readonly moduleLevelDismissOnDestroy: boolean) {
}
/**
* Angular lifecycle hook.
* Asks the SweetAlert2 loader service to preload the SweetAlert2 library, so it begins to be loaded only if there
* is a <swal> component somewhere, and is probably fully loaded when the modal has to be displayed,
* causing no delay.
*/
public ngOnInit(): void {
//=> Preload SweetAlert2 library in case this component is activated.
this.sweetAlert2Loader.preloadSweetAlertLibrary();
}
/**
* Angular lifecycle hook.
* Fires the modal, if the component or module is configured to do so.
*/
public ngAfterViewInit(): void {
const fireOnInit = this.swalFireOnInit === undefined
? this.moduleLevelFireOnInit
: this.swalFireOnInit;
fireOnInit && this.fire();
}
/**
* Angular lifecycle hook.
* Updates the SweetAlert options, and if the modal is opened, asks SweetAlert to render it again.
*/
public ngOnChanges(changes: SimpleChanges): void {
//=> For each changed @Input that matches a SweetAlert2 option, mark as touched so we can
// send it with the next fire() or update() calls.
Object.keys(changes)
//=> If the filtering logic becomes more complex here, we can use Swal.isValidParameter
.filter((key): key is keyof SweetAlertOptions => !key.startsWith('swal'))
.forEach(this.markTouched);
//=> Eventually trigger re-render if the modal is open.
void this.update();
}
/**
* Angular lifecycle hook.
* Closes the SweetAlert when the component is destroyed.
*/
public ngOnDestroy(): void {
//=> Release the modal if the component is destroyed and if that behaviour is not disabled.
const dismissOnDestroy = this.swalDismissOnDestroy === undefined
? this.moduleLevelDismissOnDestroy
: this.swalDismissOnDestroy;
dismissOnDestroy && this.close();
}
/**
* Shows the SweetAlert.
*
* Returns the SweetAlert2 promise for convenience and use in code behind templates.
* Otherwise, (confirm)="myHandler($event)" and (dismiss)="myHandler($event)" can be used in templates.
*/
public async fire(): Promise<SweetAlertResult> {
const swal = await this.sweetAlert2Loader.swal;
const userOptions = this.swalOptions;
//=> Build the SweetAlert2 options
const options: SweetAlertOptions = {
//=> Merge with calculated options set for that specific swal
...userOptions,
//=> Handle modal lifecycle events
willOpen: composeHook(userOptions.willOpen, (modalElement) => {
this.willOpen.emit({ modalElement });
}),
didOpen: composeHook(userOptions.didOpen, (modalElement) => {
this.isCurrentlyShown = true;
this.didOpen.emit({ modalElement });
}),
didRender: composeHook(userOptions.didRender, (modalElement) => {
this.didRender.emit({ modalElement });
}),
willClose: composeHook(userOptions.willClose, (modalElement) => {
this.isCurrentlyShown = false;
this.willClose.emit({ modalElement });
}),
didClose: composeHook(userOptions.didClose, () => {
this.didClose.emit();
}),
didDestroy: composeHook(userOptions.didDestroy, () => {
this.didDestroy.emit();
})
};
//=> Show the Swal! And wait for confirmation or dimissal.
const result = await swal.fire(options);
//=> Emit on (confirm), (deny) or (dismiss)
switch (true) {
case result.isConfirmed: this.confirm.emit(result.value); break;
case result.isDenied: this.deny.emit(); break;
case result.isDismissed: this.dismiss.emit(result.dismiss); break;
}
return result;
function composeHook<T extends (...args: any[]) => void>(
userHook: T | undefined,
libHook: T): (...args: Parameters<T>) => void {
return (...args) => (libHook(...args), userHook?.(...args));
}
}
/**
* Closes the modal, if opened.
*
* @param result The value that the modal will resolve with, triggering either (confirm), (deny) or (dismiss).
* If the argument is not passed, it is (dismiss) that will emit an `undefined` reason.
* {@see Swal.close}.
*/
public async close(result?: SweetAlertResult): Promise<void> {
if (!this.isCurrentlyShown) return;
const swal = await this.sweetAlert2Loader.swal;
swal.close(result);
}
/**
* Updates SweetAlert2 options while the modal is opened, causing the modal to re-render.
* If the modal is not opened, the component options will simply be updated and that's it.
*
* /!\ Please note that not all SweetAlert2 options are updatable while the modal is opened.
*
* @param options
*/
public async update(options?: Pick<SweetAlertOptions, SweetAlertUpdatableParameters>): Promise<void> {
if (options) {
this.swalOptions = options;
}
if (!this.isCurrentlyShown) return;
const swal = await this.sweetAlert2Loader.swal;
const allOptions = this.swalOptions;
const updatableOptions = Object.keys(allOptions)
.filter(swal.isUpdatableParameter)
.reduce<Pick<SweetAlertOptions, SweetAlertUpdatableParameters>>(
(obj, key) => ({ ...obj, [key]: allOptions[key] }),
{});
swal.update(updatableOptions);
}
} | the_stack |
import * as path from "path";
import { Project as ITwin, ProjectsAccessClient, ProjectsSearchableProperty } from "@itwin/projects-client";
import { IModelHost, IModelJsFs, V1CheckpointManager } from "@itwin/core-backend";
import { AccessToken, ChangeSetStatus, GuidString, Logger, OpenMode, PerfLogger } from "@itwin/core-bentley";
import { BriefcaseIdValue, ChangesetFileProps, ChangesetProps } from "@itwin/core-common";
import { TestUserCredentials, TestUsers, TestUtility } from "@itwin/oidc-signin-tool";
/** the types of users available for tests */
export enum TestUserType {
Regular,
Manager,
Super,
SuperManager
}
/** Utility to work with test iModels in the iModelHub */
export class HubUtility {
public static logCategory = "HubUtility";
public static testITwinName = "iModelJsIntegrationTest";
public static testIModelNames = {
noVersions: "NoVersionsTest",
stadium: "Stadium Dataset 1",
readOnly: "ReadOnlyTest",
readWrite: "ReadWriteTest",
};
/** get an AuthorizedClientRequestContext for a [[TestUserType]].
* @note if the current test is using [[HubMock]], calling this method multiple times with the same type will return users from the same organization,
* but with different credentials. This can be useful for simulating more than one user of the same type on the same iTwin.
* However, if a real IModelHub is used, the credentials are supplied externally and will always return the same value (because otherwise they would not be valid.)
*/
public static async getAccessToken(user: TestUserType): Promise<AccessToken> {
let credentials: TestUserCredentials;
switch (user) {
case TestUserType.Regular:
credentials = TestUsers.regular;
break;
case TestUserType.Manager:
credentials = TestUsers.manager;
break;
case TestUserType.Super:
credentials = TestUsers.super;
break;
case TestUserType.SuperManager:
credentials = TestUsers.superManager;
break;
}
return TestUtility.getAccessToken(credentials);
}
public static iTwinId: GuidString | undefined;
/** Returns the iTwinId if an iTwin with the name exists. Otherwise, returns undefined. */
public static async getTestITwinId(accessToken: AccessToken): Promise<GuidString> {
if (undefined !== HubUtility.iTwinId)
return HubUtility.iTwinId;
return HubUtility.getITwinIdByName(accessToken, HubUtility.testITwinName);
}
private static imodelCache = new Map<string, GuidString>();
/** Returns the iModelId if the iModel exists. Otherwise, returns undefined. */
public static async getTestIModelId(accessToken: AccessToken, name: string): Promise<GuidString> {
if (HubUtility.imodelCache.has(name))
return HubUtility.imodelCache.get(name)!;
const iTwinId = await HubUtility.getTestITwinId(accessToken);
const iModelId = await IModelHost.hubAccess.queryIModelByName({ accessToken, iTwinId, iModelName: name });
if (undefined === iModelId)
throw new Error(`Cannot find iModel with ${name} in ${iTwinId}`);
HubUtility.imodelCache.set(name, iModelId);
return iModelId;
}
/**
* Queries the iTwin id by its name
* @param accessToken The client request context
* @param name Name of iTwin
* @throws If the iTwin is not found, or there is more than one iTwin with the supplied name
*/
public static async getITwinIdByName(accessToken: AccessToken, name: string): Promise<string> {
if (undefined !== HubUtility.iTwinId)
return HubUtility.iTwinId;
const iTwin = await getITwinAbstraction().getITwinByName(accessToken, name);
if (iTwin === undefined || !iTwin.id)
throw new Error(`ITwin ${name} was not found for the user.`);
return iTwin.id;
}
/** Download all change sets of the specified iModel */
private static async downloadChangesets(accessToken: AccessToken, changesetsPath: string, iModelId: GuidString): Promise<ChangesetProps[]> {
// Determine the range of changesets that remain to be downloaded
const changesets: ChangesetProps[] = await IModelHost.hubAccess.queryChangesets({ iModelId, accessToken }); // oldest to newest
if (changesets.length === 0)
return changesets;
const latestIndex = changesets.length;
let earliestIndex = 0; // Earliest index that doesn't exist
while (earliestIndex <= latestIndex) {
const pathname = path.join(changesetsPath, changesets[earliestIndex].id);
if (!IModelJsFs.existsSync(pathname))
break;
++earliestIndex;
}
if (earliestIndex > latestIndex) // All change sets have already been downloaded
return changesets;
const earliestChangesetIndex = earliestIndex > 0 ? earliestIndex - 1 : 0; // Query results exclude earliest specified changeset
const latestChangesetIndex = latestIndex; // Query results include latest specified change set
const perfLogger = new PerfLogger("HubUtility.downloadChangesets -> Download Changesets");
await IModelHost.hubAccess.downloadChangesets({ accessToken, iModelId, range: { first: earliestChangesetIndex, end: latestChangesetIndex }, targetDir: changesetsPath });
perfLogger.dispose();
return changesets;
}
/** Download an iModel's seed file and changesets from the Hub.
* A standard hierarchy of folders is created below the supplied downloadDir
*/
public static async downloadIModelById(accessToken: AccessToken, iTwinId: string, iModelId: GuidString, downloadDir: string, reDownload: boolean): Promise<void> {
// Recreate the download folder if necessary
if (reDownload) {
if (IModelJsFs.existsSync(downloadDir))
IModelJsFs.purgeDirSync(downloadDir);
IModelJsFs.recursiveMkDirSync(downloadDir);
}
// Download the seed file
const seedPathname = path.join(downloadDir, "seed", iModelId.concat(".bim"));
if (!IModelJsFs.existsSync(seedPathname)) {
const perfLogger = new PerfLogger("HubUtility.downloadIModelById -> Download Seed File");
await V1CheckpointManager.downloadCheckpoint({
localFile: seedPathname,
checkpoint: {
accessToken,
iTwinId,
iModelId,
changeset: {
id: "0",
index: 0,
},
},
});
perfLogger.dispose();
}
// Download the change sets
const changesetDir = path.join(downloadDir, "changesets");
const changesets = await HubUtility.downloadChangesets(accessToken, changesetDir, iModelId);
const changesetsJsonStr = JSON.stringify(changesets, undefined, 4);
const changesetsJsonPathname = path.join(downloadDir, "changesets.json");
IModelJsFs.writeFileSync(changesetsJsonPathname, changesetsJsonStr);
}
/** Download an IModel's seed files and change sets from the Hub.
* A standard hierarchy of folders is created below the supplied downloadDir
*/
public static async downloadIModelByName(accessToken: AccessToken, iTwinName: string, iModelName: string, downloadDir: string, reDownload: boolean): Promise<void> {
const iTwinId = await HubUtility.getITwinIdByName(accessToken, iTwinName);
const iModelId = await IModelHost.hubAccess.queryIModelByName({ accessToken, iTwinId, iModelName });
if (!iModelId)
throw new Error(`IModel ${iModelName} not found`);
await HubUtility.downloadIModelById(accessToken, iTwinId, iModelId, downloadDir, reDownload);
}
/** Delete an IModel from the hub */
public static async deleteIModel(accessToken: AccessToken, iTwinName: string, iModelName: string): Promise<void> {
const iTwinId = await HubUtility.getITwinIdByName(accessToken, iTwinName);
const iModelId = await IModelHost.hubAccess.queryIModelByName({ accessToken, iTwinId, iModelName });
if (!iModelId)
return;
await IModelHost.hubAccess.deleteIModel({ accessToken, iTwinId, iModelId });
}
/** Get the pathname of the briefcase in the supplied directory - assumes a standard layout of the supplied directory */
public static getBriefcasePathname(iModelDir: string): string {
const seedPathname = HubUtility.getSeedPathname(iModelDir);
return path.join(iModelDir, path.basename(seedPathname));
}
/** Apply change set with Merge operation on an iModel on disk - the supplied directory contains a sub folder
* with the seed files, change sets, etc. in a standard format.
* Returns time taken for each changeset. Returns on first apply changeset error.
*/
public static getApplyChangeSetTime(iModelDir: string, startCS: number = 0, endCS: number = 0): any[] {
const briefcasePathname = HubUtility.getBriefcasePathname(iModelDir);
Logger.logInfo(HubUtility.logCategory, "Making a local copy of the seed");
HubUtility.copyIModelFromSeed(briefcasePathname, iModelDir, true /* =overwrite */);
const nativeDb = new IModelHost.platform.DgnDb();
nativeDb.openIModel(briefcasePathname, OpenMode.ReadWrite);
const changesets = HubUtility.readChangesets(iModelDir);
const endNum: number = endCS ? endCS : changesets.length;
const filteredCS = changesets.filter((obj) => obj.index >= startCS && obj.index <= endNum);
Logger.logInfo(HubUtility.logCategory, "Merging all available change sets");
const perfLogger = new PerfLogger(`Applying change sets }`);
const results = [];
// Apply change sets one by one to debug any issues
for (const changeSet of filteredCS) {
const startTime = new Date().getTime();
let csResult = ChangeSetStatus.Success;
try {
nativeDb.applyChangeset(changeSet);
} catch (err: any) {
csResult = err.errorNumber;
}
const endTime = new Date().getTime();
const elapsedTime = (endTime - startTime) / 1000.0;
results.push({
csNum: changeSet.index,
csId: changeSet.id,
csResult,
time: elapsedTime,
});
}
perfLogger.dispose();
nativeDb.closeIModel();
return results;
}
private static getSeedPathname(iModelDir: string) {
const seedFileDir = path.join(iModelDir, "seed");
const seedFileNames = IModelJsFs.readdirSync(seedFileDir);
if (seedFileNames.length !== 1) {
throw new Error(`Expected to find one and only one seed file in: ${seedFileDir}`);
}
const seedFileName = seedFileNames[0];
const seedPathname = path.join(seedFileDir, seedFileName);
return seedPathname;
}
/** Reads change sets from disk and expects a standard structure of how the folder is organized */
public static readChangesets(iModelDir: string): ChangesetFileProps[] {
const props: ChangesetFileProps[] = [];
const changeSetJsonPathname = path.join(iModelDir, "changesets.json");
if (!IModelJsFs.existsSync(changeSetJsonPathname))
return props;
const jsonStr = IModelJsFs.readFileSync(changeSetJsonPathname) as string;
const changesets = JSON.parse(jsonStr);
for (const changeset of changesets) {
changeset.index = parseInt(changeset.index, 10); // it's a string from iModelHub
const pathname = path.join(iModelDir, "changesets", `${changeset.id}.cs`);
if (!IModelJsFs.existsSync(pathname))
throw new Error(`Cannot find the ChangeSet file: ${pathname}`);
props.push({ ...changeset, pathname });
}
return props;
}
/** Creates a standalone iModel from the seed file (version 0) */
public static copyIModelFromSeed(iModelPathname: string, iModelDir: string, overwrite: boolean) {
const seedPathname = HubUtility.getSeedPathname(iModelDir);
if (!IModelJsFs.existsSync(iModelPathname)) {
IModelJsFs.copySync(seedPathname, iModelPathname);
} else if (overwrite) {
IModelJsFs.unlinkSync(iModelPathname);
IModelJsFs.copySync(seedPathname, iModelPathname);
}
const nativeDb = new IModelHost.platform.DgnDb();
nativeDb.openIModel(iModelPathname, OpenMode.ReadWrite);
nativeDb.deleteAllTxns();
nativeDb.resetBriefcaseId(BriefcaseIdValue.Unassigned);
if (nativeDb.queryLocalValue("StandaloneEdit"))
nativeDb.deleteLocalValue("StandaloneEdit");
nativeDb.saveChanges();
nativeDb.closeIModel();
return iModelPathname;
}
}
/** An implementation of TestITwin backed by an iTwin */
class TestITwin {
public get isIModelHub(): boolean { return true; }
public terminate(): void { }
private static _iTwinAccessClient?: ProjectsAccessClient;
private static get iTwinClient(): ProjectsAccessClient {
if (this._iTwinAccessClient === undefined)
this._iTwinAccessClient = new ProjectsAccessClient();
return this._iTwinAccessClient;
}
public async getITwinByName(accessToken: AccessToken, name: string): Promise<ITwin> {
const client = TestITwin.iTwinClient;
const iTwinList: ITwin[] = await client.getAll(accessToken, {
search: {
searchString: name,
propertyName: ProjectsSearchableProperty.Name,
exactMatch: true,
},
});
if (iTwinList.length === 0)
throw new Error(`ITwin ${name} was not found for the user.`);
else if (iTwinList.length > 1)
throw new Error(`Multiple iTwins named ${name} were found for the user.`);
return iTwinList[0];
}
}
let iTwinAbstraction: TestITwin;
export function getITwinAbstraction(): TestITwin {
if (iTwinAbstraction !== undefined)
return iTwinAbstraction;
return iTwinAbstraction = new TestITwin();
} | the_stack |
import * as chai from 'chai'
import * as chaiAsPromised from 'chai-as-promised'
import 'mocha'
import {
PermissionRequest,
BeaconMessageType,
ConnectionContext,
LocalStorage,
NetworkType,
P2PTransport,
BEACON_VERSION,
Origin,
PermissionResponseInput,
AppMetadataManager,
PermissionManager,
PermissionInfo,
PermissionScope,
Serializer,
getSenderId,
BeaconErrorType,
BeaconResponseInputMessage
} from '../../src'
import * as sinon from 'sinon'
import { WalletClient } from '../../src/clients/wallet-client/WalletClient'
import { ExtendedP2PPairingRequest } from '../../src/types/P2PPairingRequest'
import { windowRef } from '../../src/MockWindow'
// use chai-as-promised plugin
chai.use(chaiAsPromised)
const expect = chai.expect
const pubkey1 = 'c126ba9a0217756c4d3540ba15aaa01e0edcb7c917d66f64db20b1dae8296ddd'
const senderId1 = 'NMPgABdfdvBE'
const pubkey2 = '04be24648e1b753cbfc6cb46aa12f8f2469f9cdf3b414a33ebcb807912d43447'
const senderId2 = 'QwMX82A3vQwX'
const peer1: ExtendedP2PPairingRequest = {
id: 'id1',
type: 'p2p-pairing-request',
name: 'test',
senderId: senderId1,
version: BEACON_VERSION,
publicKey: pubkey1,
relayServer: 'test-relay.walletbeacon.io'
}
const peer2: ExtendedP2PPairingRequest = {
id: 'id2',
type: 'p2p-pairing-request',
name: 'test',
senderId: senderId2,
version: BEACON_VERSION,
publicKey: pubkey2,
relayServer: 'test-relay.walletbeacon.io'
}
describe(`WalletClient`, () => {
before(function () {
/**
* This is used to mock the window object
*
* We cannot do it globally because it fails in the storage tests because of security policies
*/
this.jsdom = require('jsdom-global')('<!doctype html><html><body></body></html>', {
url: 'http://localhost/'
})
})
after(function () {
/**
* Remove jsdom again because it's only needed in this test
*/
this.jsdom()
sinon.restore()
})
beforeEach(() => {
sinon.restore()
;(windowRef as any).beaconCreatedClientInstance = false
})
it(`should throw an error if initialized with an empty object`, async () => {
try {
const walletClient = new WalletClient({} as any)
expect(walletClient).to.be.undefined
} catch (e) {
expect(e.message).to.equal('Name not set')
}
})
it(`should initialize without an error`, async () => {
const walletClient = new WalletClient({ name: 'Test' })
expect(walletClient).to.not.be.undefined
})
it(`should have a beacon ID`, async () => {
const walletClient = new WalletClient({ name: 'Test', storage: new LocalStorage() })
expect(typeof (await walletClient.beaconId)).to.equal('string')
})
it(`should connect and register the callback and receive a callback`, async () => {
const walletClient = new WalletClient({ name: 'Test', storage: new LocalStorage() })
const connectStub = sinon.stub(P2PTransport.prototype, 'connect').resolves()
const addListenerStub = sinon.stub(P2PTransport.prototype, 'addListener').resolves()
const callback = sinon.fake()
await walletClient.init()
await walletClient.connect(callback)
expect(typeof (<any>walletClient).handleResponse).to.equal('function')
expect(connectStub.callCount).to.equal(1)
expect(addListenerStub.callCount).to.equal(1)
expect(callback.callCount).to.equal(0)
const message: PermissionRequest = {
id: 'some-id',
version: BEACON_VERSION,
senderId: 'sender-id',
type: BeaconMessageType.PermissionRequest,
appMetadata: { name: 'test', senderId: 'sender-id-2' },
network: { type: NetworkType.MAINNET },
scopes: []
}
const contextInfo: ConnectionContext = {
origin: Origin.P2P,
id: 'some-id'
}
await (<any>walletClient).handleResponse(message, contextInfo)
expect(callback.callCount).to.equal(1)
expect(callback.firstCall.args[0]).to.equal(message)
expect(callback.firstCall.args[1]).to.equal(contextInfo)
})
it(`should not respond to a message if matching request is not found`, async () => {
const walletClient = new WalletClient({ name: 'Test', storage: new LocalStorage() })
const id = 'some-id'
const message: PermissionResponseInput = {
id,
type: BeaconMessageType.PermissionResponse,
network: { type: NetworkType.MAINNET },
scopes: [],
publicKey: 'public-key'
}
try {
await walletClient.respond(message)
throw new Error('Should not work!')
} catch (error) {
expect(error.message).to.equal('No matching request found!')
}
})
it(`should respond to a message if matching request is found`, async () => {
const walletClient = new WalletClient({ name: 'Test', storage: new LocalStorage() })
const id = 'some-id'
const message: PermissionResponseInput = {
id,
type: BeaconMessageType.PermissionResponse,
network: { type: NetworkType.MAINNET },
scopes: [],
publicKey: '69421294fd0136926639977666e8523550af4c126b6bcd429d3ae555c7aca3a3'
}
;(<any>walletClient).pendingRequests.push([{ id }, {}])
const respondStub = sinon.stub(walletClient, <any>'respondToMessage').resolves()
const appMetadataManagerStub = sinon
.stub(AppMetadataManager.prototype, 'getAppMetadata')
.resolves({ name: 'my-test', senderId: 'my-sender-id' })
await walletClient.respond(message)
expect(appMetadataManagerStub.callCount).to.equal(1)
expect(respondStub.callCount).to.equal(1)
expect(respondStub.firstCall.args[0]).to.include(message)
})
it(`should remove a peer and all its permissions`, async () => {
const walletClient = new WalletClient({ name: 'Test', storage: new LocalStorage() })
const transportRemovePeerStub = sinon.stub(P2PTransport.prototype, 'removePeer').resolves()
const removePermissionsForPeersStub = sinon
.stub(walletClient, <any>'removePermissionsForPeers')
.resolves()
await walletClient.init()
await walletClient.removePeer(peer1 as any)
expect(transportRemovePeerStub.callCount).to.equal(1)
expect(removePermissionsForPeersStub.callCount).to.equal(1)
})
it(`should remove all peers and all their permissions`, async () => {
const walletClient = new WalletClient({ name: 'Test', storage: new LocalStorage() })
const transportGetPeerStub = sinon.stub(P2PTransport.prototype, 'getPeers').resolves([])
const transportRemoveAllPeersStub = sinon
.stub(P2PTransport.prototype, 'removeAllPeers')
.resolves()
const removePermissionsForPeersStub = sinon
.stub(walletClient, <any>'removePermissionsForPeers')
.resolves()
await walletClient.init()
await walletClient.removeAllPeers()
expect(transportGetPeerStub.callCount, 'transportGetPeerStub').to.equal(1)
expect(transportRemoveAllPeersStub.callCount, 'transportRemoveAllPeersStub').to.equal(1)
expect(removePermissionsForPeersStub.callCount, 'removePermissionsForPeersStub').to.equal(1)
})
it(`should remove all permissions for peers (empty storage)`, async () => {
const walletClient = new WalletClient({ name: 'Test', storage: new LocalStorage() })
const permissionManagerGetPermissionsSpy = sinon.spy(
PermissionManager.prototype,
'getPermissions'
)
const permissionManagerRemovePermissionsSpy = sinon.spy(
PermissionManager.prototype,
'removePermissions'
)
await walletClient.init()
await (<any>walletClient).removePermissionsForPeers([peer1, peer2])
expect(
permissionManagerGetPermissionsSpy.callCount,
'permissionManagerGetPermissionsSpy'
).to.equal(1)
expect(
permissionManagerRemovePermissionsSpy.callCount,
'permissionManagerRemovePermissionsSpy'
).to.equal(1)
expect(permissionManagerRemovePermissionsSpy.firstCall.args[0].length).to.equal(0)
})
it(`should remove all permissions for peers (two accounts for 1 peer)`, async () => {
const walletClient = new WalletClient({ name: 'Test', storage: new LocalStorage() })
const permission1: PermissionInfo = {
accountIdentifier: 'a1',
senderId: await getSenderId(peer1.publicKey),
appMetadata: { senderId: await getSenderId(peer1.publicKey), name: 'name1' },
website: 'website1',
address: 'tz1',
publicKey: 'publicKey1',
network: { type: NetworkType.MAINNET },
scopes: [PermissionScope.SIGN],
connectedAt: new Date().getTime()
}
const permission2: PermissionInfo = {
accountIdentifier: 'a2',
senderId: await getSenderId(peer1.publicKey),
appMetadata: { senderId: await getSenderId(peer1.publicKey), name: 'name1' },
website: 'website2',
address: 'tz1',
publicKey: 'publicKey2',
network: { type: NetworkType.MAINNET },
scopes: [PermissionScope.SIGN],
connectedAt: new Date().getTime()
}
const permissionManagerGetPermissionsStub = sinon
.stub(PermissionManager.prototype, 'getPermissions')
.resolves([permission1, permission2])
const permissionManagerRemovePermissionsStub = sinon.stub(
PermissionManager.prototype,
'removePermissions'
)
await walletClient.init()
await (<any>walletClient).removePermissionsForPeers([peer1, peer2])
expect(
permissionManagerGetPermissionsStub.callCount,
'permissionManagerGetPermissionsStub'
).to.equal(1)
expect(
permissionManagerRemovePermissionsStub.callCount,
'permissionManagerRemovePermissionsStub'
).to.equal(1)
expect(permissionManagerRemovePermissionsStub.firstCall.args[0].length).to.equal(2)
expect(permissionManagerRemovePermissionsStub.firstCall.args[0][0]).to.equal('a1')
expect(permissionManagerRemovePermissionsStub.firstCall.args[0][1]).to.equal('a2')
})
it(`should respond to a message`, async () => {
const walletClient = new WalletClient({ name: 'Test', storage: new LocalStorage() })
const serializerStub = sinon.stub(Serializer.prototype, 'serialize').resolves()
// const sendStub = sinon.stub(P2PTransport.prototype, 'send').resolves()
await walletClient.init()
;(<any>walletClient).respondToMessage({ test: 'message' })
// TODO: Test if acknowledge message is sent
expect(serializerStub.callCount).to.equal(1)
expect(serializerStub.firstCall.args[0]).to.deep.equal({ test: 'message' })
// expect(sendStub.callCount).to.equal(1)
// expect(sendStub.firstCall.args[0]).to.equal('aRNACa2rFgw2dfAugetVZpzSbMdahH')
})
it(`should respond with an error message`, async () => {
const walletClient = new WalletClient({ name: 'Test', storage: new LocalStorage() })
const respondStub = sinon.stub(walletClient, <any>'respondToMessage').resolves()
const id = '1234test'
;(<any>walletClient).pendingRequests.push([{ id }, {}])
await walletClient.init()
const message: BeaconResponseInputMessage = {
id,
type: BeaconMessageType.Error,
errorType: BeaconErrorType.TRANSACTION_INVALID_ERROR,
errorData: [
{
kind: 'temporary',
id: 'proto.007-PsDELPH1.contract.non_existing_contract',
contract: 'KT1RxKJyi48W3bZR8HErRiisXZQw19HwLGWj'
}
]
}
await walletClient.respond(message)
expect(respondStub.callCount).to.equal(1)
expect(respondStub.firstCall.args[0]).to.include(message)
expect(respondStub.firstCall.args[0].errorData).not.to.be.undefined
})
it(`should respond with an error message`, async () => {
const walletClient = new WalletClient({ name: 'Test', storage: new LocalStorage() })
const respondStub = sinon.stub(walletClient, <any>'respondToMessage').resolves()
const id = '1234test'
;(<any>walletClient).pendingRequests.push([{ id }, {}])
await walletClient.init()
const message: BeaconResponseInputMessage = {
id,
type: BeaconMessageType.Error,
errorType: BeaconErrorType.PARAMETERS_INVALID_ERROR,
errorData: [
{
kind: 'temporary',
id: 'proto.007-PsDELPH1.contract.non_existing_contract',
contract: 'KT1RxKJyi48W3bZR8HErRiisXZQw19HwLGWj'
}
]
}
await walletClient.respond(message)
const { errorData, ...newMessage } = message
expect(respondStub.callCount).to.equal(1)
expect(respondStub.firstCall.args[0]).to.include(newMessage)
expect(respondStub.firstCall.args[0].errorData).to.be.undefined
})
it(`should not respond with an invalid error message`, async () => {
const walletClient = new WalletClient({ name: 'Test', storage: new LocalStorage() })
const respondStub = sinon.stub(walletClient, <any>'respondToMessage').resolves()
const id = '1234test'
;(<any>walletClient).pendingRequests.push([{ id }, {}])
await walletClient.init()
const message: BeaconResponseInputMessage = {
id,
type: BeaconMessageType.Error,
errorType: BeaconErrorType.PARAMETERS_INVALID_ERROR,
errorData: {
test: 123
}
}
await walletClient.respond(message)
const { errorData, ...newMessage } = message
expect(respondStub.callCount).to.equal(1)
expect(respondStub.firstCall.args[0]).to.include(newMessage)
expect(respondStub.firstCall.args[0].errorData).to.be.undefined
})
}) | the_stack |
import * as ChildProcess from 'child_process';
import { EventEmitter } from 'events';
import * as Fs from 'fs-extra';
import { resolve } from 'path';
/**
Contains general utilities.
*/
let cwdReturnValue: string;
let git;
let npm;
let node;
function init() {
// Defaults to process's current working dir
cwdReturnValue = process.env.TORTILLA_CWD || process.cwd();
try {
cwdReturnValue = ChildProcess.execFileSync('git', [
'rev-parse', '--show-toplevel',
], {
cwd: cwdReturnValue,
stdio: ['pipe', 'pipe', 'ignore'],
}).toString()
.trim();
} catch (err) {
// If no git-exists nor git-failed use default value instead
}
// Setting all relative utils
(exec as any).print = spawn;
git = exec.bind(null, 'git');
git.print = spawn.bind(null, 'git');
npm = exec.bind(null, 'npm');
npm.print = spawn.bind(null, 'npm');
node = exec.bind(null, 'node');
node.print = spawn.bind(null, 'node');
}
init();
function cwd () {
return cwdReturnValue;
}
// Checks if one of the parent processes launched by the provided file and has
// the provided arguments
function isChildProcessOf(file, argv, offset?) {
// There might be nested processes of the same file so we wanna go through all of them,
// This variable represents how much skips will be done anytime the file is found.
let trial = offset = offset || 0;
// The current process would be the node's
const currProcess = {
file: process.title,
pid: process.pid,
argv: process.argv,
};
// Will abort once the file is found and there are no more skips left to be done
while (currProcess.file !== file || trial--) {
// Get the parent process id
currProcess.pid = Number(getProcessData(currProcess.pid, 'ppid'));
// The root process'es id is 0 which means we've reached the limit
if (!currProcess.pid) {
return false;
}
currProcess.argv = getProcessData(currProcess.pid, 'command')
.split(' ')
.filter(Boolean);
// The first word in the command would be the file name
currProcess.file = currProcess.argv[0];
// The rest would be the arguments vector
currProcess.argv = currProcess.argv.slice(1);
}
// Make sure it has the provided arguments
const result = argv.every((arg) => currProcess.argv.indexOf(arg) !== -1);
// If this is not the file we're looking for keep going up in the processes tree
return result || isChildProcessOf(file, argv, ++offset);
}
// Gets process data using 'ps' formatting
function getProcessData(pid, format) {
if (arguments.length === 1) {
format = pid;
pid = process.pid;
}
const result = exec('ps', ['-p', pid, '-o', format]).split('\n');
result.shift();
return result.join('\n');
}
// Spawn new process and print result to the terminal
function spawn(file: string, argv?: string[], options?) {
argv = argv || [];
options = extend({
cwd: process.env.TORTILLA_CWD || cwd(),
stdio: process.env.TORTILLA_STDIO || 'inherit',
env: {},
maxBuffer: 10 * 1024 * 1024,
}, options);
const envRedundantKeys = Object.keys(options.env).filter((key) => {
return options.env[key] == null;
});
options.env = extend({
TORTILLA_CHILD_PROCESS: true,
}, process.env, options.env);
envRedundantKeys.forEach((key) => {
delete options.env[key];
});
return ChildProcess.spawnSync(file, argv, options);
}
// Execute file
function exec(file: string, argv?: string[], options?) {
argv = argv || [];
options = extend({
cwd: process.env.TORTILLA_CWD || cwd(),
stdio: 'pipe',
maxBuffer: 10 * 1024 * 1024,
env: {},
}, options);
const envRedundantKeys = Object.keys(options.env).filter((key) => {
return options.env[key] == null;
});
options.env = {
TORTILLA_CHILD_PROCESS: true,
...process.env,
...options.env,
};
envRedundantKeys.forEach((key) => {
delete options.env[key];
});
debug(`Executing (execFileSync) command "${file} ${argv.join(' ')}" (${options.cwd})`);
const out = ChildProcess.execFileSync(file, argv, options);
// In case of stdio inherit
if (!out) {
return '';
}
return out.toString().trim();
}
function inspect(str: string, argv: string[] = []) {
return spawn('less', argv, {
input: str,
stdio: ['pipe', 'inherit', 'inherit']
});
}
// Tells if entity exists or not by an optional document type
function exists(path, type?) {
try {
const stats = Fs.lstatSync(path);
switch (type) {
case 'dir':
return stats.isDirectory();
case 'file':
return stats.isFile();
case 'symlink':
return stats.isSymbolicLink();
default:
return true;
}
} catch (err) {
return false;
}
}
// Create a temporary scope which will define provided variables on the environment
function scopeEnv(fn, env) {
const keys = Object.keys(env);
const originalEnv = pluck(process.env, keys);
const nullKeys = keys.filter((key) => process.env[key] == null);
extend(process.env, env);
try {
return fn();
} finally {
extend(process.env, originalEnv);
contract(process.env, nullKeys);
}
}
// Filter all strings matching the provided pattern in an array
function filterMatches(arr, pattern) {
pattern = pattern || '';
return arr.filter((str) => str.match(pattern));
}
// Deeply merges destination object with source object
function merge(destination, source) {
if (!(destination instanceof Object) ||
!(source instanceof Object)) {
return source;
}
Object.keys(source).forEach((k) => {
destination[k] = merge(destination[k], source[k]);
});
return destination;
}
// Extend destination object with provided sources
function extend(destination, ...sources) {
sources.forEach((source) => {
if (!(source instanceof Object)) {
return;
}
Object.keys(source).forEach((k) => {
destination[k] = source[k];
});
});
return destination;
}
// Deletes all keys in the provided object
function contract(destination, keys) {
keys.forEach((key) => {
delete destination[key];
});
return destination;
}
// Plucks all keys from object
function pluck(obj, keys) {
return keys.reduce((result, key) => {
result[key] = obj[key];
return result;
}, {});
}
// Pad the provided string with the provided pad params from the left
// '1' -> '00001'
function pad(str, length, char?) {
str = str.toString();
char = char || ' ';
const chars = Array(length + 1).join(char);
return chars.substr(0, chars.length - str.length) + str;
}
// Like pad() only from the right
// '1' -> '10000'
function padRight(str, length, char?) {
str = str.toString();
char = char || ' ';
const chars = Array(length + 1).join(char);
return str + chars.substr(0, chars.length - str.length);
}
// foo_barBaz -> foo-bar-baz
function toKebabCase(str) {
return splitWords(str)
.map(lowerFirst)
.join('-');
}
// foo_barBaz -> Foo Bar Baz
function toStartCase(str) {
return splitWords(str)
.map(upperFirst)
.join(' ');
}
// Lower -> lower
function lowerFirst(str) {
return str.substr(0, 1).toLowerCase() + str.substr(1);
}
// upper -> Upper
function upperFirst(str) {
return str.substr(0, 1).toUpperCase() + str.substr(1);
}
// foo_barBaz -> ['foo', 'bar', 'Baz']
function splitWords(str) {
return str
.replace(/[A-Z]/, ' $&')
.split(/[^a-zA-Z0-9]+/);
}
// Wraps source descriptors and defines them on destination. The modifiers object
// contains the wrappers for the new descriptors, and has 3 properties:
// - value - A value wrapper, if function
// - get - A getter wrapper
// - set - A setter wrapper
// All 3 wrappers are called with 3 arguments: handler, propertyName, args
function delegateProperties(destination, source, modifiers) {
Object.getOwnPropertyNames(source).forEach((propertyName) => {
const propertyDescriptor = Object.getOwnPropertyDescriptor(source, propertyName);
if (typeof propertyDescriptor.value === 'function' && modifiers.value) {
const superValue = propertyDescriptor.value;
propertyDescriptor.value = function() {
const args = [].slice.call(arguments);
return modifiers.value.call(this, superValue, propertyName, args);
};
} else {
if (propertyDescriptor.get && modifiers.get) {
const superGetter = propertyDescriptor.get;
propertyDescriptor.get = function() {
return modifiers.get.call(this, superGetter, propertyName);
};
}
if (propertyDescriptor.set && modifiers.set) {
const superGetter = propertyDescriptor.set;
propertyDescriptor.set = function(value) {
return modifiers.value.call(this, superGetter, propertyName, value);
};
}
}
Object.defineProperty(destination, propertyName, propertyDescriptor);
});
return destination;
}
function isEqual(objA, objB) {
if (objA === objB) {
return true;
}
if (typeof objA !== typeof objB) {
return false;
}
if (!(objA instanceof Object) || !(objB instanceof Object)) {
return false;
}
if ((objA as any).__proto__ !== (objB as any).__proto__) {
return false;
}
const objAKeys = Object.keys(objA);
const objBKeys = Object.keys(objB);
if (objAKeys.length !== objBKeys.length) {
return;
}
objAKeys.sort();
objBKeys.sort();
return objAKeys.every((keyA, index) => {
const keyB = objBKeys[index];
if (keyA !== keyB) {
return false;
}
const valueA = objA[keyA];
const valueB = objB[keyB];
return isEqual(valueA, valueB);
});
}
function escapeBrackets(str) {
return str
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)')
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
.replace(/\{/g, '\\{')
.replace(/\}/g, '\\}')
.replace(/\</g, '\\<')
.replace(/\>/g, '\\>');
}
// Takes a shell script string and transforms it into a one liner
function shCmd(cmd) {
return cmd
.trim()
.replace(/\n+/g, ';')
.replace(/\s+/g, ' ')
.replace(/then\s*;/g, 'then')
.replace(/else\s*;/g, 'else')
.replace(/;\s*;/g, ';')
.trim();
}
function naturalSort(as, bs) {
let a1;
let b1;
let i = 0;
let n;
const rx = /(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.\D+)|(\.$)/g;
if (as === bs) {
return 0;
}
const a = as.toLowerCase().match(rx);
const b = bs.toLowerCase().match(rx);
const L = a.length;
while (i < L) {
if (!b[i]) {
return 1;
}
a1 = a[i];
b1 = b[i++];
if (a1 !== b1) {
n = a1 - b1;
if (!isNaN(n)) {
return n;
}
return a1 > b1 ? 1 : -1;
}
}
return b[i] ? -1 : 0;
}
// Temporarily changes CWD for child_process and then restores it at the end
// of the execution. Useful for submodules. Will emit a 'cwdChange' event once
// it happens to do so
function setTempCwd(callback, tempCwd) {
tempCwd = resolve(cwd(), tempCwd);
const result = scopeEnv(() => {
init();
Utils.emit('cwdChange', tempCwd);
return callback();
}, {
TORTILLA_CWD: tempCwd
});
init();
Utils.emit('cwdChange', cwdReturnValue);
return result;
}
// Will use the shortest indention as an axis
export const freeText = (text) => {
if (text instanceof Array) {
text = text.join('')
}
// This will allow inline text generation with external functions, same as ctrl+shift+c
// As long as we surround the inline text with ==>text<==
text = text.replace(
/( *)==>((?:.|\n)*?)<==/g,
(match, baseIndent, content) =>
{
return content
.split('\n')
.map(line => `${baseIndent}${line}`)
.join('\n')
})
const lines = text.split('\n')
const minIndent = lines.filter(line => line.trim()).reduce((soFar, line) => {
const currIndent = line.match(/^ */)[0].length
return currIndent < soFar ? currIndent : soFar
}, Infinity)
return lines
.map(line => line.slice(minIndent))
.join('\n')
.trim()
.replace(/\n +\n/g, '\n\n')
}
export function pluckRemoteData(remoteUrl) {
// git@github.com:Urigo/WhatsApp-Clone-Client-React.git
const match = (
remoteUrl.match(/^git@([^\n:]+):([^\n\/]+)\/([^\n\.]+)(\.git)?$/) ||
remoteUrl.match(/^https?:\/\/([^\n\/]+)\/([^\n\/]+)\/([^\n\.]+)(\.git)?$/)
)
if (!match) { return null }
return {
host: match[1],
owner: match[2],
repo: match[3],
}
}
function log(...args) {
console.log(...args);
}
function debug(...args) {
if (process.env.DEBUG) {
console.log(...args);
}
}
export const Utils = Object.assign(new EventEmitter(), {
cwd,
exec,
inspect,
git,
npm,
childProcessOf: isChildProcessOf,
exists,
scopeEnv,
filterMatches,
merge,
extend,
contract,
pluck,
pad,
padRight,
kebabCase: toKebabCase,
startCase: toStartCase,
lowerFirst,
upperFirst,
words: splitWords,
delegateProperties,
isEqual,
escapeBrackets,
shCmd,
naturalSort,
tempCwd: setTempCwd,
freeText,
pluckRemoteData,
log,
debug,
}); | the_stack |
import * as ts from 'typescript';
import {ModulesManifest} from './modules_manifest';
import {getIdentifierText, Rewriter} from './rewriter';
import {isDtsFileName} from './tsickle';
import {toArray} from './util';
export interface Es5ProcessorHost {
/**
* Takes a context (the current file) and the path of the file to import
* and generates a googmodule module name
*/
pathToModuleName(context: string, importPath: string): string;
/**
* If we do googmodule processing, we polyfill module.id, since that's
* part of ES6 modules. This function determines what the module.id will be
* for each file.
*/
fileNameToModuleId(fileName: string): string;
/** Whether to convert CommonJS module syntax to `goog.module` Closure imports. */
googmodule?: boolean;
/** Whether the emit targets ES5 or ES6+. */
es5Mode?: boolean;
/**
* An additional prelude to insert in front of the emitted code, e.g. to import a shared library.
*/
prelude?: string;
}
/**
* Extracts the namespace part of a goog: import, or returns null if the given
* import is not a goog: import.
*/
export function extractGoogNamespaceImport(tsImport: string): string|null {
if (tsImport.match(/^goog:/)) return tsImport.substring('goog:'.length);
return null;
}
/**
* ES5Processor postprocesses TypeScript compilation output JS, to rewrite commonjs require()s into
* goog.require(). Contrary to its name it handles converting the modules in both ES5 and ES6
* outputs.
*/
class ES5Processor extends Rewriter {
/**
* namespaceImports collects the variables for imported goog.modules.
* If the original TS input is:
* import foo from 'goog:bar';
* then TS produces:
* var foo = require('goog:bar');
* and this class rewrites it to:
* var foo = require('goog.bar');
* After this step, namespaceImports['foo'] is true.
* (This is used to rewrite 'foo.default' into just 'foo'.)
*/
namespaceImports = new Set<string>();
/**
* moduleVariables maps from module names to the variables they're assigned to.
* Continuing the above example, moduleVariables['goog.bar'] = 'foo'.
*/
moduleVariables = new Map<string, string>();
/** strippedStrict is true once we've stripped a "use strict"; from the input. */
strippedStrict = false;
/** unusedIndex is used to generate fresh symbols for unnamed imports. */
unusedIndex = 0;
constructor(private host: Es5ProcessorHost, file: ts.SourceFile) {
super(file);
}
process(): {output: string, referencedModules: string[]} {
const moduleId = this.host.fileNameToModuleId(this.file.fileName);
// TODO(evanm): only emit the goog.module *after* the first comment,
// so that @suppress statements work.
const moduleName = this.host.pathToModuleName('', this.file.fileName);
// NB: No linebreak after module call so sourcemaps are not offset.
this.emit(`goog.module('${moduleName}');`);
if (this.host.prelude) this.emit(this.host.prelude);
// Allow code to use `module.id` to discover its module URL, e.g. to resolve
// a template URL against.
// Uses 'var', as this code is inserted in ES6 and ES5 modes.
// The following pattern ensures closure doesn't throw an error in advanced
// optimizations mode.
if (this.host.es5Mode) {
this.emit(`var module = module || {id: '${moduleId}'};`);
} else {
// The `exports = {}` serves as a default export to disable Closure Compiler's error checking
// for mutable exports. That's OK because TS compiler makes sure that consuming code always
// accesses exports through the module object, so mutable exports work.
// It is only inserted in ES6 because we strip `.default` accesses in ES5 mode, which breaks
// when assigning an `exports = {}` object and then later accessing it.
this.emit(` exports = {}; var module = {id: '${moduleId}'};`);
}
let pos = 0;
for (const stmt of this.file.statements) {
this.writeRange(this.file, pos, stmt.getFullStart());
this.visitTopLevel(stmt);
pos = stmt.getEnd();
}
this.writeRange(this.file, pos, this.file.getEnd());
const referencedModules = toArray(this.moduleVariables.keys());
// Note: don't sort referencedModules, as the keys are in the same order
// they occur in the source file.
const {output} = this.getOutput();
return {output, referencedModules};
}
/**
* visitTopLevel processes a top-level ts.Node and emits its contents.
*
* It's separate from the normal Rewriter recursive traversal
* because some top-level statements are handled specially.
*/
visitTopLevel(node: ts.Node) {
switch (node.kind) {
case ts.SyntaxKind.ExpressionStatement:
// Check for "use strict" and skip it if necessary.
if (!this.strippedStrict && this.isUseStrict(node)) {
this.emitCommentWithoutStatementBody(node);
this.strippedStrict = true;
return;
}
// Check for:
// - "require('foo');" (a require for its side effects)
// - "__export(require(...));" (an "export * from ...")
if (this.emitRewrittenRequires(node)) {
return;
}
// Check for
// Object.defineProperty(exports, "__esModule", ...);
if (this.isEsModuleProperty(node as ts.ExpressionStatement)) {
this.emitCommentWithoutStatementBody(node);
return;
}
// Otherwise fall through to default processing.
break;
case ts.SyntaxKind.VariableStatement:
// Check for a "var x = require('foo');".
if (this.emitRewrittenRequires(node)) return;
break;
default:
break;
}
this.visit(node);
}
/**
* The TypeScript AST attaches comments to statement nodes, so even if a node
* contains code we want to skip emitting, we need to emit the attached
* comment(s).
*/
emitCommentWithoutStatementBody(node: ts.Node) {
this.writeLeadingTrivia(node);
}
/** isUseStrict returns true if node is a "use strict"; statement. */
isUseStrict(node: ts.Node): boolean {
if (node.kind !== ts.SyntaxKind.ExpressionStatement) return false;
const exprStmt = node as ts.ExpressionStatement;
const expr = exprStmt.expression;
if (expr.kind !== ts.SyntaxKind.StringLiteral) return false;
const literal = expr as ts.StringLiteral;
return literal.text === 'use strict';
}
/**
* emitRewrittenRequires rewrites require()s into goog.require() equivalents.
*
* @return True if the node was rewritten, false if needs ordinary processing.
*/
emitRewrittenRequires(node: ts.Node): boolean {
// We're looking for requires, of one of the forms:
// - "var importName = require(...);".
// - "require(...);".
if (node.kind === ts.SyntaxKind.VariableStatement) {
// It's possibly of the form "var x = require(...);".
const varStmt = node as ts.VariableStatement;
// Verify it's a single decl (and not "var x = ..., y = ...;").
if (varStmt.declarationList.declarations.length !== 1) return false;
const decl = varStmt.declarationList.declarations[0];
// Grab the variable name (avoiding things like destructuring binds).
if (decl.name.kind !== ts.SyntaxKind.Identifier) return false;
const varName = getIdentifierText(decl.name as ts.Identifier);
if (!decl.initializer || decl.initializer.kind !== ts.SyntaxKind.CallExpression) return false;
const call = decl.initializer as ts.CallExpression;
const require = this.isRequire(call);
if (!require) return false;
this.writeLeadingTrivia(node);
this.emitGoogRequire(varName, require);
return true;
} else if (node.kind === ts.SyntaxKind.ExpressionStatement) {
// It's possibly of the form:
// - require(...);
// - __export(require(...));
// Both are CallExpressions.
const exprStmt = node as ts.ExpressionStatement;
const expr = exprStmt.expression;
if (expr.kind !== ts.SyntaxKind.CallExpression) return false;
const call = expr as ts.CallExpression;
let require = this.isRequire(call);
let isExport = false;
if (!require) {
// If it's an __export(require(...)), we emit:
// var x = require(...);
// __export(x);
// This extra variable is necessary in case there's a later import of the
// same module name.
require = this.isExportRequire(call);
isExport = require != null;
}
if (!require) return false;
this.writeLeadingTrivia(node);
const varName = this.emitGoogRequire(null, require);
if (isExport) {
this.emit(`__export(${varName});`);
}
return true;
} else {
// It's some other type of statement.
return false;
}
}
/**
* Emits a goog.require() statement for a given variable name and TypeScript import.
*
* E.g. from:
* var varName = require('tsImport');
* produces:
* var varName = goog.require('goog.module.name');
*
* If the input varName is null, generates a new variable name if necessary.
*
* @return The variable name for the imported module, reusing a previous import if one
* is available.
*/
emitGoogRequire(varName: string|null, tsImport: string): string {
let modName: string;
let isNamespaceImport = false;
const nsImport = extractGoogNamespaceImport(tsImport);
if (nsImport !== null) {
// This is a namespace import, of the form "goog:foo.bar".
// Fix it to just "foo.bar".
modName = nsImport;
isNamespaceImport = true;
} else {
modName = this.host.pathToModuleName(this.file.fileName, tsImport);
}
if (!varName) {
const mv = this.moduleVariables.get(modName);
if (mv) {
// Caller didn't request a specific variable name and we've already
// imported the module, so just return the name we already have for this module.
return mv;
}
// Note: we always introduce a variable for any import, regardless of whether
// the caller requested one. This avoids a Closure error.
varName = this.generateFreshVariableName();
}
if (isNamespaceImport) this.namespaceImports.add(varName);
if (this.moduleVariables.has(modName)) {
this.emit(`var ${varName} = ${this.moduleVariables.get(modName)};`);
} else {
this.emit(`var ${varName} = goog.require('${modName}');`);
this.moduleVariables.set(modName, varName);
}
return varName;
}
// workaround for syntax highlighting bug in Sublime: `
/**
* Returns the string argument if call is of the form
* require('foo')
*/
isRequire(call: ts.CallExpression): string|null {
// Verify that the call is a call to require(...).
if (call.expression.kind !== ts.SyntaxKind.Identifier) return null;
const ident = call.expression as ts.Identifier;
if (getIdentifierText(ident) !== 'require') return null;
// Verify the call takes a single string argument and grab it.
if (call.arguments.length !== 1) return null;
const arg = call.arguments[0];
if (arg.kind !== ts.SyntaxKind.StringLiteral) return null;
return (arg as ts.StringLiteral).text;
}
/**
* Returns the inner string if call is of the form
* __export(require('foo'))
*/
isExportRequire(call: ts.CallExpression): string|null {
if (call.expression.kind !== ts.SyntaxKind.Identifier) return null;
const ident = call.expression as ts.Identifier;
if (ident.getText() !== '__export') return null;
// Verify the call takes a single call argument and check it.
if (call.arguments.length !== 1) return null;
const arg = call.arguments[0];
if (arg.kind !== ts.SyntaxKind.CallExpression) return null;
return this.isRequire(arg as ts.CallExpression);
}
isEsModuleProperty(expr: ts.ExpressionStatement): boolean {
// We're matching the explicit source text generated by the TS compiler.
return expr.getText() === 'Object.defineProperty(exports, "__esModule", { value: true });';
}
/**
* maybeProcess is called during the recursive traversal of the program's AST.
*
* @return True if the node was processed/emitted, false if it should be emitted as is.
*/
protected maybeProcess(node: ts.Node): boolean {
switch (node.kind) {
case ts.SyntaxKind.PropertyAccessExpression:
const propAccess = node as ts.PropertyAccessExpression;
// We're looking for an expression of the form:
// module_name_var.default
if (getIdentifierText(propAccess.name) !== 'default') break;
if (propAccess.expression.kind !== ts.SyntaxKind.Identifier) break;
const lhs = getIdentifierText(propAccess.expression as ts.Identifier);
if (!this.namespaceImports.has(lhs)) break;
// Emit the same expression, with spaces to replace the ".default" part
// so that source maps still line up.
this.writeLeadingTrivia(node);
this.emit(`${lhs} `);
return true;
default:
break;
}
return false;
}
/** Generates a new variable name inside the tsickle_ namespace. */
generateFreshVariableName(): string {
return `tsickle_module_${this.unusedIndex++}_`;
}
}
/**
* Converts TypeScript's JS+CommonJS output to Closure goog.module etc.
* For use as a postprocessing step *after* TypeScript emits JavaScript.
*
* @param fileName The source file name.
* @param moduleId The "module id", a module-identifying string that is
* the value module.id in the scope of the module.
* @param pathToModuleName A function that maps a filesystem .ts path to a
* Closure module name, as found in a goog.require('...') statement.
* The context parameter is the referencing file, used for resolving
* imports with relative paths like "import * as foo from '../foo';".
* @param prelude An additional prelude to insert after the `goog.module` call,
* e.g. with additional imports or requires.
*/
export function processES5(host: Es5ProcessorHost, fileName: string, content: string):
{output: string, referencedModules: string[]} {
const file = ts.createSourceFile(fileName, content, ts.ScriptTarget.ES5, true);
return new ES5Processor(host, file).process();
}
export function convertCommonJsToGoogModuleIfNeeded(
host: Es5ProcessorHost, modulesManifest: ModulesManifest, fileName: string,
content: string): string {
if (!host.googmodule || isDtsFileName(fileName)) {
return content;
}
const {output, referencedModules} = processES5(host, fileName, content);
const moduleName = host.pathToModuleName('', fileName);
modulesManifest.addModule(fileName, moduleName);
for (const referenced of referencedModules) {
modulesManifest.addReferencedModule(fileName, referenced);
}
return output;
} | the_stack |
namespace LiteMol.Bootstrap.Entity.Transformer.Molecule {
"use strict";
export interface DownloadMoleculeSourceParams { id: string, format: Core.Formats.FormatInfo }
export function downloadMoleculeSource(params: { sourceId: string, name: string, description: string, urlTemplate: (id: string) => string, defaultId: string, specificFormat?: Core.Formats.FormatInfo, isFullUrl?: boolean }) {
return Tree.Transformer.action<Root, Action, DownloadMoleculeSourceParams>({
id: 'molecule-download-molecule-' + params.sourceId,
name: 'Molecule from ' + params.name,
description: params.description,
from: [Root],
to: [Action],
defaultParams: ctx => ({ id: params.defaultId, format: LiteMol.Core.Formats.Molecule.SupportedFormats.mmCIF }),
validateParams: p => (!p.id || !p.id.trim().length) ? [`Enter ${params.isFullUrl ? 'URL' : 'Id'}`] : void 0
}, (context, a, t) => {
let format = params.specificFormat ? params.specificFormat : t.params.format!;
return Tree.Transform.build()
.add(a, Data.Download, { url: params.urlTemplate(t.params.id!.trim()), type: format.isBinary ? 'Binary' : 'String', id: t.params.id, description: params.name, title: 'Molecule' })
.then(CreateFromData, { format: params.specificFormat ? params.specificFormat : t.params.format }, { isBinding: true })
.then(Molecule.CreateModel, { modelIndex: 0 }, { isBinding: false })
})
}
export interface OpenMoleculeFromFileParams { file: File | undefined }
export const OpenMoleculeFromFile = Tree.Transformer.action<Root, Action, OpenMoleculeFromFileParams>({
id: 'molecule-open-from-file',
name: 'Molecule from File',
description: `Open a molecule from a file (${LiteMol.Core.Formats.Molecule.SupportedFormats.All.map(f => f.name).join(', ')}).`,
from: [Root],
to: [Action],
defaultParams: ctx => ({ file: void 0 }),
validateParams: p => !p.file ? ['Select a file'] : !LiteMol.Core.Formats.FormatInfo.getFormat(p.file.name, LiteMol.Core.Formats.Molecule.SupportedFormats.All)
? [`Select a supported file format (${(<any[]>[]).concat(LiteMol.Core.Formats.Molecule.SupportedFormats.All.map(f => f.extensions)).join(', ')}).`]
: void 0
}, (context, a, t) => {
let format = LiteMol.Core.Formats.FormatInfo.getFormat(t.params.file!.name, LiteMol.Core.Formats.Molecule.SupportedFormats.All) !;
return Tree.Transform.build()
.add(a, Data.OpenFile, { file: t.params.file, type: format.isBinary ? 'Binary' : 'String' })
.then(CreateFromData, { format }, { isBinding: true })
.then(Molecule.CreateModel, { modelIndex: 0 }, { isBinding: false })
});
export interface CreateFromDataParams {
format: Core.Formats.FormatInfo,
customId?: string
}
export const CreateFromData = Tree.Transformer.create<Entity.Data.String | Entity.Data.Binary, Entity.Molecule.Molecule, CreateFromDataParams>({
id: 'molecule-create-from-data',
name: 'Molecule',
description: 'Create a molecule from string or binary data.',
from: [Entity.Data.String, Entity.Data.Binary],
to: [Entity.Molecule.Molecule],
defaultParams: (ctx) => ({ format: LiteMol.Core.Formats.Molecule.SupportedFormats.mmCIF })
}, (ctx, a, t) => {
return Task.create<Entity.Molecule.Molecule>(`Create Molecule (${a.props.label})`, 'Silent', async () => {
let r = await Task.fromComputation(`Create Molecule (${a.props.label})`, 'Normal', t.params.format!.parse(a.props.data, { id: t.params.customId }))
.setReportTime(true).run(ctx);
if (r.isError) throw r.toString();
if (r.warnings && r.warnings.length > 0) {
for (let w of r.warnings) {
ctx.logger.warning(w);
}
}
return Entity.Molecule.Molecule.create(t, { label: r.result.id, molecule: r.result });
});
});
export interface CreateFromMmCifParams {
blockIndex: number
}
export const CreateFromMmCif = Tree.Transformer.create<Entity.Data.CifDictionary, Entity.Molecule.Molecule, CreateFromMmCifParams>({
id: 'molecule-create-from-mmcif',
name: 'Molecule',
description: 'Create a molecule from a mmCIF data block.',
from: [Entity.Data.CifDictionary],
to: [Entity.Molecule.Molecule],
defaultParams: (ctx) => ({ blockIndex: 0 })
}, (ctx, a, t) => {
return Task.create<Entity.Molecule.Molecule>(`Create Molecule (${a.props.label})`, 'Normal', async ctx => {
await ctx.updateProgress('Creating...');
let index = t.params.blockIndex | 0;
let b = a.props.dictionary.dataBlocks[index];
if (!b) {
throw `The source contains only ${a.props.dictionary.dataBlocks.length} data block(s), tried to access the ${index + 1}-th.`;
}
let molecule = LiteMol.Core.Formats.Molecule.mmCIF.ofDataBlock(b);
return Entity.Molecule.Molecule.create(t, { label: molecule.id, molecule });
}).setReportTime(true);
});
export interface CreateModelParams {
modelIndex: number
}
export const CreateModel = Tree.Transformer.create<Entity.Molecule.Molecule, Entity.Molecule.Model, CreateModelParams>({
id: 'molecule-create-model',
name: 'Model',
description: 'Create a model of a molecule.',
from: [Entity.Molecule.Molecule],
to: [Entity.Molecule.Model],
isUpdatable: true,
defaultParams: ctx => ({ modelIndex: 0 })
}, (ctx, a, t) => {
return Task.create<Entity.Molecule.Model>(`Create Model (${a.props.label})`, 'Background', async ctx => {
let params = t.params;
let index = params.modelIndex | 0;
let model = a.props.molecule.models[index];
if (!model) {
throw `The molecule contains only ${a.props.molecule.models.length} model(s), tried to access the ${index + 1}-th.`;
}
return Entity.Molecule.Model.create(t, {
label: 'Model ' + model.modelId,
description: `${model.data.atoms.count} atom${model.data.atoms.count !== 1 ? 's' : ''}`,
model
});
});
});
export interface CreateSelectionParams {
name?: string,
queryString: string,
silent?: boolean,
inFullContext?: boolean
}
export const CreateSelection = Tree.Transformer.create<Entity.Molecule.Model | Entity.Molecule.Visual, Entity.Molecule.Selection, CreateSelectionParams>({
id: 'molecule-create-selection',
name: 'Selection',
description: 'Create an atom selection.',
from: [Entity.Molecule.Model, Entity.Molecule.Visual],
to: [Entity.Molecule.Selection],
isUpdatable: true,
defaultParams: ctx => ({ queryString: ctx.settings.get('molecule.model.defaultQuery') || '' }),
validateParams: p => {
if (!(p.queryString || '').trim().length) return ['Enter query'];
try {
return Core.Structure.Query.Builder.toQuery(p.queryString) && void 0 || void 0;
} catch (e) {
return ['' + e];
}
},
}, (ctx, a, t) => {
return Task.create<Entity.Molecule.Selection>(`Create Selection (${a.props.label})`, 'Background', async ctx => {
let params = t.params;
let query = Core.Structure.Query.Builder.toQuery(params.queryString);
let queryCtx = t.params.inFullContext ? Utils.Molecule.findModel(a) !.props.model.queryContext : Utils.Molecule.findQueryContext(a);
let indices = query(queryCtx).unionAtomIndices();
if (!indices.length) {
throw { warn: true, message: `Empty selection${t.params.name ? ' (' + t.params.name + ')' : ''}.` };
}
return Entity.Molecule.Selection.create(t, { label: params.name ? params.name : 'Selection', description: `${indices.length} atom${indices.length !== 1 ? 's' : ''}`, indices });
}).setReportTime(!t.params.silent);
});
export interface CreateSelectionFromQueryParams {
query: Core.Structure.Query.Source,
name?: string,
silent?: boolean,
inFullContext?: boolean
}
export const CreateSelectionFromQuery = Tree.Transformer.create<Entity.Molecule.Model | Entity.Molecule.Visual | Entity.Molecule.Selection, Entity.Molecule.Selection, CreateSelectionFromQueryParams>({
id: 'molecule-create-selection',
name: 'Selection',
description: 'Create an atom selection.',
from: [Entity.Molecule.Selection, Entity.Molecule.Model, Entity.Molecule.Visual],
to: [Entity.Molecule.Selection],
defaultParams: ctx => void 0,
}, (ctx, a, t) => {
return Task.create<Entity.Molecule.Selection>(`Create Selection (${a.props.label})`, 'Background', async ctx => {
let params = t.params;
let query = Core.Structure.Query.Builder.toQuery(params.query);
let queryCtx = t.params.inFullContext ? Utils.Molecule.findModel(a)!.props.model.queryContext : Utils.Molecule.findQueryContext(a);
let indices = query(queryCtx).unionAtomIndices();
if (!indices.length) {
throw { warn: true, message: `Empty selection${t.params.name ? ' (' + t.params.name + ')' : ''}.` };
}
return Entity.Molecule.Selection.create(t, { label: params.name ? params.name : 'Selection', description: `${indices.length} atom${indices.length !== 1 ? 's' : ''}`, indices });
}).setReportTime(!t.params.silent);
});
export interface CreateAssemblyParams {
name: string
}
export const CreateAssembly = Tree.Transformer.create<Entity.Molecule.Model, Entity.Molecule.Model, CreateAssemblyParams>({
id: 'molecule-create-assemly',
name: 'Assembly',
description: 'Create an assembly of a molecule.',
from: [Entity.Molecule.Model],
to: [Entity.Molecule.Model],
defaultParams: (ctx, e) => {
let m = Utils.Molecule.findModel(e) !;
let ret = ({ name: ctx.settings.get('molecule.model.defaultAssemblyName') || '1' });
let asm = m.props.model.data.assemblyInfo;
if (!asm || !asm.assemblies.length) return ret;
if (asm.assemblies.filter(a => a.name === ret.name)) return ret;
ret.name = asm.assemblies[0].name;
return ret;
},
isUpdatable: true,
isApplicable: m => !!(m && m.props.model.data.assemblyInfo && m.props.model.data.assemblyInfo.assemblies.length)
}, (ctx, a, t) => {
return Task.create<Entity.Molecule.Model>(`Create Model (${a.props.label})`, 'Background', async ctx => {
let i = a.props.model.data.assemblyInfo;
if (!i || !i.assemblies.length) {
throw 'Assembly info not available.';
}
let gen = i.assemblies.filter(a => a.name === t.params.name)[0];
if (!gen) {
throw `No assembly called '${t.params.name}' found.`;
}
await ctx.updateProgress('Creating...');
let asm = Core.Structure.buildAssembly(a.props.model, gen);
return Entity.Molecule.Model.create(t, {
label: 'Assembly ' + gen.name,
description: `${asm.data.atoms.count} atom${asm.data.atoms.count !== 1 ? 's' : ''}`,
model: asm
});
});
});
export interface CreateSymmetryMatesParams {
type: 'Mates' | 'Interaction',
radius: number
}
export const CreateSymmetryMates = Tree.Transformer.create<Entity.Molecule.Model, Entity.Molecule.Model, CreateSymmetryMatesParams>({
id: 'molecule-create-symmetry-mates',
name: 'Crystal Symmetry',
description: 'Find crystal symmetry mates or interaction partners.',
from: [Entity.Molecule.Model],
to: [Entity.Molecule.Model],
defaultParams: ctx => ({ type: 'Interaction', radius: 5.0 }),
isUpdatable: true,
isApplicable: m => {
if (!m || !m.props.model.data.symmetryInfo) return false;
const info = m.props.model.data.symmetryInfo;
if (info.cellSize[0] === 1 && info.cellSize[1] === 1 && info.cellSize[2] === 1) return false;
return true;
}
}, (ctx, a, t) => {
return Task.create<Entity.Molecule.Model>(`Create Model (${a.props.label})`, 'Background', async ctx => {
let i = a.props.model.data.symmetryInfo;
if (!i) {
throw 'Spacegroup info info not available.';
}
let radius = Math.max(t.params.radius, 0);
await ctx.updateProgress('Creating...');
let symm = t.params.type === 'Mates' ? Core.Structure.buildSymmetryMates(a.props.model, radius) : Core.Structure.buildPivotGroupSymmetry(a.props.model, radius);
return Entity.Molecule.Model.create(t, {
label: 'Symmetry',
model: symm,
description: `${symm.data.atoms.count} atom${symm.data.atoms.count !== 1 ? 's' : ''}, ${t.params.type} ${Utils.round(radius, 1)} \u212B`
});
});
});
export interface ModelTransform3DParams {
/**
* a 4x4 matrix stored as 1D array in column major order.
* (Use Core.Geometry.LinearAlgebra.Matrix4.empty & setValue(m, row, column, value)
* if you are not sure).
*/
transform: number[],
description?: string
}
export const ModelTransform3D = Tree.Transformer.create<Entity.Molecule.Model, Entity.Molecule.Model, ModelTransform3DParams>({
id: 'molecule-model-transform3d',
name: 'Transform 3D',
description: 'Transform 3D coordinates of a model using a 4x4 matrix.',
from: [Entity.Molecule.Model],
to: [Entity.Molecule.Model],
validateParams: p => !p || !p.transform || p.transform.length !== 16 ? ['Specify a 4x4 transform matrix.'] : void 0,
defaultParams: (ctx, e) => ({ transform: Core.Geometry.LinearAlgebra.Matrix4.identity() }),
isUpdatable: false
}, (ctx, a, t) => {
return Task.create<Entity.Molecule.Model>(`Transform 3D (${a.props.label})`, 'Normal', async ctx => {
await ctx.updateProgress('Transforming...');
let m = a.props.model;
let tCtx = { t: t.params.transform!, v: Core.Geometry.LinearAlgebra.Vector3.zero() };
let transformed = Core.Structure.Molecule.Model.withTransformedXYZ(m, tCtx, (ctx, x, y, z, out) => {
let v = ctx.v;
Core.Geometry.LinearAlgebra.Vector3.set(v, x, y, z);
Core.Geometry.LinearAlgebra.Vector3.transformMat4(out, v, ctx.t);
});
return Entity.Molecule.Model.create(t, {
label: a.props.label,
description: t.params.description ? t.params.description : 'Transformed',
model: transformed
});
});
});
export interface CreateVisualParams {
style: Visualization.Molecule.Style<any>
}
export const CreateVisual = Tree.Transformer.create<Entity.Molecule.Model | Entity.Molecule.Selection, Entity.Molecule.Visual, CreateVisualParams>({
id: 'molecule-create-visual',
name: 'Visual',
description: 'Create a visual of a molecule or a selection.',
from: [Entity.Molecule.Model, Entity.Molecule.Selection],
to: [Entity.Molecule.Visual],
isUpdatable: true,
defaultParams: ctx => ({ style: Visualization.Molecule.Default.ForType.get('Cartoons')! }),
validateParams: p => !p.style ? ['Specify Style'] : void 0,
customController: (ctx, t, e) => new Components.Transform.MoleculeVisual(ctx, t, e) as Components.Transform.Controller<any>
}, (ctx, a, t) => {
let params = t.params;
return Visualization.Molecule.create(a, t, params.style).setReportTime(Visualization.Style.getTaskType(t.params.style) === 'Normal');
}, (ctx, b, t) => {
let oldParams = b.transform.params as CreateVisualParams;
if (oldParams.style.type !== t.params.style.type || !Utils.deepEqual(oldParams.style.params, t.params.style.params)) return void 0;
let model = b.props.model;
if (!model) return void 0;
let a = Utils.Molecule.findModel(b.parent);
if (!a) return void 0;
let ti = t.params.style.theme!;
let theme = ti.template!.provider(a, Visualization.Theme.getProps(ti!));
model.applyTheme(theme);
b.props.style = t.params.style;
Entity.nodeUpdated(b);
return Task.resolve(t.transformer.info.name, 'Background', Tree.Node.Null);
});
export interface CreateMacromoleculeVisualParams {
groupRef?: string,
polymer?: boolean,
polymerRef?: string,
het?: boolean,
hetRef?: string,
water?: boolean,
waterRef?: string
}
export const CreateMacromoleculeVisual = Tree.Transformer.action<Entity.Molecule.Model | Entity.Molecule.Selection, Entity.Action, CreateMacromoleculeVisualParams>({
id: 'molecule-create-macromolecule-visual',
name: 'Macromolecule Visual',
description: 'Create a visual of a molecule that is split into polymer, HET, and water parts.',
from: [Entity.Molecule.Selection, Entity.Molecule.Model],
to: [Entity.Action],
validateParams: p => !p.polymer && !p.het && !p.water ? ['Select at least one component'] : void 0,
defaultParams: ctx => ({ polymer: true, het: true, water: true }),
}, (context, a, t) => {
let g = Tree.Transform.build().add(a, Basic.CreateGroup, { label: 'Group', description: 'Macromolecule' }, { ref: t.params.groupRef });
if (t.params.polymer) {
g.then(CreateSelectionFromQuery, { query: Core.Structure.Query.nonHetPolymer(), name: 'Polymer', silent: true }, { isBinding: true })
.then(CreateVisual, { style: Visualization.Molecule.Default.ForType.get('Cartoons') }, { ref: t.params.polymerRef });
}
if (t.params.het) {
g.then(CreateSelectionFromQuery, { query: Core.Structure.Query.hetGroups(), name: 'HET', silent: true }, { isBinding: true })
.then(CreateVisual, { style: Visualization.Molecule.Default.ForType.get('BallsAndSticks') }, { ref: t.params.hetRef });
}
if (t.params.water) {
let style: Visualization.Molecule.Style<Visualization.Molecule.BallsAndSticksParams> = {
type: 'BallsAndSticks',
params: { useVDW: false, atomRadius: 0.23, bondRadius: 0.09, detail: 'Automatic' },
theme: { template: Visualization.Molecule.Default.ElementSymbolThemeTemplate, colors: Visualization.Molecule.Default.ElementSymbolThemeTemplate.colors, transparency: { alpha: 0.25 } }
}
g.then(CreateSelectionFromQuery, { query: Core.Structure.Query.entities({ type: 'water' }), name: 'Water', silent: true }, { isBinding: true })
.then(CreateVisual, { style }, { ref: t.params.waterRef });
}
return g;
});
export interface CreateLabelsParams {
style: Visualization.Labels.Style<Utils.Molecule.Labels3DOptions>
}
export const CreateLabels = Tree.Transformer.create<Entity.Molecule.Model | Entity.Molecule.Selection | Entity.Molecule.Visual, Entity.Visual.Labels, CreateLabelsParams>({
id: 'molecule-create-labels',
name: 'Labels',
description: 'Create a labels for a molecule or a selection.',
from: [Entity.Molecule.Model, Entity.Molecule.Selection, Entity.Molecule.Visual],
to: [Entity.Visual.Labels],
isUpdatable: true,
defaultParams: ctx => ({ style: Visualization.Labels.Default.MoleculeLabels }),
validateParams: p => !p.style ? ['Specify Style'] : void 0,
customController: (ctx, t, e) => new Components.Transform.MoleculeLabels(ctx, t, e) as Components.Transform.Controller<any>
}, (ctx, a, t) => {
let params = t.params;
return Visualization.Labels.createMoleculeLabels(a, t, params.style).setReportTime(false);
}, (ctx, b, t) => {
const oldParams = b.transform.params;
const newParams = t.params;
if (!Visualization.Labels.Style.moleculeHasOnlyThemeChanged(oldParams.style, newParams.style)) return void 0;
const model = b.props.model;
const a = Tree.Node.findClosestNodeOfType(b, [Entity.Molecule.Model, Entity.Molecule.Selection, Entity.Molecule.Visual]);
if (!a) return void 0;
const theme = newParams.style.theme.template.provider(a, Visualization.Theme.getProps(newParams.style.theme));
model.applyTheme(theme);
Entity.nodeUpdated(b);
return Task.resolve(t.transformer.info.name, 'Background', Tree.Node.Null);
});
} | the_stack |
import RecordDeletion from './record-deletion'
import { recordRequestBinding } from './record-request'
import { RecordTransition } from './record-transition'
import { SubscriptionRegistry, Handler, DeepstreamConfig, DeepstreamServices, SocketWrapper, EVENT } from '@deepstream/types'
import { ListenerRegistry } from '../../listen/listener-registry'
import { isExcluded } from '../../utils/utils'
import { STATE_REGISTRY_TOPIC, RecordMessage, TOPIC, RecordWriteMessage, BulkSubscriptionMessage, ListenMessage, PARSER_ACTION, RECORD_ACTION as RA, JSONObject, Message, RECORD_ACTION, ALL_ACTIONS } from '../../constants'
export default class RecordHandler extends Handler<RecordMessage> {
private subscriptionRegistry: SubscriptionRegistry
private listenerRegistry: ListenerRegistry
private transitions = new Map<string, RecordTransition>()
private recordRequestsInProgress = new Map<string, Function[]>()
private recordRequest: Function
/**
* The entry point for record related operations
*/
constructor (private readonly config: DeepstreamConfig, private readonly services: DeepstreamServices, subscriptionRegistry?: SubscriptionRegistry, listenerRegistry?: ListenerRegistry, private readonly metaData?: any) {
super()
this.subscriptionRegistry =
subscriptionRegistry || services.subscriptions.getSubscriptionRegistry(TOPIC.RECORD, STATE_REGISTRY_TOPIC.RECORD_SUBSCRIPTIONS)
this.listenerRegistry =
listenerRegistry || new ListenerRegistry(TOPIC.RECORD, config, services, this.subscriptionRegistry, null)
this.subscriptionRegistry.setSubscriptionListener(this.listenerRegistry)
this.recordRequest = recordRequestBinding(config, services, this, metaData)
this.onDeleted = this.onDeleted.bind(this)
this.create = this.create.bind(this)
this.onPermissionResponse = this.onPermissionResponse.bind(this)
}
public async close () {
this.listenerRegistry.close()
}
/**
* Handles incoming record requests.
*
* Please note that neither CREATE nor READ is supported as a
* client send action. Instead the client sends CREATEORREAD
* and deepstream works which one it will be
*/
public handle (socketWrapper: SocketWrapper | null, message: RecordMessage): void {
const action = message.action
if (socketWrapper === null) {
this.handleClusterUpdate(message)
return
}
if (action === RA.SUBSCRIBE) {
this.subscriptionRegistry.subscribeBulk(message as BulkSubscriptionMessage, socketWrapper)
return
}
if (action === RA.SUBSCRIBECREATEANDREAD || action === RA.SUBSCRIBEANDREAD) {
const onSuccess = action === RA.SUBSCRIBECREATEANDREAD ? this.onSubscribeCreateAndRead : this.onSubscribeAndRead
const l = message.names!.length
for (let i = 0; i < l; i++) {
this.recordRequest(
message.names![i],
socketWrapper,
onSuccess,
onRequestError,
{ ...message, name: message.names![i] }
)
}
socketWrapper.sendAckMessage(message)
return
}
if (
action === RA.CREATEANDUPDATE ||
action === RA.CREATEANDPATCH
) {
/*
* Allows updates to the record without being subscribed, creates
* the record if it doesn't exist
*/
this.createAndUpdate(socketWrapper!, message as RecordWriteMessage)
return
}
if (action === RA.READ) {
/*
* Return the current state of the record in cache or db
*/
this.recordRequest(message.name, socketWrapper, onSnapshotComplete, onRequestError, message)
return
}
if (action === RA.HEAD) {
/*
* Return the current version of the record or -1 if not found
*/
this.head(socketWrapper!, message)
return
}
if (action === RA.SUBSCRIBEANDHEAD) {
/*
* Return the current version of the record or -1 if not found, subscribing either way
*/
this.subscribeAndHeadBulk(socketWrapper!, message)
return
}
if (action === RA.UPDATE || action === RA.PATCH || action === RA.ERASE) {
/*
* Handle complete (UPDATE) or partial (PATCH/ERASE) updates
*/
this.update(socketWrapper, message as RecordWriteMessage, message.isWriteAck || false)
return
}
if (action === RA.DELETE) {
/*
* Deletes the record
*/
this.delete(socketWrapper!, message)
return
}
if (action === RA.UNSUBSCRIBE) {
/*
* Unsubscribes (discards) a record that was previously subscribed to
* using read()
*/
this.subscriptionRegistry.unsubscribeBulk(message as BulkSubscriptionMessage, socketWrapper!)
return
}
if (action === RA.LISTEN || action === RA.UNLISTEN || action === RA.LISTEN_ACCEPT || action === RA.LISTEN_REJECT) {
/*
* Listen to requests for a particular record or records
* whose names match a pattern
*/
this.listenerRegistry.handle(socketWrapper!, message as ListenMessage)
return
}
if (message.action === RA.NOTIFY) {
this.recordUpdatedWithoutDeepstream(message, socketWrapper)
return
}
this.services.logger.error(PARSER_ACTION[PARSER_ACTION.UNKNOWN_ACTION], RA[action], this.metaData)
}
private handleClusterUpdate (message: RecordMessage) {
if (message.action === RA.DELETED) {
this.remoteDelete(message)
return
}
if (message.action === RA.NOTIFY) {
this.recordUpdatedWithoutDeepstream(message)
return
}
this.broadcastUpdate(message.name, {
topic: message.topic,
action: message.action,
name: message.name,
path: message.path,
version: message.version,
data: message.data,
parsedData: message.parsedData
}, false, null)
}
private async recordUpdatedWithoutDeepstream (message: RecordMessage, socketWrapper: SocketWrapper | null = null) {
if (socketWrapper) {
if (this.services.cache.deleteBulk === undefined) {
const errorMessage = 'Cache needs to implement deleteBulk in order for it to work correctly'
this.services.logger.error(EVENT.PLUGIN_ERROR, errorMessage)
socketWrapper.sendMessage({
topic: TOPIC.RECORD,
action: RECORD_ACTION.RECORD_NOTIFY_ERROR,
isError: true,
parsedData: errorMessage,
correlationId: message.correlationId
})
return
}
try {
await new Promise<void>((resolve, reject) => this.services.cache.deleteBulk(message.names!, (error) => {
error ? reject(error) : resolve()
}))
} catch (error) {
const errorMessage = 'Error deleting messages in bulk when attempting to notify of remote changes'
this.services.logger.error(EVENT.ERROR, `${errorMessage}: ${error.toString()}`, { message })
socketWrapper.sendMessage({
topic: TOPIC.RECORD,
action: RECORD_ACTION.RECORD_NOTIFY_ERROR,
isError: true,
parsedData: errorMessage,
correlationId: message.correlationId
})
return
}
}
let completed = 0
message.names!.forEach((recordName, index, names) => {
if (this.subscriptionRegistry.hasLocalSubscribers(recordName)) {
this.recordRequest(recordName, socketWrapper, (name: string, version: number, data: JSONObject) => {
if (version === -1) {
this.remoteDelete({
topic: TOPIC.RECORD,
action: RECORD_ACTION.DELETED,
name
})
} else {
this.subscriptionRegistry.sendToSubscribers(name, {
topic: TOPIC.RECORD,
action: RECORD_ACTION.UPDATE,
name,
version,
parsedData: data
}, true, null)
}
completed++
if (completed === names.length && socketWrapper) {
socketWrapper.sendAckMessage(message)
this.services.clusterNode.send(message)
}
}, (event: RA, errorMessage: string, name: string, socket: SocketWrapper, msg: Message) => {
completed++
if (socket) {
onRequestError(event, errorMessage, recordName, socket, msg)
}
if (completed === names.length && socket) {
socket.sendAckMessage(message)
this.services.clusterNode.send(message)
}
}, message)
} else {
completed++
if (completed === names.length && socketWrapper) {
socketWrapper.sendAckMessage(message)
this.services.clusterNode.send(message)
}
}
})
}
/**
* Returns just the current version number of a record
* Results in a HEAD_RESPONSE
* If the record is not found, the version number will be -1
*/
private head (socketWrapper: SocketWrapper, message: RecordMessage, name: string = message.name): void {
this.recordRequest(name, socketWrapper, onHeadComplete, onRequestError, message)
}
private subscribeAndHeadBulk (socketWrapper: SocketWrapper, message: RecordMessage): void {
this.services.cache.headBulk(message.names!, (error, versions, missing) => {
if (error) {
this.services.logger.error(EVENT.ERROR, `Error subscribing and head bulk for ${message.correlationId}`)
return
}
if (Object.keys(versions!).length > -1) {
socketWrapper.sendMessage({
topic: TOPIC.RECORD,
action: RA.HEAD_RESPONSE_BULK,
versions
})
}
this.subscriptionRegistry.subscribeBulk(message as BulkSubscriptionMessage, socketWrapper)
const l = missing!.length
for (let i = 0; i < l; i++) {
if (versions![missing![i]] === undefined) {
this.head(socketWrapper, message, missing![i])
}
}
})
}
private onSubscribeCreateAndRead (recordName: string, version: number, data: JSONObject | null, socketWrapper: SocketWrapper, message: RecordMessage) {
if (data) {
this.readAndSubscribe(message, version, data, socketWrapper)
} else {
this.permissionAction(
RA.CREATE,
message,
message.action,
socketWrapper,
this.create,
)
}
}
private onSubscribeAndRead (recordName: string, version: number, data: JSONObject | null, socketWrapper: SocketWrapper, message: RecordMessage) {
if (data) {
this.readAndSubscribe(message, version, data, socketWrapper)
} else {
this.permissionAction(RA.READ, message, message.action, socketWrapper, () => {
this.subscriptionRegistry.subscribe(message.name, { ...message, action: RA.SUBSCRIBE }, socketWrapper, message.names !== undefined)
socketWrapper.sendMessage({
topic: TOPIC.RECORD,
action: RECORD_ACTION.READ_RESPONSE,
name: message.name,
version: -1,
parsedData: {},
})
})
}
}
/**
* An upsert operation where the record will be created and written to
* with the data in the message. Important to note that each operation,
* the create and the write are permissioned separately.
*
* This method also takes note of the storageHotPathPatterns option, when a record
* with a name that matches one of the storageHotPathPatterns is written to with
* the CREATEANDUPDATE action, it will be permissioned for both CREATE and UPDATE, then
* inserted into the cache and storage.
*/
private createAndUpdate (socketWrapper: SocketWrapper, message: RecordWriteMessage): void {
const recordName = message.name
const isPatch = message.path !== undefined
const originalAction = message.action
message = { ...message, action: isPatch ? RA.PATCH : RA.UPDATE }
// allow writes on the hot path to bypass the record transition
// and be written directly to cache and storage
for (let i = 0; i < this.config.record.storageHotPathPrefixes.length; i++) {
const pattern = this.config.record.storageHotPathPrefixes[i]
if (recordName.indexOf(pattern) === 0) {
if (isPatch) {
const errorMessage = {
topic: TOPIC.RECORD,
action: RA.INVALID_PATCH_ON_HOTPATH,
originalAction,
name: recordName
} as RecordMessage
if (message.correlationId) {
errorMessage.correlationId = message.correlationId
}
socketWrapper.sendMessage(errorMessage)
return
}
this.permissionAction(RA.CREATE, message, originalAction, socketWrapper, () => {
this.permissionAction(RA.UPDATE, message, originalAction, socketWrapper, () => {
this.forceWrite(recordName, message, socketWrapper)
})
})
return
}
}
const transition = this.transitions.get(recordName)
if (transition) {
this.permissionAction(message.action, message, originalAction, socketWrapper, () => {
transition.add(socketWrapper, message)
})
return
}
this.permissionAction(RA.CREATE, message, originalAction, socketWrapper, () => {
this.permissionAction(RA.UPDATE, message, originalAction, socketWrapper, () => {
this.update(socketWrapper, message, true)
})
})
}
/**
* Forcibly writes to the cache and storage layers without going via
* the RecordTransition. Usually updates and patches will go via the
* transition which handles write acknowledgements, however in the
* case of a hot path write acknowledgement we need to handle that
* case here.
*/
private forceWrite (recordName: string, message: RecordWriteMessage, socketWrapper: SocketWrapper): void {
socketWrapper.parseData(message)
const writeAck = message.isWriteAck
let cacheResponse = false
let storageResponse = false
let writeError: string | null
this.services.storage.set(recordName, 0, message.parsedData, (error) => {
if (writeAck) {
storageResponse = true
writeError = writeError || error || null
this.handleForceWriteAcknowledgement(
socketWrapper, message, cacheResponse, storageResponse, writeError,
)
}
}, this.metaData)
this.services.cache.set(recordName, 0, message.parsedData, (error) => {
if (!error) {
this.broadcastUpdate(recordName, message, false, socketWrapper)
}
if (writeAck) {
cacheResponse = true
writeError = writeError || error || null
this.handleForceWriteAcknowledgement(
socketWrapper, message, cacheResponse, storageResponse, writeError,
)
}
}, this.metaData)
}
/**
* Handles write acknowledgements during a force write. Usually
* this case is handled via the record transition.
*/
public handleForceWriteAcknowledgement (
socketWrapper: SocketWrapper, message: RecordWriteMessage, cacheResponse: boolean, storageResponse: boolean, error: Error | string | null,
): void {
if (storageResponse && cacheResponse) {
socketWrapper.sendMessage({
topic: TOPIC.RECORD,
action: RA.WRITE_ACKNOWLEDGEMENT,
name: message.name,
correlationId: message.correlationId
}, true)
}
}
/**
* Creates a new, empty record and triggers a read operation once done
*/
private create (socketWrapper: SocketWrapper, message: RecordMessage, originalAction: RECORD_ACTION): void {
const recordName = message.name
// store the records data in the cache and wait for the result
this.services.cache.set(recordName, 0, {}, (error) => {
if (error) {
this.services.logger.error(RA[RA.RECORD_CREATE_ERROR], recordName, this.metaData)
socketWrapper.sendMessage({
topic: TOPIC.RECORD,
action: RA.RECORD_CREATE_ERROR,
originalAction,
name: message.name
})
return
}
// this isn't really needed, can subscribe and send empty data immediately
this.readAndSubscribe({ ...message, action: originalAction }, 0, {}, socketWrapper)
}, this.metaData)
if (!isExcluded(this.config.record.storageExclusionPrefixes, message.name)) {
// store the record data in the persistant storage independently and don't wait for the result
this.services.storage.set(recordName, 0, {}, (error) => {
if (error) {
this.services.logger.error(RA[RA.RECORD_CREATE_ERROR], `storage:${error}`, this.metaData)
}
}, this.metaData)
}
}
/**
* Subscribes to updates for a record and sends its current data once done
*/
private readAndSubscribe (message: RecordMessage, version: number, data: any, socketWrapper: SocketWrapper): void {
this.permissionAction(RA.READ, message, message.action, socketWrapper, () => {
this.subscriptionRegistry.subscribe(message.name, { ...message, action: RA.SUBSCRIBE }, socketWrapper, message.names !== undefined)
this.recordRequest(message.name, socketWrapper, (_: string, newVersion: number, latestData: any) => {
if (latestData) {
if (newVersion !== version) {
this.services.logger.info(
EVENT.INFO, `BUG CAUGHT! ${message.name} was version ${version} for readAndSubscribe, ` +
`but updated during permission to ${message.version}`
)
}
sendRecord(message.name, version, latestData, socketWrapper)
} else {
this.services.logger.error(
EVENT.ERROR,
`BUG? ${message.name} was version ${version} for readAndSubscribe, ` +
'but was removed during permission check',
{ message }
)
onRequestError(
message.action, `"${message.name}" was removed during permission check`,
message.name, socketWrapper, message
)
}
}, onRequestError, message)
})
}
/**
* Applies both full and partial updates. Creates a new record transition that will live as
* long as updates are in flight and new updates come in
*/
private update (socketWrapper: SocketWrapper | null, message: RecordWriteMessage, upsert: boolean): void {
const recordName = message.name
const version = message.version
/*
* If the update message is received from the message bus, rather than from a client,
* assume that the original deepstream node has already updated the record in cache and
* storage and only broadcast the message to subscribers
*/
if (socketWrapper === null) {
this.broadcastUpdate(recordName, message, false, socketWrapper)
return
}
const isPatch = message.path !== undefined
message = { ...message, action: isPatch ? RA.PATCH : RA.UPDATE }
let transition = this.transitions.get(recordName)
if (transition && transition.hasVersion(version)) {
transition.sendVersionExists({ message, sender: socketWrapper })
return
}
if (!transition) {
transition = new RecordTransition(recordName, this.config, this.services, this, this.metaData)
this.transitions.set(recordName, transition)
}
transition.add(socketWrapper, message, upsert)
}
/**
* Invoked by RecordTransition. Notifies local subscribers and other deepstream
* instances of record updates
*/
public broadcastUpdate (name: string, message: RecordMessage, noDelay: boolean, originalSender: SocketWrapper | null): void {
this.subscriptionRegistry.sendToSubscribers(name, message, noDelay, originalSender)
}
/**
* Called by a RecordTransition, either if it is complete or if an error occured. Removes
* the transition from the registry
*/
public transitionComplete (recordName: string): void {
this.transitions.delete(recordName)
}
/**
* Executes or schedules a callback function once all transitions are complete
*
* This is called from the PermissionHandler destroy method, which
* could occur in cases where 'runWhenRecordStable' is never called,
* such as when no cross referencing or data loading is used.
*/
public removeRecordRequest (recordName: string): void {
const recordRequests = this.recordRequestsInProgress.get(recordName)
if (!recordRequests) {
return
}
if (recordRequests.length === 0) {
this.recordRequestsInProgress.delete(recordName)
return
}
const callback = recordRequests.splice(0, 1)[0]
callback(recordName)
}
/**
* Executes or schedules a callback function once all record requests are removed.
* This is critical to block reads until writes have occured for a record, which is
* only from permissions when a rule is required to be run and the cache has not
* verified it has the latest version
*/
public runWhenRecordStable (recordName: string, callback: Function): void {
const recordRequests = this.recordRequestsInProgress.get(recordName)
if (!recordRequests || recordRequests.length === 0) {
this.recordRequestsInProgress.set(recordName, [])
callback(recordName)
} else {
recordRequests.push(callback)
}
}
/**
* Deletes a record. If a transition is in progress it will be stopped. Once the deletion is
* complete, an ACK is returned to the sender and broadcast to the message bus.
*/
private delete (socketWrapper: SocketWrapper, message: RecordMessage) {
const recordName = message.name
const transition = this.transitions.get(recordName)
if (transition) {
transition.destroy()
this.transitions.delete(recordName)
}
// tslint:disable-next-line
new RecordDeletion(this.config, this.services, socketWrapper, message, this.onDeleted, this.metaData)
}
/**
* Handle a remote record deletion from the message bus. We assume that the original deepstream node
* has already deleted the record from cache and storage and we only need to broadcast the message
* to subscribers.
*
* If a transition is in progress it will be stopped.
*/
private remoteDelete (message: RecordMessage) {
const recordName = message.name
const transition = this.transitions.get(recordName)
if (transition) {
transition.destroy()
this.transitions.delete(recordName)
}
this.onDeleted(recordName, message, null)
}
/*
* Callback for completed deletions. Notifies subscribers of the delete and unsubscribes them
*/
private onDeleted (name: string, message: RecordMessage, originalSender: SocketWrapper | null) {
this.broadcastUpdate(name, message, true, originalSender)
for (const subscriber of this.subscriptionRegistry.getLocalSubscribers(name)) {
this.subscriptionRegistry.unsubscribe(name, message, subscriber, true)
}
}
/**
* A secondary permissioning step that is performed once we know if the record exists (READ)
* or if it should be created (CREATE)
*/
private permissionAction (actionToPermission: RA, message: Message, originalAction: RA, socketWrapper: SocketWrapper, successCallback: Function) {
const copyWithAction = {...message, action: actionToPermission }
this.services.permission.canPerformAction(
socketWrapper,
copyWithAction,
this.onPermissionResponse,
{ originalAction, successCallback }
)
}
/*
* Callback for complete permissions. Important to note that only compound operations like
* CREATE_AND_UPDATE will end up here.
*/
private onPermissionResponse (
socketWrapper: SocketWrapper, message: Message, { originalAction, successCallback }: { originalAction: RA, successCallback: Function }, error: string | Error | ALL_ACTIONS | null, canPerformAction: boolean,
): void {
if (error || !canPerformAction) {
let action
if (error) {
this.services.logger.error(RA[RA.MESSAGE_PERMISSION_ERROR], error.toString())
action = RA.MESSAGE_PERMISSION_ERROR
} else {
action = RA.MESSAGE_DENIED
}
const msg = {
topic: TOPIC.RECORD,
action,
originalAction,
name: message.name,
isError: true
} as RecordMessage
if (message.correlationId) {
msg.correlationId = message.correlationId
}
if (message.isWriteAck) {
msg.isWriteAck = true
}
socketWrapper.sendMessage(msg)
} else {
successCallback(socketWrapper, message, originalAction)
}
}
}
function onRequestError (event: RA, errorMessage: string, recordName: string, socket: SocketWrapper, message: Message) {
const msg = {
topic: TOPIC.RECORD,
action: event,
originalAction: message.action,
name: recordName,
isError: true,
} as Message
if (message.isWriteAck) {
msg.isWriteAck = true
}
socket.sendMessage(msg)
}
function onSnapshotComplete (recordName: string, version: number, data: JSONObject, socket: SocketWrapper, message: Message) {
if (data) {
sendRecord(recordName, version, data, socket)
} else {
socket.sendMessage({
topic: TOPIC.RECORD,
action: RA.RECORD_NOT_FOUND,
originalAction: message.action,
name: message.name,
isError: true
})
}
}
function onHeadComplete (name: string, version: number, data: never, socketWrapper: SocketWrapper) {
socketWrapper.sendMessage({
topic: TOPIC.RECORD,
action: RA.HEAD_RESPONSE,
name,
version
})
}
/**
* Sends the records data current data once done
*/
function sendRecord (recordName: string, version: number, data: any, socketWrapper: SocketWrapper) {
socketWrapper.sendMessage({
topic: TOPIC.RECORD,
action: RA.READ_RESPONSE,
name: recordName,
version,
parsedData: data,
})
} | the_stack |
* github-sls-rest-api
* To generate a JWT token, go to the <a href=\"https://sso.saml.to/auth/jwt.html\" target=\"_blank\">JWT Token Generator</a>
*
* The version of the OpenAPI document: 1.0.51-0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Configuration } from './configuration';
import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios';
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base';
/**
*
* @export
* @interface GithubSlsRestApiAssumeBrowserResponse
*/
export interface GithubSlsRestApiAssumeBrowserResponse {
/**
*
* @type {string}
* @memberof GithubSlsRestApiAssumeBrowserResponse
*/
'browserUri': string;
}
/**
*
* @export
* @interface GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1
*/
export interface GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1 {
/**
*
* @type {GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1VersionEnum}
* @memberof GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1
*/
'version': GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1VersionEnum;
/**
*
* @type {GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1TypeEnum}
* @memberof GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1
*/
'type': GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1TypeEnum;
/**
*
* @type {boolean}
* @memberof GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1
*/
'deleted'?: boolean;
/**
*
* @type {string}
* @memberof GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1
*/
'token'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1
*/
'email'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1
*/
'login': string;
}
/**
*
* @export
* @enum {string}
*/
export enum GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1TypeEnum {
GithubLoginTokenEvent = 'GithubLoginTokenEvent'
}
/**
*
* @export
* @enum {string}
*/
export enum GithubSlsRestApiAuthSlsRestApiGithubLoginTokenEventV1VersionEnum {
NUMBER_1 = 1
}
/**
*
* @export
* @interface GithubSlsRestApiAwsAssumeSdkOptions
*/
export interface GithubSlsRestApiAwsAssumeSdkOptions {
/**
*
* @type {number}
* @memberof GithubSlsRestApiAwsAssumeSdkOptions
*/
'DurationSeconds': number;
/**
*
* @type {string}
* @memberof GithubSlsRestApiAwsAssumeSdkOptions
*/
'RoleArn': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiAwsAssumeSdkOptions
*/
'PrincipalArn': string;
}
/**
*
* @export
* @interface GithubSlsRestApiConfigBaseSupportedVersions
*/
export interface GithubSlsRestApiConfigBaseSupportedVersions {
/**
*
* @type {string}
* @memberof GithubSlsRestApiConfigBaseSupportedVersions
*/
'repo'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiConfigBaseSupportedVersions
*/
'org'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiConfigBaseSupportedVersions
*/
'ref'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiConfigBaseSupportedVersions
*/
'sha'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiConfigBaseSupportedVersions
*/
'path'?: string;
/**
*
* @type {GithubSlsRestApiSupportedVersions}
* @memberof GithubSlsRestApiConfigBaseSupportedVersions
*/
'version': GithubSlsRestApiSupportedVersions;
}
/**
*
* @export
* @interface GithubSlsRestApiConfigV20220101
*/
export interface GithubSlsRestApiConfigV20220101 {
/**
*
* @type {string}
* @memberof GithubSlsRestApiConfigV20220101
*/
'repo'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiConfigV20220101
*/
'org'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiConfigV20220101
*/
'ref'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiConfigV20220101
*/
'sha'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiConfigV20220101
*/
'path'?: string;
/**
*
* @type {GithubSlsRestApiSupportedVersions}
* @memberof GithubSlsRestApiConfigV20220101
*/
'version': GithubSlsRestApiSupportedVersions;
/**
*
* @type {{ [key: string]: GithubSlsRestApiPermissionV1; }}
* @memberof GithubSlsRestApiConfigV20220101
*/
'permissions'?: { [key: string]: GithubSlsRestApiPermissionV1; };
/**
*
* @type {{ [key: string]: GithubSlsRestApiProviderV1; }}
* @memberof GithubSlsRestApiConfigV20220101
*/
'providers'?: { [key: string]: GithubSlsRestApiProviderV1; };
/**
*
* @type {{ [key: string]: GithubSlsRestApiVariableV1; }}
* @memberof GithubSlsRestApiConfigV20220101
*/
'variables'?: { [key: string]: GithubSlsRestApiVariableV1; };
}
/**
*
* @export
* @interface GithubSlsRestApiConfigV20220101AllOf
*/
export interface GithubSlsRestApiConfigV20220101AllOf {
/**
*
* @type {{ [key: string]: GithubSlsRestApiPermissionV1; }}
* @memberof GithubSlsRestApiConfigV20220101AllOf
*/
'permissions'?: { [key: string]: GithubSlsRestApiPermissionV1; };
/**
*
* @type {{ [key: string]: GithubSlsRestApiProviderV1; }}
* @memberof GithubSlsRestApiConfigV20220101AllOf
*/
'providers'?: { [key: string]: GithubSlsRestApiProviderV1; };
/**
*
* @type {{ [key: string]: GithubSlsRestApiVariableV1; }}
* @memberof GithubSlsRestApiConfigV20220101AllOf
*/
'variables'?: { [key: string]: GithubSlsRestApiVariableV1; };
}
/**
*
* @export
* @interface GithubSlsRestApiEncryptRequest
*/
export interface GithubSlsRestApiEncryptRequest {
/**
*
* @type {string}
* @memberof GithubSlsRestApiEncryptRequest
*/
'value': string;
}
/**
*
* @export
* @interface GithubSlsRestApiEncryptResponse
*/
export interface GithubSlsRestApiEncryptResponse {
/**
*
* @type {string}
* @memberof GithubSlsRestApiEncryptResponse
*/
'encryptedValue': string;
}
/**
* This file was automatically generated by joi-to-typescript Do not modify this file manually
* @export
* @interface GithubSlsRestApiEncryptedField
*/
export interface GithubSlsRestApiEncryptedField {
/**
*
* @type {string}
* @memberof GithubSlsRestApiEncryptedField
*/
'encryptedValue': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiEncryptedField
*/
'keyId': string;
}
/**
*
* @export
* @interface GithubSlsRestApiErrorResponse
*/
export interface GithubSlsRestApiErrorResponse {
/**
*
* @type {string}
* @memberof GithubSlsRestApiErrorResponse
*/
'message': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiErrorResponse
*/
'traceId': string;
/**
*
* @type {GithubSlsRestApiErrorResponseTracking}
* @memberof GithubSlsRestApiErrorResponse
*/
'tracking': GithubSlsRestApiErrorResponseTracking;
/**
*
* @type {{ [key: string]: any; }}
* @memberof GithubSlsRestApiErrorResponse
*/
'context'?: { [key: string]: any; };
}
/**
*
* @export
* @interface GithubSlsRestApiErrorResponseTracking
*/
export interface GithubSlsRestApiErrorResponseTracking {
/**
*
* @type {string}
* @memberof GithubSlsRestApiErrorResponseTracking
*/
'method': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiErrorResponseTracking
*/
'path': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiErrorResponseTracking
*/
'version': string;
}
/**
*
* @export
* @interface GithubSlsRestApiGithubUserResponse
*/
export interface GithubSlsRestApiGithubUserResponse {
/**
*
* @type {string}
* @memberof GithubSlsRestApiGithubUserResponse
*/
'login': string;
}
/**
*
* @export
* @interface GithubSlsRestApiHealthResponse
*/
export interface GithubSlsRestApiHealthResponse {
/**
*
* @type {string}
* @memberof GithubSlsRestApiHealthResponse
*/
'version': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiHealthResponse
*/
'now': string;
/**
*
* @type {boolean}
* @memberof GithubSlsRestApiHealthResponse
*/
'healty': boolean;
/**
*
* @type {string}
* @memberof GithubSlsRestApiHealthResponse
*/
'name': string;
}
/**
*
* @export
* @interface GithubSlsRestApiListResponseLoginResponse
*/
export interface GithubSlsRestApiListResponseLoginResponse {
/**
*
* @type {GithubSlsRestApiListResponseOrgRepoResponseNext}
* @memberof GithubSlsRestApiListResponseLoginResponse
*/
'next'?: GithubSlsRestApiListResponseOrgRepoResponseNext;
/**
*
* @type {number}
* @memberof GithubSlsRestApiListResponseLoginResponse
*/
'total': number;
/**
*
* @type {number}
* @memberof GithubSlsRestApiListResponseLoginResponse
*/
'count': number;
/**
*
* @type {Array<GithubSlsRestApiLoginResponse>}
* @memberof GithubSlsRestApiListResponseLoginResponse
*/
'results': Array<GithubSlsRestApiLoginResponse>;
}
/**
*
* @export
* @interface GithubSlsRestApiListResponseOrgRepoResponse
*/
export interface GithubSlsRestApiListResponseOrgRepoResponse {
/**
*
* @type {GithubSlsRestApiListResponseOrgRepoResponseNext}
* @memberof GithubSlsRestApiListResponseOrgRepoResponse
*/
'next'?: GithubSlsRestApiListResponseOrgRepoResponseNext;
/**
*
* @type {number}
* @memberof GithubSlsRestApiListResponseOrgRepoResponse
*/
'total': number;
/**
*
* @type {number}
* @memberof GithubSlsRestApiListResponseOrgRepoResponse
*/
'count': number;
/**
*
* @type {Array<GithubSlsRestApiOrgRepoResponse>}
* @memberof GithubSlsRestApiListResponseOrgRepoResponse
*/
'results': Array<GithubSlsRestApiOrgRepoResponse>;
}
/**
*
* @export
* @interface GithubSlsRestApiListResponseOrgRepoResponseNext
*/
export interface GithubSlsRestApiListResponseOrgRepoResponseNext {
/**
*
* @type {string}
* @memberof GithubSlsRestApiListResponseOrgRepoResponseNext
*/
'sk': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiListResponseOrgRepoResponseNext
*/
'pk': string;
}
/**
*
* @export
* @interface GithubSlsRestApiListResponseRoleResponse
*/
export interface GithubSlsRestApiListResponseRoleResponse {
/**
*
* @type {GithubSlsRestApiListResponseOrgRepoResponseNext}
* @memberof GithubSlsRestApiListResponseRoleResponse
*/
'next'?: GithubSlsRestApiListResponseOrgRepoResponseNext;
/**
*
* @type {number}
* @memberof GithubSlsRestApiListResponseRoleResponse
*/
'total': number;
/**
*
* @type {number}
* @memberof GithubSlsRestApiListResponseRoleResponse
*/
'count': number;
/**
*
* @type {Array<GithubSlsRestApiRoleResponse>}
* @memberof GithubSlsRestApiListResponseRoleResponse
*/
'results': Array<GithubSlsRestApiRoleResponse>;
}
/**
*
* @export
* @interface GithubSlsRestApiLoginResponse
*/
export interface GithubSlsRestApiLoginResponse {
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginResponse
*/
'issuer': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginResponse
*/
'provider': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginResponse
*/
'repo': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginResponse
*/
'org': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginResponse
*/
'login': string;
}
/**
*
* @export
* @interface GithubSlsRestApiLoginResponseContainer
*/
export interface GithubSlsRestApiLoginResponseContainer {
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginResponseContainer
*/
'browserUri': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginResponseContainer
*/
'provider': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginResponseContainer
*/
'repo': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginResponseContainer
*/
'org': string;
}
/**
*
* @export
* @interface GithubSlsRestApiLoginToken
*/
export interface GithubSlsRestApiLoginToken {
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginToken
*/
'email'?: string;
/**
*
* @type {GithubSlsRestApiEncryptedField}
* @memberof GithubSlsRestApiLoginToken
*/
'encryptedToken': GithubSlsRestApiEncryptedField;
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginToken
*/
'login': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginToken
*/
'namespace': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginToken
*/
'pk': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginToken
*/
'scopes'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiLoginToken
*/
'sk': string;
}
/**
*
* @export
* @interface GithubSlsRestApiMetadataResponse
*/
export interface GithubSlsRestApiMetadataResponse {
/**
*
* @type {Array<GithubSlsRestApiGithubUserResponse>}
* @memberof GithubSlsRestApiMetadataResponse
*/
'admins': Array<GithubSlsRestApiGithubUserResponse>;
/**
*
* @type {string}
* @memberof GithubSlsRestApiMetadataResponse
*/
'certificate': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiMetadataResponse
*/
'logoutUrl': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiMetadataResponse
*/
'loginUrl': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiMetadataResponse
*/
'entityId': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiMetadataResponse
*/
'metadataXml': string;
}
/**
*
* @export
* @enum {string}
*/
export enum GithubSlsRestApiNameIdFormatV1 {
Id = 'id',
Login = 'login',
Email = 'email',
EmailV2 = 'emailV2'
}
/**
* This file was automatically generated by joi-to-typescript Do not modify this file manually
* @export
* @interface GithubSlsRestApiOrgRepo
*/
export interface GithubSlsRestApiOrgRepo {
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepo
*/
'baseUrl': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepo
*/
'configSha'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepo
*/
'org': string;
/**
*
* @type {number}
* @memberof GithubSlsRestApiOrgRepo
*/
'orgId': number;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepo
*/
'pk': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepo
*/
'repo': string;
/**
*
* @type {number}
* @memberof GithubSlsRestApiOrgRepo
*/
'repoId': number;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepo
*/
'sk': string;
}
/**
*
* @export
* @interface GithubSlsRestApiOrgRepoConfigRefreshResponse
*/
export interface GithubSlsRestApiOrgRepoConfigRefreshResponse {
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoConfigRefreshResponse
*/
'repo': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoConfigRefreshResponse
*/
'org': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoConfigRefreshResponse
*/
'branch'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoConfigRefreshResponse
*/
'path'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoConfigRefreshResponse
*/
'sha'?: string;
/**
*
* @type {boolean}
* @memberof GithubSlsRestApiOrgRepoConfigRefreshResponse
*/
'dryrun': boolean;
/**
*
* @type {GithubSlsRestApiConfigV20220101}
* @memberof GithubSlsRestApiOrgRepoConfigRefreshResponse
*/
'config': GithubSlsRestApiConfigV20220101;
}
/**
*
* @export
* @interface GithubSlsRestApiOrgRepoConfigRefreshResponseAllOf
*/
export interface GithubSlsRestApiOrgRepoConfigRefreshResponseAllOf {
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoConfigRefreshResponseAllOf
*/
'branch'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoConfigRefreshResponseAllOf
*/
'path'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoConfigRefreshResponseAllOf
*/
'sha'?: string;
/**
*
* @type {boolean}
* @memberof GithubSlsRestApiOrgRepoConfigRefreshResponseAllOf
*/
'dryrun': boolean;
/**
*
* @type {GithubSlsRestApiConfigV20220101}
* @memberof GithubSlsRestApiOrgRepoConfigRefreshResponseAllOf
*/
'config': GithubSlsRestApiConfigV20220101;
}
/**
* This file was automatically generated by joi-to-typescript Do not modify this file manually
* @export
* @interface GithubSlsRestApiOrgRepoLogin
*/
export interface GithubSlsRestApiOrgRepoLogin {
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoLogin
*/
'login': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoLogin
*/
'org': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoLogin
*/
'pk': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoLogin
*/
'repo': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoLogin
*/
'sk': string;
}
/**
*
* @export
* @interface GithubSlsRestApiOrgRepoResponse
*/
export interface GithubSlsRestApiOrgRepoResponse {
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoResponse
*/
'repo': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiOrgRepoResponse
*/
'org': string;
}
/**
*
* @export
* @interface GithubSlsRestApiPermissionV1
*/
export interface GithubSlsRestApiPermissionV1 {
/**
*
* @type {boolean}
* @memberof GithubSlsRestApiPermissionV1
*/
'self'?: boolean;
/**
*
* @type {Array<GithubSlsRestApiRolesV1>}
* @memberof GithubSlsRestApiPermissionV1
*/
'roles'?: Array<GithubSlsRestApiRolesV1>;
/**
*
* @type {GithubSlsRestApiReposV1}
* @memberof GithubSlsRestApiPermissionV1
*/
'repos'?: GithubSlsRestApiReposV1;
/**
*
* @type {GithubSlsRestApiUsersV1}
* @memberof GithubSlsRestApiPermissionV1
*/
'users'?: GithubSlsRestApiUsersV1;
}
/**
*
* @export
* @interface GithubSlsRestApiProviderV1
*/
export interface GithubSlsRestApiProviderV1 {
/**
*
* @type {GithubSlsRestApiProvisioningV1}
* @memberof GithubSlsRestApiProviderV1
*/
'provisioning'?: GithubSlsRestApiProvisioningV1;
/**
*
* @type {{ [key: string]: string; }}
* @memberof GithubSlsRestApiProviderV1
*/
'attributes'?: { [key: string]: string; };
/**
*
* @type {GithubSlsRestApiNameIdFormatV1}
* @memberof GithubSlsRestApiProviderV1
*/
'nameIdFormat'?: GithubSlsRestApiNameIdFormatV1;
/**
*
* @type {string}
* @memberof GithubSlsRestApiProviderV1
*/
'nameId'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiProviderV1
*/
'loginUrl'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiProviderV1
*/
'acsUrl'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiProviderV1
*/
'entityId'?: string;
}
/**
*
* @export
* @interface GithubSlsRestApiProvisioningV1
*/
export interface GithubSlsRestApiProvisioningV1 {
/**
*
* @type {GithubSlsRestApiScimV1}
* @memberof GithubSlsRestApiProvisioningV1
*/
'scim'?: GithubSlsRestApiScimV1;
}
/**
*
* @export
* @interface GithubSlsRestApiRepoV1
*/
export interface GithubSlsRestApiRepoV1 {
/**
*
* @type {string}
* @memberof GithubSlsRestApiRepoV1
*/
'name'?: string;
}
/**
*
* @export
* @interface GithubSlsRestApiReposV1
*/
export interface GithubSlsRestApiReposV1 {
/**
*
* @type {Array<GithubSlsRestApiRepoV1>}
* @memberof GithubSlsRestApiReposV1
*/
'github'?: Array<GithubSlsRestApiRepoV1>;
}
/**
*
* @export
* @interface GithubSlsRestApiRoleResponse
*/
export interface GithubSlsRestApiRoleResponse {
/**
*
* @type {string}
* @memberof GithubSlsRestApiRoleResponse
*/
'issuer': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiRoleResponse
*/
'role': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiRoleResponse
*/
'provider': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiRoleResponse
*/
'repo': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiRoleResponse
*/
'org': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiRoleResponse
*/
'login': string;
}
/**
*
* @export
* @interface GithubSlsRestApiRolesV1
*/
export interface GithubSlsRestApiRolesV1 {
/**
*
* @type {boolean}
* @memberof GithubSlsRestApiRolesV1
*/
'self'?: boolean;
/**
*
* @type {GithubSlsRestApiReposV1}
* @memberof GithubSlsRestApiRolesV1
*/
'repos'?: GithubSlsRestApiReposV1;
/**
*
* @type {GithubSlsRestApiUsersV1}
* @memberof GithubSlsRestApiRolesV1
*/
'users'?: GithubSlsRestApiUsersV1;
/**
*
* @type {string}
* @memberof GithubSlsRestApiRolesV1
*/
'name'?: string;
}
/**
*
* @export
* @interface GithubSlsRestApiSamlResponseContainer
*/
export interface GithubSlsRestApiSamlResponseContainer {
/**
*
* @type {GithubSlsRestApiAwsAssumeSdkOptions}
* @memberof GithubSlsRestApiSamlResponseContainer
*/
'sdkOptions'?: GithubSlsRestApiAwsAssumeSdkOptions;
/**
*
* @type {string}
* @memberof GithubSlsRestApiSamlResponseContainer
*/
'browserUri'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiSamlResponseContainer
*/
'role'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiSamlResponseContainer
*/
'provider': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiSamlResponseContainer
*/
'repo': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiSamlResponseContainer
*/
'org': string;
/**
*
* @type {{ [key: string]: string; }}
* @memberof GithubSlsRestApiSamlResponseContainer
*/
'attributes'?: { [key: string]: string; };
/**
*
* @type {string}
* @memberof GithubSlsRestApiSamlResponseContainer
*/
'samlResponse': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiSamlResponseContainer
*/
'relayState': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiSamlResponseContainer
*/
'recipient': string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiSamlResponseContainer
*/
'issuer': string;
}
/**
*
* @export
* @interface GithubSlsRestApiScimV1
*/
export interface GithubSlsRestApiScimV1 {
/**
*
* @type {string}
* @memberof GithubSlsRestApiScimV1
*/
'encryptedToken'?: string;
/**
*
* @type {string}
* @memberof GithubSlsRestApiScimV1
*/
'endpoint'?: string;
}
/**
*
* @export
* @enum {string}
*/
export enum GithubSlsRestApiSupportedVersions {
_20220101 = '20220101'
}
/**
*
* @export
* @interface GithubSlsRestApiUsersV1
*/
export interface GithubSlsRestApiUsersV1 {
/**
*
* @type {Array<string>}
* @memberof GithubSlsRestApiUsersV1
*/
'github'?: Array<string>;
}
/**
*
* @export
* @interface GithubSlsRestApiVariableV1
*/
export interface GithubSlsRestApiVariableV1 {
}
/**
* HealthApi - axios parameter creator
* @export
*/
export const HealthApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
get: async (options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/api/health`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* HealthApi - functional programming interface
* @export
*/
export const HealthApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = HealthApiAxiosParamCreator(configuration)
return {
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async get(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GithubSlsRestApiHealthResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.get(options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* HealthApi - factory interface
* @export
*/
export const HealthApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = HealthApiFp(configuration)
return {
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
get(options?: any): AxiosPromise<GithubSlsRestApiHealthResponse> {
return localVarFp.get(options).then((request) => request(axios, basePath));
},
};
};
/**
* HealthApi - object-oriented interface
* @export
* @class HealthApi
* @extends {BaseAPI}
*/
export class HealthApi extends BaseAPI {
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof HealthApi
*/
public get(options?: AxiosRequestConfig) {
return HealthApiFp(this.configuration).get(options).then((request) => request(this.axios, this.basePath));
}
}
/**
* IDPApi - axios parameter creator
* @export
*/
export const IDPApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @param {string} role
* @param {string} [org]
* @param {string} [provider]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
assumeRole: async (role: string, org?: string, provider?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'role' is not null or undefined
assertParamExists('assumeRole', 'role', role)
const localVarPath = `/api/v1/idp/roles/{role}/assume`
.replace(`{${"role"}}`, encodeURIComponent(String(role)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication jwt required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (org !== undefined) {
localVarQueryParameter['org'] = org;
}
if (provider !== undefined) {
localVarQueryParameter['provider'] = provider;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {string} role
* @param {string} [org]
* @param {string} [provider]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
assumeRoleForBrowser: async (role: string, org?: string, provider?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'role' is not null or undefined
assertParamExists('assumeRoleForBrowser', 'role', role)
const localVarPath = `/api/v1/idp/roles/{role}/assume/browser`
.replace(`{${"role"}}`, encodeURIComponent(String(role)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (org !== undefined) {
localVarQueryParameter['org'] = org;
}
if (provider !== undefined) {
localVarQueryParameter['provider'] = provider;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {string} org
* @param {string} repo
* @param {string} role
* @param {string} [provider]
* @param {string} [commitSha]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
assumeRoleForRepo: async (org: string, repo: string, role: string, provider?: string, commitSha?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'org' is not null or undefined
assertParamExists('assumeRoleForRepo', 'org', org)
// verify required parameter 'repo' is not null or undefined
assertParamExists('assumeRoleForRepo', 'repo', repo)
// verify required parameter 'role' is not null or undefined
assertParamExists('assumeRoleForRepo', 'role', role)
const localVarPath = `/api/v1/idp/orgs/{org}/repos/{repo}/roles/{role}/assume`
.replace(`{${"org"}}`, encodeURIComponent(String(org)))
.replace(`{${"repo"}}`, encodeURIComponent(String(repo)))
.replace(`{${"role"}}`, encodeURIComponent(String(role)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication jwt required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (provider !== undefined) {
localVarQueryParameter['provider'] = provider;
}
if (commitSha !== undefined) {
localVarQueryParameter['commitSha'] = commitSha;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {string} org
* @param {GithubSlsRestApiEncryptRequest} githubSlsRestApiEncryptRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
encrypt: async (org: string, githubSlsRestApiEncryptRequest: GithubSlsRestApiEncryptRequest, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'org' is not null or undefined
assertParamExists('encrypt', 'org', org)
// verify required parameter 'githubSlsRestApiEncryptRequest' is not null or undefined
assertParamExists('encrypt', 'githubSlsRestApiEncryptRequest', githubSlsRestApiEncryptRequest)
const localVarPath = `/api/v1/idp/orgs/{org}/encrypt`
.replace(`{${"org"}}`, encodeURIComponent(String(org)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(githubSlsRestApiEncryptRequest, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {string} org
* @param {boolean} [raw]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getOrgConfig: async (org: string, raw?: boolean, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'org' is not null or undefined
assertParamExists('getOrgConfig', 'org', org)
const localVarPath = `/api/v1/idp/orgs/{org}/config`
.replace(`{${"org"}}`, encodeURIComponent(String(org)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication jwt required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (raw !== undefined) {
localVarQueryParameter['raw'] = raw;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {string} org
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getOrgMetadata: async (org: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'org' is not null or undefined
assertParamExists('getOrgMetadata', 'org', org)
const localVarPath = `/api/v1/idp/orgs/{org}/metadata`
.replace(`{${"org"}}`, encodeURIComponent(String(org)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {string} [org]
* @param {boolean} [refresh]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listLogins: async (org?: string, refresh?: boolean, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/api/v1/idp/logins`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication jwt required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (org !== undefined) {
localVarQueryParameter['org'] = org;
}
if (refresh !== undefined) {
localVarQueryParameter['refresh'] = refresh;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listOrgRepos: async (options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/api/v1/idp/orgs`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication jwt required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {string} [org]
* @param {string} [provider]
* @param {boolean} [refresh]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listRoles: async (org?: string, provider?: string, refresh?: boolean, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/api/v1/idp/roles`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication jwt required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (org !== undefined) {
localVarQueryParameter['org'] = org;
}
if (provider !== undefined) {
localVarQueryParameter['provider'] = provider;
}
if (refresh !== undefined) {
localVarQueryParameter['refresh'] = refresh;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {string} provider
* @param {string} [org]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
providerLogin: async (provider: string, org?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'provider' is not null or undefined
assertParamExists('providerLogin', 'provider', provider)
const localVarPath = `/api/v1/idp/logins/{provider}/login`
.replace(`{${"provider"}}`, encodeURIComponent(String(provider)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication jwt required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (org !== undefined) {
localVarQueryParameter['org'] = org;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {string} org
* @param {string} repo
* @param {boolean} [dryrun]
* @param {string} [commitSha]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
refreshOrgRepoConfig: async (org: string, repo: string, dryrun?: boolean, commitSha?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'org' is not null or undefined
assertParamExists('refreshOrgRepoConfig', 'org', org)
// verify required parameter 'repo' is not null or undefined
assertParamExists('refreshOrgRepoConfig', 'repo', repo)
const localVarPath = `/api/v1/idp/orgs/{org}/repos/{repo}/config`
.replace(`{${"org"}}`, encodeURIComponent(String(org)))
.replace(`{${"repo"}}`, encodeURIComponent(String(repo)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication jwt required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (dryrun !== undefined) {
localVarQueryParameter['dryrun'] = dryrun;
}
if (commitSha !== undefined) {
localVarQueryParameter['commitSha'] = commitSha;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {string} org
* @param {string} repo
* @param {boolean} [force]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
setOrgAndRepo: async (org: string, repo: string, force?: boolean, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'org' is not null or undefined
assertParamExists('setOrgAndRepo', 'org', org)
// verify required parameter 'repo' is not null or undefined
assertParamExists('setOrgAndRepo', 'repo', repo)
const localVarPath = `/api/v1/idp/orgs/{org}/repos/{repo}`
.replace(`{${"org"}}`, encodeURIComponent(String(org)))
.replace(`{${"repo"}}`, encodeURIComponent(String(repo)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication jwt required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (force !== undefined) {
localVarQueryParameter['force'] = force;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* IDPApi - functional programming interface
* @export
*/
export const IDPApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = IDPApiAxiosParamCreator(configuration)
return {
/**
*
* @param {string} role
* @param {string} [org]
* @param {string} [provider]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async assumeRole(role: string, org?: string, provider?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GithubSlsRestApiSamlResponseContainer>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.assumeRole(role, org, provider, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @param {string} role
* @param {string} [org]
* @param {string} [provider]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async assumeRoleForBrowser(role: string, org?: string, provider?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GithubSlsRestApiAssumeBrowserResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.assumeRoleForBrowser(role, org, provider, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @param {string} org
* @param {string} repo
* @param {string} role
* @param {string} [provider]
* @param {string} [commitSha]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async assumeRoleForRepo(org: string, repo: string, role: string, provider?: string, commitSha?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GithubSlsRestApiSamlResponseContainer>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.assumeRoleForRepo(org, repo, role, provider, commitSha, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @param {string} org
* @param {GithubSlsRestApiEncryptRequest} githubSlsRestApiEncryptRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async encrypt(org: string, githubSlsRestApiEncryptRequest: GithubSlsRestApiEncryptRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GithubSlsRestApiEncryptResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.encrypt(org, githubSlsRestApiEncryptRequest, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @param {string} org
* @param {boolean} [raw]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getOrgConfig(org: string, raw?: boolean, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GithubSlsRestApiConfigV20220101>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getOrgConfig(org, raw, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @param {string} org
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getOrgMetadata(org: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GithubSlsRestApiMetadataResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getOrgMetadata(org, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @param {string} [org]
* @param {boolean} [refresh]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listLogins(org?: string, refresh?: boolean, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GithubSlsRestApiListResponseLoginResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listLogins(org, refresh, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listOrgRepos(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GithubSlsRestApiListResponseOrgRepoResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listOrgRepos(options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @param {string} [org]
* @param {string} [provider]
* @param {boolean} [refresh]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listRoles(org?: string, provider?: string, refresh?: boolean, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GithubSlsRestApiListResponseRoleResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listRoles(org, provider, refresh, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @param {string} provider
* @param {string} [org]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async providerLogin(provider: string, org?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GithubSlsRestApiLoginResponseContainer>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.providerLogin(provider, org, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @param {string} org
* @param {string} repo
* @param {boolean} [dryrun]
* @param {string} [commitSha]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async refreshOrgRepoConfig(org: string, repo: string, dryrun?: boolean, commitSha?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GithubSlsRestApiOrgRepoConfigRefreshResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.refreshOrgRepoConfig(org, repo, dryrun, commitSha, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @param {string} org
* @param {string} repo
* @param {boolean} [force]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async setOrgAndRepo(org: string, repo: string, force?: boolean, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GithubSlsRestApiOrgRepoLogin>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.setOrgAndRepo(org, repo, force, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* IDPApi - factory interface
* @export
*/
export const IDPApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = IDPApiFp(configuration)
return {
/**
*
* @param {string} role
* @param {string} [org]
* @param {string} [provider]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
assumeRole(role: string, org?: string, provider?: string, options?: any): AxiosPromise<GithubSlsRestApiSamlResponseContainer> {
return localVarFp.assumeRole(role, org, provider, options).then((request) => request(axios, basePath));
},
/**
*
* @param {string} role
* @param {string} [org]
* @param {string} [provider]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
assumeRoleForBrowser(role: string, org?: string, provider?: string, options?: any): AxiosPromise<GithubSlsRestApiAssumeBrowserResponse> {
return localVarFp.assumeRoleForBrowser(role, org, provider, options).then((request) => request(axios, basePath));
},
/**
*
* @param {string} org
* @param {string} repo
* @param {string} role
* @param {string} [provider]
* @param {string} [commitSha]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
assumeRoleForRepo(org: string, repo: string, role: string, provider?: string, commitSha?: string, options?: any): AxiosPromise<GithubSlsRestApiSamlResponseContainer> {
return localVarFp.assumeRoleForRepo(org, repo, role, provider, commitSha, options).then((request) => request(axios, basePath));
},
/**
*
* @param {string} org
* @param {GithubSlsRestApiEncryptRequest} githubSlsRestApiEncryptRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
encrypt(org: string, githubSlsRestApiEncryptRequest: GithubSlsRestApiEncryptRequest, options?: any): AxiosPromise<GithubSlsRestApiEncryptResponse> {
return localVarFp.encrypt(org, githubSlsRestApiEncryptRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @param {string} org
* @param {boolean} [raw]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getOrgConfig(org: string, raw?: boolean, options?: any): AxiosPromise<GithubSlsRestApiConfigV20220101> {
return localVarFp.getOrgConfig(org, raw, options).then((request) => request(axios, basePath));
},
/**
*
* @param {string} org
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getOrgMetadata(org: string, options?: any): AxiosPromise<GithubSlsRestApiMetadataResponse> {
return localVarFp.getOrgMetadata(org, options).then((request) => request(axios, basePath));
},
/**
*
* @param {string} [org]
* @param {boolean} [refresh]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listLogins(org?: string, refresh?: boolean, options?: any): AxiosPromise<GithubSlsRestApiListResponseLoginResponse> {
return localVarFp.listLogins(org, refresh, options).then((request) => request(axios, basePath));
},
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listOrgRepos(options?: any): AxiosPromise<GithubSlsRestApiListResponseOrgRepoResponse> {
return localVarFp.listOrgRepos(options).then((request) => request(axios, basePath));
},
/**
*
* @param {string} [org]
* @param {string} [provider]
* @param {boolean} [refresh]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listRoles(org?: string, provider?: string, refresh?: boolean, options?: any): AxiosPromise<GithubSlsRestApiListResponseRoleResponse> {
return localVarFp.listRoles(org, provider, refresh, options).then((request) => request(axios, basePath));
},
/**
*
* @param {string} provider
* @param {string} [org]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
providerLogin(provider: string, org?: string, options?: any): AxiosPromise<GithubSlsRestApiLoginResponseContainer> {
return localVarFp.providerLogin(provider, org, options).then((request) => request(axios, basePath));
},
/**
*
* @param {string} org
* @param {string} repo
* @param {boolean} [dryrun]
* @param {string} [commitSha]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
refreshOrgRepoConfig(org: string, repo: string, dryrun?: boolean, commitSha?: string, options?: any): AxiosPromise<GithubSlsRestApiOrgRepoConfigRefreshResponse> {
return localVarFp.refreshOrgRepoConfig(org, repo, dryrun, commitSha, options).then((request) => request(axios, basePath));
},
/**
*
* @param {string} org
* @param {string} repo
* @param {boolean} [force]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
setOrgAndRepo(org: string, repo: string, force?: boolean, options?: any): AxiosPromise<GithubSlsRestApiOrgRepoLogin> {
return localVarFp.setOrgAndRepo(org, repo, force, options).then((request) => request(axios, basePath));
},
};
};
/**
* IDPApi - object-oriented interface
* @export
* @class IDPApi
* @extends {BaseAPI}
*/
export class IDPApi extends BaseAPI {
/**
*
* @param {string} role
* @param {string} [org]
* @param {string} [provider]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof IDPApi
*/
public assumeRole(role: string, org?: string, provider?: string, options?: AxiosRequestConfig) {
return IDPApiFp(this.configuration).assumeRole(role, org, provider, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} role
* @param {string} [org]
* @param {string} [provider]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof IDPApi
*/
public assumeRoleForBrowser(role: string, org?: string, provider?: string, options?: AxiosRequestConfig) {
return IDPApiFp(this.configuration).assumeRoleForBrowser(role, org, provider, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} org
* @param {string} repo
* @param {string} role
* @param {string} [provider]
* @param {string} [commitSha]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof IDPApi
*/
public assumeRoleForRepo(org: string, repo: string, role: string, provider?: string, commitSha?: string, options?: AxiosRequestConfig) {
return IDPApiFp(this.configuration).assumeRoleForRepo(org, repo, role, provider, commitSha, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} org
* @param {GithubSlsRestApiEncryptRequest} githubSlsRestApiEncryptRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof IDPApi
*/
public encrypt(org: string, githubSlsRestApiEncryptRequest: GithubSlsRestApiEncryptRequest, options?: AxiosRequestConfig) {
return IDPApiFp(this.configuration).encrypt(org, githubSlsRestApiEncryptRequest, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} org
* @param {boolean} [raw]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof IDPApi
*/
public getOrgConfig(org: string, raw?: boolean, options?: AxiosRequestConfig) {
return IDPApiFp(this.configuration).getOrgConfig(org, raw, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} org
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof IDPApi
*/
public getOrgMetadata(org: string, options?: AxiosRequestConfig) {
return IDPApiFp(this.configuration).getOrgMetadata(org, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} [org]
* @param {boolean} [refresh]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof IDPApi
*/
public listLogins(org?: string, refresh?: boolean, options?: AxiosRequestConfig) {
return IDPApiFp(this.configuration).listLogins(org, refresh, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof IDPApi
*/
public listOrgRepos(options?: AxiosRequestConfig) {
return IDPApiFp(this.configuration).listOrgRepos(options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} [org]
* @param {string} [provider]
* @param {boolean} [refresh]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof IDPApi
*/
public listRoles(org?: string, provider?: string, refresh?: boolean, options?: AxiosRequestConfig) {
return IDPApiFp(this.configuration).listRoles(org, provider, refresh, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} provider
* @param {string} [org]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof IDPApi
*/
public providerLogin(provider: string, org?: string, options?: AxiosRequestConfig) {
return IDPApiFp(this.configuration).providerLogin(provider, org, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} org
* @param {string} repo
* @param {boolean} [dryrun]
* @param {string} [commitSha]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof IDPApi
*/
public refreshOrgRepoConfig(org: string, repo: string, dryrun?: boolean, commitSha?: string, options?: AxiosRequestConfig) {
return IDPApiFp(this.configuration).refreshOrgRepoConfig(org, repo, dryrun, commitSha, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} org
* @param {string} repo
* @param {boolean} [force]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof IDPApi
*/
public setOrgAndRepo(org: string, repo: string, force?: boolean, options?: AxiosRequestConfig) {
return IDPApiFp(this.configuration).setOrgAndRepo(org, repo, force, options).then((request) => request(this.axios, this.basePath));
}
} | the_stack |
import { getMetaDataProperty } from '../../test/helper/get-meta-data-property.function'
import {
ComplexModel,
CustomTableNameModel,
DifferentModel,
IdMapper,
INDEX_ACTIVE,
INDEX_ACTIVE_CREATED_AT,
INDEX_COUNT,
ModelWithABunchOfIndexes,
ModelWithCustomMapperModel,
ModelWithEnum,
ModelWithGSI,
NestedObject,
SimpleModel,
} from '../../test/models'
import { Form } from '../../test/models/real-world'
import { updateDynamoEasyConfig } from '../config/update-config.function'
import { LogLevel } from '../logger/log-level.type'
import { CollectionProperty } from './impl/collection/collection-property.decorator'
import { GSIPartitionKey } from './impl/index/gsi-partition-key.decorator'
import { GSISortKey } from './impl/index/gsi-sort-key.decorator'
import { LSISortKey } from './impl/index/lsi-sort-key.decorator'
import { PartitionKey } from './impl/key/partition-key.decorator'
import { SortKey } from './impl/key/sort-key.decorator'
import { Model } from './impl/model/model.decorator'
import { Property } from './impl/property/property.decorator'
import { Transient } from './impl/transient/transient.decorator'
import { Metadata } from './metadata/metadata'
import { metadataForModel } from './metadata/metadata-for-model.function'
import { ModelMetadata } from './metadata/model-metadata.model'
describe('Decorators should add correct metadata', () => {
describe('Property() should allow to define a different Mapper', () => {
it('should define the mapper in metadata', () => {
const metaData = metadataForModel(ModelWithCustomMapperModel).modelOptions
expect(metaData).toBeDefined()
expect(metaData.clazz).toBe(ModelWithCustomMapperModel)
expect(metaData.properties).toBeDefined()
const idMeta = getMetaDataProperty(metaData, 'id')
expect(idMeta).toBeDefined()
expect(idMeta!.name).toBe('id')
expect(idMeta!.mapper).toBeDefined()
expect(idMeta!.mapper!()).toBe(IdMapper)
})
})
describe('for simple model', () => {
let modelOptions: ModelMetadata<SimpleModel>
beforeEach(() => {
modelOptions = metadataForModel(SimpleModel).modelOptions
})
it('with default table name', () => {
expect(modelOptions).toBeDefined()
expect(modelOptions.tableName).toBe('simple-models')
expect(modelOptions.clazz).toBe(SimpleModel)
expect(modelOptions.clazzName).toBe('SimpleModel')
})
it('with no properties', () => {
expect(modelOptions.properties).toEqual([])
})
})
describe('for custom table name', () => {
let modelOptions: ModelMetadata<CustomTableNameModel>
beforeEach(() => {
modelOptions = metadataForModel(CustomTableNameModel).modelOptions
})
it('with custom table name', () => {
expect(modelOptions).toBeDefined()
expect(modelOptions.tableName).toBe('myCustomName')
expect(modelOptions.clazz).toBe(CustomTableNameModel)
expect(modelOptions.clazzName).toBe('CustomTableNameModel')
})
})
describe('for complex model', () => {
let modelOptions: ModelMetadata<ComplexModel>
beforeEach(() => {
modelOptions = metadataForModel(ComplexModel).modelOptions
})
it('with default model metadata', () => {
expect(modelOptions.tableName).toBe('complex_model')
expect(modelOptions.clazz).toBe(ComplexModel)
expect(modelOptions.clazzName).toBe('ComplexModel')
})
it('with correct properties', () => {
expect(modelOptions.properties).toBeDefined()
expect(modelOptions.properties!.length).toBe(10)
})
it('with correct transient properties', () => {
expect(modelOptions.transientProperties).toBeDefined()
expect(modelOptions.transientProperties!.length).toBe(1)
})
describe('with correct property metadata', () => {
it('ids', () => {
const prop = getMetaDataProperty(modelOptions, 'id')
expect(prop).toBeDefined()
expect(prop!.name).toBe('id')
expect(prop!.nameDb).toBe('id')
expect(prop!.key).toBeDefined()
expect(prop!.key!.type).toBe('HASH')
expect(prop!.transient).toBeFalsy()
expect(prop!.typeInfo).toBeDefined()
expect(prop!.typeInfo!.type).toBe(String)
})
it('creationDate', () => {
const prop = getMetaDataProperty(modelOptions, 'creationDate')
expect(prop).toBeDefined()
expect(prop!.name).toBe('creationDate')
expect(prop!.nameDb).toBe('creationDate')
expect(prop!.key).toBeDefined()
expect(prop!.key!.type).toBe('RANGE')
expect(prop!.transient).toBeFalsy()
expect(prop!.typeInfo).toBeDefined()
})
it('active', () => {
const prop = getMetaDataProperty(modelOptions, 'active')
expect(prop).toBeDefined()
expect(prop!.name).toBe('active')
expect(prop!.nameDb).toBe('isActive')
expect(prop!.key).toBeUndefined()
expect(prop!.transient).toBeFalsy()
expect(prop!.typeInfo).toBeDefined()
expect(prop!.typeInfo!.type).toBe(Boolean)
})
it('set', () => {
const prop = getMetaDataProperty(modelOptions, 'set')
expect(prop).toBeDefined()
expect(prop!.name).toBe('set')
expect(prop!.nameDb).toBe('set')
expect(prop!.key).toBeUndefined()
expect(prop!.transient).toBeFalsy()
expect(prop!.typeInfo).toBeDefined()
expect(prop!.typeInfo!.type).toBe(Set)
})
it('sortedSet', () => {
const prop = getMetaDataProperty(modelOptions, 'sortedSet')
expect(prop).toBeDefined()
expect(prop!.name).toBe('sortedSet')
expect(prop!.nameDb).toBe('sortedSet')
expect(prop!.key).toBeUndefined()
expect(prop!.transient).toBeFalsy()
expect(prop!.isSortedCollection).toBeTruthy()
expect(prop!.typeInfo).toBeDefined()
expect(prop!.typeInfo!.type).toBe(Set)
})
it('sortedComplexSet', () => {
const prop = getMetaDataProperty(modelOptions, 'sortedComplexSet')
expect(prop).toBeDefined()
expect(prop!.name).toBe('sortedComplexSet')
expect(prop!.nameDb).toBe('sortedComplexSet')
expect(prop!.key).toBeUndefined()
expect(prop!.transient).toBeFalsy()
expect(prop!.isSortedCollection).toBeTruthy()
expect(prop!.typeInfo).toBeDefined()
expect(prop!.typeInfo!.type).toBe(Set)
expect(prop!.typeInfo!.genericType).toBeDefined()
expect(prop!.typeInfo!.genericType).toBe(NestedObject)
})
it('mapWithNoType', () => {
const prop = getMetaDataProperty(modelOptions, 'mapWithNoType')
expect(prop).toBeDefined()
expect(prop!.name).toBe('mapWithNoType')
expect(prop!.nameDb).toBe('mapWithNoType')
expect(prop!.key).toBeUndefined()
expect(prop!.transient).toBeFalsy()
expect(prop!.typeInfo).toBeDefined()
expect(prop!.typeInfo!.type).toBe(Map)
})
it('transientField', () => {
const prop = getMetaDataProperty(modelOptions, 'transientField')
expect(prop).toBeDefined()
expect(prop!.name).toBe('transientField')
expect(prop!.nameDb).toBe('transientField')
expect(prop!.key).toBeUndefined()
expect(prop!.transient).toBeTruthy()
expect(prop!.typeInfo).toBeDefined()
expect(prop!.typeInfo!.type).toBe(String)
})
it('simpleProperty', () => {
const prop = getMetaDataProperty(modelOptions, 'simpleProperty')
expect(prop).toBeUndefined()
})
it('nestedObject', () => {
const prop = getMetaDataProperty(modelOptions, 'nestedObj')
expect(prop).toBeDefined()
expect(prop!.name).toBe('nestedObj')
expect(prop!.nameDb).toBe('my_nested_object')
expect(prop!.key).toBeUndefined()
expect(prop!.transient).toBeFalsy()
expect(prop!.typeInfo).toBeDefined()
expect(prop!.typeInfo!.type).toBe(NestedObject)
})
})
})
describe('indexes', () => {
describe('simple index (partition key, no range key)', () => {
let metadata: Metadata<ModelWithGSI>
beforeEach(() => {
metadata = metadataForModel(ModelWithGSI)
})
it('should add indexes on model', () => {
expect(metadata.modelOptions.indexes).toBeDefined()
expect(metadata.modelOptions.indexes!.size).toBe(1)
expect(metadata.modelOptions.indexes!.get(INDEX_ACTIVE)).toBeDefined()
expect(metadata.modelOptions.indexes!.get(INDEX_ACTIVE)!.partitionKey).toBe('active')
expect(metadata.modelOptions.indexes!.get(INDEX_ACTIVE)!.sortKey).toBeUndefined()
})
it('should define the index on property metadata', () => {
const propMeta: any = metadata.forProperty('active')
expect(propMeta).toBeDefined()
expect(propMeta.keyForGSI).toBeDefined()
expect(Object.keys(propMeta.keyForGSI).length).toBe(1)
expect(propMeta.keyForGSI[INDEX_ACTIVE]).toBeDefined()
expect(propMeta.keyForGSI[INDEX_ACTIVE]).toBe('HASH')
})
})
describe('index (partition key and range key)', () => {
let metadata: Metadata<DifferentModel>
beforeEach(() => {
metadata = metadataForModel(DifferentModel)
})
it('should add indexes on model', () => {
expect(metadata.modelOptions.indexes).toBeDefined()
expect(metadata.modelOptions.indexes!.size).toBe(1)
expect(metadata.modelOptions.indexes!.get(INDEX_ACTIVE)).toBeDefined()
expect(metadata.modelOptions.indexes!.get(INDEX_ACTIVE)!.partitionKey).toBe('active')
expect(metadata.modelOptions.indexes!.get(INDEX_ACTIVE)!.sortKey).toBe('createdAt')
})
it('should define the index on property metadata', () => {
const propMeta: any = metadata.forProperty('active')
expect(propMeta).toBeDefined()
expect(propMeta.keyForGSI).toBeDefined()
expect(Object.keys(propMeta.keyForGSI).length).toBe(1)
expect(propMeta.keyForGSI[INDEX_ACTIVE]).toBeDefined()
expect(propMeta.keyForGSI[INDEX_ACTIVE]).toBe('HASH')
})
it('should define the index on property metadata', () => {
const propMeta: any = metadata.forProperty('createdAt')
expect(propMeta).toBeDefined()
expect(propMeta.keyForGSI).toBeDefined()
expect(Object.keys(propMeta.keyForGSI).length).toBe(1)
expect(propMeta.keyForGSI[INDEX_ACTIVE]).toBeDefined()
expect(propMeta.keyForGSI[INDEX_ACTIVE]).toBe('RANGE')
})
})
describe('index (a bunch of indexes with wild combinations)', () => {
let metadata: Metadata<ModelWithABunchOfIndexes>
beforeEach(() => {
metadata = metadataForModel(ModelWithABunchOfIndexes)
})
it('should add indexes on model', () => {
expect(metadata.getPartitionKey()).toBeDefined()
expect(metadata.getPartitionKey()).toBe('id')
expect(metadata.getSortKey()).toBeDefined()
expect(metadata.getSortKey()).toBe('createdAt')
// metadata.getGlobalIndex(INDEX_ACTIVE_CREATED_AT)
// metadata.getLocalIndex(INDEX_ACTIVE_CREATED_AT)
expect(metadata.modelOptions.indexes).toBeDefined()
expect(metadata.modelOptions.indexes!.size).toBe(2)
const gsiActive = metadata.getIndex(INDEX_ACTIVE_CREATED_AT)
expect(gsiActive).toBeDefined()
expect(gsiActive!.partitionKey).toBe('active')
expect(gsiActive!.sortKey).toBe('createdAt')
const lsiCount = metadata.getIndex(INDEX_COUNT)
expect(lsiCount).toBeDefined()
expect(lsiCount!.partitionKey).toBe('myId')
expect(lsiCount!.sortKey).toBe('count')
})
})
})
describe('multiple property decorators', () => {
const REVERSE_INDEX = 'reverse-index'
const OTHER_INDEX = 'other-index'
const LSI_1 = 'lsi-1'
const LSI_2 = 'lsi-2'
@Model()
class ABC {
@PartitionKey()
@Property({ name: 'pk' })
@GSISortKey(REVERSE_INDEX)
id: string
@SortKey()
@Property({ name: 'sk' })
@GSIPartitionKey(REVERSE_INDEX)
@GSISortKey(OTHER_INDEX)
timestamp: number
@GSIPartitionKey(OTHER_INDEX)
@LSISortKey(LSI_1)
@LSISortKey(LSI_2)
otherId: string
}
let metaData: Metadata<ABC>
beforeEach(() => (metaData = metadataForModel(ABC)))
it('PartitionKey & Property & GSISortKey should combine the data', () => {
const propData = metaData.forProperty('id')
expect(propData).toEqual({
key: { type: 'HASH' },
name: 'id',
nameDb: 'pk',
typeInfo: { type: String },
keyForGSI: { [REVERSE_INDEX]: 'RANGE' },
})
})
it('SortKey & Property & GSIPartitionKey & GSISortKey should combine the data', () => {
const propData = metaData.forProperty('timestamp')
expect(propData).toEqual({
key: { type: 'RANGE' },
name: 'timestamp',
nameDb: 'sk',
typeInfo: { type: Number },
keyForGSI: { [REVERSE_INDEX]: 'HASH', [OTHER_INDEX]: 'RANGE' },
})
})
it('GSIPartitionKey & multiple LSISortkey should combine the data', () => {
const propData = metaData.forProperty('otherId')
expect(propData).toBeDefined()
expect(propData!.name).toEqual('otherId')
expect(propData!.nameDb).toEqual('otherId')
expect(propData!.typeInfo).toEqual({ type: String })
expect(propData!.keyForGSI).toEqual({ [OTHER_INDEX]: 'HASH' })
expect(propData!.sortKeyForLSI).toContain(LSI_1)
expect(propData!.sortKeyForLSI).toContain(LSI_2)
})
it('correctly defines the indexes', () => {
const reverseIndex = metaData.getIndex(REVERSE_INDEX)
const otherIndex = metaData.getIndex(OTHER_INDEX)
const lsi1 = metaData.getIndex(LSI_1)
const lsi2 = metaData.getIndex(LSI_2)
expect(reverseIndex).toEqual({ partitionKey: 'sk', sortKey: 'pk' })
expect(otherIndex).toEqual({ partitionKey: 'otherId', sortKey: 'sk' })
expect(lsi1).toEqual({ partitionKey: 'pk', sortKey: 'otherId' })
expect(lsi2).toEqual({ partitionKey: 'pk', sortKey: 'otherId' })
})
})
describe('enum (no Enum decorator)', () => {
let metadata: Metadata<ModelWithEnum>
beforeEach(() => {
metadata = metadataForModel(ModelWithEnum)
})
it('should add enum type to property', () => {
const enumPropertyMetadata = metadata.forProperty('type')!
expect(enumPropertyMetadata.typeInfo).toBeDefined()
expect(enumPropertyMetadata.typeInfo).toEqual({ type: Number })
const strEnumPropertyMetadata = metadata.forProperty('strType')!
expect(strEnumPropertyMetadata.typeInfo).toBeDefined()
expect(strEnumPropertyMetadata.typeInfo).toEqual({ type: String })
})
})
describe('with inheritance', () => {
it('should override the table name', () => {
@Model({ tableName: 'super-table-name' })
class A {}
@Model({ tableName: 'my-real-table-name' })
class B extends A {}
const metaData = metadataForModel(B).modelOptions
expect(metaData.tableName).toBe('my-real-table-name')
})
it('should not inherit the table name', () => {
@Model({ tableName: 'super-table-name' })
class A {}
@Model()
class B extends A {}
const metaData = metadataForModel(B).modelOptions
expect(metaData.tableName).toBe('bs')
})
it("should contain the super-class' and own properties", () => {
@Model()
class A {
@PartitionKey()
myPartitionKey: string
@SortKey()
mySortKey: number
}
@Model()
class B extends A {
@CollectionProperty({ sorted: true })
myOwnProp: string[]
}
const metaData = metadataForModel(B).modelOptions
expect(metaData.properties).toBeDefined()
expect(metaData.properties!.length).toBe(3)
const bMetadata = metadataForModel(B)
expect(bMetadata.forProperty('myPartitionKey')).toBeDefined()
expect(bMetadata.forProperty('mySortKey')).toBeDefined()
expect(bMetadata.forProperty('myOwnProp')).toBeDefined()
})
it("should contain the super-class' and own indexes", () => {
@Model()
class A {
@PartitionKey()
myPartitionKey: string
@GSIPartitionKey('my-gsi')
myGsiPartitionKey: string
@GSISortKey('my-gsi')
myGsiSortKey: number
@LSISortKey('my-lsi')
myLsiSortKey: number
}
@Model()
class B extends A {
@GSIPartitionKey('my-other-gsi')
myOtherGsiPartitionKey: string
}
const metaData = metadataForModel(B).modelOptions
expect(metaData.properties).toBeDefined()
expect(metaData.properties!.length).toBe(5)
const bMetadata = metadataForModel(B)
expect(bMetadata.forProperty('myPartitionKey')).toBeDefined()
expect(bMetadata.forProperty('myGsiPartitionKey')).toBeDefined()
expect(bMetadata.forProperty('myGsiSortKey')).toBeDefined()
expect(bMetadata.forProperty('myLsiSortKey')).toBeDefined()
expect(bMetadata.forProperty('myOtherGsiPartitionKey')).toBeDefined()
expect(metaData.indexes).toBeDefined()
expect(metaData.indexes!.get('my-gsi')).toBeDefined()
expect(metaData.indexes!.get('my-lsi')).toBeDefined()
expect(metaData.indexes!.get('my-other-gsi')).toBeDefined()
})
it("should contain the super-class' and own transient properties", () => {
@Model()
class A {
@Transient()
myTransientProp: string
}
@Model()
class B extends A {
@Transient()
myOtherTransientProp: number
}
const metaData = metadataForModel(B).modelOptions
expect(metaData.transientProperties).toBeDefined()
expect(metaData.transientProperties!.length).toBe(2)
expect(metaData.transientProperties!.includes('myTransientProp')).toBeTruthy()
expect(metaData.transientProperties!.includes('myOtherTransientProp')).toBeTruthy()
})
it(`should not contains 'sibling' props `, () => {
@Model()
class A {
@Property()
aProp: string
}
@Model()
class B extends A {
@Property()
bProp: string
}
@Model()
class C extends A {
@Property()
cProp: string
}
const aMetaData = metadataForModel(A)
const aModelMetadata = aMetaData.modelOptions
const bMetaData = metadataForModel(B)
const bModelMetadata = bMetaData.modelOptions
const cMetaData = metadataForModel(C)
const cModelMetadata = cMetaData.modelOptions
expect(aModelMetadata.properties).toBeDefined()
expect(aModelMetadata.properties!.length).toBe(1)
expect(bModelMetadata.properties).toBeDefined()
expect(bModelMetadata.properties!.length).toBe(2)
expect(bMetaData.forProperty('bProp')).toBeDefined()
expect(bMetaData.forProperty('cProp')).toBeFalsy()
expect(cModelMetadata.properties).toBeDefined()
expect(cModelMetadata.properties!.length).toBe(2)
expect(cMetaData.forProperty('cProp')).toBeDefined()
expect(cMetaData.forProperty('bProp')).toBeFalsy()
})
it('should not alter super props', () => {
@Model()
class A {
@Property()
aProp: string
}
@Model()
class B extends A {
@Property({ name: 'bProp' })
aProp: string
}
const aMeta = metadataForModel(A)
const aModelMetadata = aMeta.modelOptions
expect(aModelMetadata.properties).toBeDefined()
expect(aModelMetadata.properties!.length).toBe(1)
const aPropMeta = aModelMetadata.properties![0]
expect(aPropMeta).toBeDefined()
expect(aPropMeta!.name).toBe('aProp')
expect(aPropMeta!.nameDb).toBe('aProp')
const bMeta = metadataForModel(B)
const bModelMetadata = bMeta.modelOptions
expect(bModelMetadata.properties).toBeDefined()
expect(bModelMetadata.properties!.length).toBe(1)
const bPropMeta = bModelMetadata.properties![0]
expect(bPropMeta).toBeDefined()
expect(bPropMeta!.name).toBe('aProp')
expect(bPropMeta!.nameDb).toBe('bProp')
})
it('should have all parents props even if empty', () => {
@Model()
class A {
@Property()
aProp: string
}
@Model()
class B extends A {}
const bMeta = metadataForModel(B)
expect(bMeta.modelOptions.properties).toBeDefined()
expect(bMeta.modelOptions.properties!.length).toBe(1)
})
it('should work for real world scenario 1', () => {
const metadata = metadataForModel(Form)
expect(metadata.modelOptions.properties!.length).toBe(4)
const meta = metadata.forProperty('id')
expect(meta).toBeDefined()
})
})
describe('should throw when more than one partitionKey was defined in a model', () => {
it('does so', () => {
expect(() => {
@Model()
class InvalidModel {
@PartitionKey()
partKeyA: string
@PartitionKey()
partKeyB: string
}
return new InvalidModel()
}).toThrow()
})
})
describe('decorate property multiple times identically', () => {
let logReceiver: jest.Mock
beforeEach(() => {
logReceiver = jest.fn()
updateDynamoEasyConfig({ logReceiver })
})
it('should not throw but warn, if the PartitionKey is two times annotated', () => {
@Model()
class NotCoolButOkModel {
@PartitionKey()
@PartitionKey()
doppeltGemoppelt: string
}
const propertyMetaData = metadataForModel(NotCoolButOkModel).forProperty('doppeltGemoppelt')
expect(propertyMetaData).toBeDefined()
expect(propertyMetaData!.key).toEqual({ type: 'HASH' })
expect(logReceiver).toBeCalledTimes(1)
expect(logReceiver.mock.calls[0][0].level).toBe(LogLevel.WARNING)
})
})
}) | the_stack |
import * as astTypes from 'ast-types';
import {NodePath} from 'ast-types';
import * as dom5 from 'dom5';
import * as estree from 'estree';
import {Iterable as IterableX} from 'ix';
import * as jsc from 'jscodeshift';
import {EOL} from 'os';
import * as parse5 from 'parse5';
import {AstNodeWithLanguage} from 'polymer-analyzer';
import {babelNodeToEstreeNode} from './util';
/**
* Serialize a parse5 Node to a string.
*/
export function serializeNode(node: parse5.ASTNode): string {
const container = parse5.treeAdapters.default.createDocumentFragment();
dom5.append(container, node);
return parse5.serialize(container);
}
/**
* Finds an unused identifier name given a requested name and set of used names.
*/
export function findAvailableIdentifier(requested: string, used: Set<string>) {
let suffix = 0;
let alias = requested;
while (used.has(alias)) {
alias = requested + '$' + (suffix++);
}
return alias;
}
/**
* Detect if two Node's have the same source location.
*/
export function isSourceLocationEqual(a: estree.Node, b: estree.Node): boolean {
if (a === b) {
return true;
}
const aLoc = a.loc;
const bLoc = b.loc;
if (aLoc === bLoc) {
return true;
}
if (aLoc == null || bLoc == null) {
return false;
}
return aLoc.start.column === bLoc.start.column &&
aLoc.start.line === bLoc.start.line &&
aLoc.end.column === bLoc.end.column && aLoc.end.line === bLoc.end.line;
}
/**
* Serialize a Node to string, wrapped as an estree template literal.
*/
export function serializeNodeToTemplateLiteral(
node: parse5.ASTNode, addNewLines = true) {
const lines = parse5.serialize(node).split('\n');
// Remove empty / whitespace-only leading lines.
while (/^\s*$/.test(lines[0])) {
lines.shift();
}
// Remove empty / whitespace-only trailing lines.
while (/^\s*$/.test(lines[lines.length - 1])) {
lines.pop();
}
let cooked = lines.join(EOL);
if (addNewLines) {
cooked = `${EOL}${cooked}${EOL}`;
}
// The `\` -> `\\` replacement must occur first so that the backslashes
// introduced by later replacements are not replaced.
const raw = cooked.replace(/(<\/script|\\|`|\$)/g, (_match, group) => {
switch (group) {
case `<\/script`:
return '</script';
case '\\':
return '\\\\';
case '`':
return '\\`';
case '$':
return '\\$';
default:
throw new Error(`oops!: ${group}`);
}
});
return jsc.templateLiteral([jsc.templateElement({cooked, raw}, true)], []);
}
/**
* Returns an array of identifiers if an expression is a chain of property
* access, as used in namespace-style exports.
*/
export function getMemberPath(expression: estree.Node): string[]|undefined {
if (expression.type !== 'MemberExpression' || expression.computed ||
expression.property.type !== 'Identifier') {
return;
}
const property = expression.property.name;
if (expression.object.type === 'ThisExpression') {
return ['this', property];
} else if (expression.object.type === 'Identifier') {
if (expression.object.name === 'window') {
return [property];
} else {
return [expression.object.name, property];
}
} else if (expression.object.type === 'MemberExpression') {
const prefixPath = getMemberPath(expression.object);
if (prefixPath !== undefined) {
return [...prefixPath, property];
}
}
return undefined;
}
/**
* Returns a string of identifiers (dot-seperated) if an expression is a chain
* of property access, as used in namespace-style exports.
*/
export function getMemberName(expression: estree.Node): string|undefined {
const path = getMemberPath(expression);
return path ? path.join('.') : path;
}
/**
* Returns an Identifier's name if Node is a simple Identifier. Otherwise,
* get the full member name.
*/
export function getMemberOrIdentifierName(expression: estree.Node): string|
undefined {
if (expression.type === 'Identifier') {
return expression.name;
}
return getMemberName(expression);
}
/**
* Find the node in program that corresponds to the same part of code
* as the given node.
*
* This method is necessary because program is parsed locally, but the
* given node may have come from the analyzer (so a different parse run,
* possibly by a different parser, though they output the same format).
*/
export function getNodePathInProgram(
program: estree.Program, astNode: AstNodeWithLanguage|undefined) {
if (astNode === undefined || astNode.language !== 'js') {
return;
}
const node = astNode.node;
let associatedNodePath: NodePath|undefined;
astTypes.visit(program, {
visitNode(path: NodePath<estree.Node>): boolean |
undefined {
// Traverse first, because we want the most specific node that exactly
// matches the given node.
this.traverse(path);
if (associatedNodePath === undefined &&
isSourceLocationEqual(path.node, babelNodeToEstreeNode(node)) &&
path.node.type === node.type) {
associatedNodePath = path;
return false;
}
return undefined;
}
});
return associatedNodePath;
}
/**
* Yields the NodePath for each statement at the top level of `program`.
*
* Like `yield* program.body` except it yields NodePaths rather than
* Nodes, so that the caller can mutate the AST with the NodePath api.
*/
export function* getTopLevelStatements(program: estree.Program) {
const nodePaths: NodePath[] = [];
astTypes.visit(program, {
visitNode(path: NodePath<estree.Node>) {
if (!path.parent) {
// toplevel program
this.traverse(path);
return;
}
if (path.parent.node.type !== 'Program') {
// not a toplevel statement, skip it
return false;
}
this.traverse(path);
// ok, path.node must be a toplevel statement of the program.
nodePaths.push(path);
return;
}
});
yield* nodePaths;
}
/**
* If the given NodePath Node is on the left side of an assignment expression,
* return a NodePath object for that assignment expression.
*
* Examples where the assignment expression is returned for `foo`:
*
* foo = 10;
* window.foo = 10;
*
* Examples where an assignment expression is NOT matched:
*
* bar = foo;
* foo();
* const foo = 10;
* this.foo = 10;
*/
export function getPathOfAssignmentTo(path: NodePath):
NodePath<estree.AssignmentExpression>|undefined {
if (!path.parent) {
return undefined;
}
const parentNode = path.parent.node;
if (parentNode.type === 'AssignmentExpression') {
if (parentNode.left === path.node) {
return path.parent as NodePath<estree.AssignmentExpression>;
}
return undefined;
}
if (parentNode.type === 'MemberExpression' &&
parentNode.property === path.node &&
parentNode.object.type === 'Identifier' &&
parentNode.object.name === 'window') {
return getPathOfAssignmentTo(path.parent);
}
return undefined;
}
/**
* Give the name of the setter we should use to set the given memberPath. Does
* not check to see if the setter exists, just returns the name it would have.
* e.g.
*
* ['Polymer', 'foo', 'bar'] => 'Polymer.foo.setBar'
*/
export function getSetterName(memberPath: string[]): string {
const lastSegment = memberPath[memberPath.length - 1];
memberPath[memberPath.length - 1] =
`set${lastSegment.charAt(0).toUpperCase()}${lastSegment.slice(1)}`;
return memberPath.join('.');
}
export function filterClone(
nodes: parse5.ASTNode[], filter: dom5.Predicate): parse5.ASTNode[] {
const clones = [];
for (const node of nodes) {
if (!filter(node)) {
continue;
}
const clone = dom5.cloneNode(node);
clones.push(clone);
if (node.childNodes) {
clone.childNodes = filterClone(node.childNodes, filter);
}
}
return clones;
}
/**
* Finds all identifiers within the given program and creates a set of their
* names (strings). Identifiers in the `ignored` argument set will not
* contribute to the output set.
*/
export function collectIdentifierNames(
program: estree.Program,
ignored: ReadonlySet<estree.Identifier>): Set<string> {
const identifiers = new Set();
astTypes.visit(program, {
visitIdentifier(path: NodePath<estree.Identifier>): (boolean | void) {
const node = path.node;
if (!ignored.has(node)) {
identifiers.add(path.node.name);
}
this.traverse(path);
},
});
return identifiers;
}
/**
* Returns true if a dom module ASTNode is eligible for inlining.
*/
export function canDomModuleBeInlined(domModule: parse5.ASTNode) {
if (domModule.attrs.some((a) => a.name !== 'id')) {
return false; // attributes other than 'id' on dom-module
}
let templateTagsSeen = 0;
for (const node of domModule.childNodes || []) {
if (node.tagName === 'template') {
if (node.attrs.length > 0) {
return false; // attributes on template
}
templateTagsSeen++;
} else if (node.tagName === 'script') {
// this is fine, scripts are handled elsewhere
} else if (
dom5.isTextNode(node) && dom5.getTextContent(node).trim() === '') {
// empty text nodes are fine
} else {
return false; // anything else, we can't convert it
}
}
if (templateTagsSeen > 1) {
return false; // more than one template tag, can't convert
}
return true;
}
/**
* Yields all nodes inside the given node in top-down, first-to-last order.
*/
function* nodesInside(node: parse5.ASTNode): Iterable<parse5.ASTNode> {
const childNodes = parse5.treeAdapters.default.getChildNodes(node);
if (childNodes === undefined) {
return;
}
for (const child of childNodes) {
yield child;
yield* nodesInside(child);
}
}
/**
* Yields all nodes that come after the given node, including later siblings
* of ancestors.
*/
function* nodesAfter(node: parse5.ASTNode): Iterable<parse5.ASTNode> {
const parentNode = node.parentNode;
if (!parentNode) {
return;
}
const siblings = parse5.treeAdapters.default.getChildNodes(parentNode);
for (let i = siblings.indexOf(node) + 1; i < siblings.length; i++) {
const laterSibling = siblings[i];
yield laterSibling;
yield* nodesInside(laterSibling);
}
yield* nodesAfter(parentNode);
}
/**
* Returns the text of all comments in the document between the two optional
* points.
*
* If `from` is given, returns all comments after `from` in the document.
* If `until` is given, returns all comments up to `until` in the document.
*/
export function getCommentsBetween(
document: parse5.ASTNode,
from: parse5.ASTNode|undefined,
until: parse5.ASTNode|undefined): string[] {
const nodesStart =
from === undefined ? nodesInside(document) : nodesAfter(from);
const nodesBetween =
IterableX.from(nodesStart).takeWhile((node) => node !== until);
const commentNodesBetween =
nodesBetween.filter((node) => dom5.isCommentNode(node));
const commentStringsBetween =
commentNodesBetween.map((node) => dom5.getTextContent(node));
const formattedCommentStringsBetween =
commentStringsBetween.map((commentText) => {
// If it looks like there might be jsdoc in the comment, start the
// comment with an extra * so that the js comment looks like a jsdoc
// comment.
if (/@\w+/.test(commentText)) {
return '*' + commentText;
}
return commentText;
});
return Array.from(formattedCommentStringsBetween);
}
/** Recast represents comments differently than espree. */
interface RecastNode {
comments?: null|undefined|Array<RecastComment>;
}
interface RecastComment {
type: 'Line'|'Block';
leading: boolean;
trailing: boolean;
value: string;
}
/**
* Given some comments, attach them to the first statement, if any, in the
* given array of statements.
*
* If there is no first statement, one will be created.
*/
export function attachCommentsToFirstStatement(
comments: string[],
statements: Array<estree.Statement|estree.ModuleDeclaration>) {
if (comments.length === 0) {
return;
}
// A license comment is appropriate at the top of a file. Anything else
// should be checked.
if (comments.filter((c) => !/@license/.test(c)).length > 0) {
const message =
`\n FIXME(polymer-modulizer): the above comments were extracted\n` +
` from HTML and may be out of place here. Review them and\n` +
` then delete this comment!\n`;
comments.push(message);
}
const recastComments = getCommentsFromTexts(comments);
let firstStatement: RecastNode&(estree.Statement | estree.ModuleDeclaration) =
statements[0];
if (firstStatement === undefined) {
firstStatement = jsc.expressionStatement(jsc.identifier(''));
statements.unshift(firstStatement);
}
firstStatement.comments =
recastComments.concat(firstStatement.comments || []);
}
export function attachCommentsToEndOfProgram(
comments: string[],
statements: Array<estree.Statement|estree.ModuleDeclaration>) {
if (comments.length === 0) {
return;
}
const message =
`\n FIXME(polymer-modulizer): the above comments were extracted\n` +
` from HTML and may be out of place here. Review them and\n` +
` then delete this comment!\n`;
comments.push(message);
const recastComments = getCommentsFromTexts(comments);
const lastStatement =
jsc.expressionStatement(jsc.identifier('')) as RecastNode &
estree.Statement;
lastStatement.comments =
(lastStatement.comments || []).concat(recastComments);
statements.push(lastStatement);
}
function getCommentsFromTexts(commentTexts: string[]) {
const recastComments: RecastComment[] = commentTexts.map((comment) => {
const escapedComment = comment.replace(/\*\//g, '*\\/');
return {
type: 'Block' as 'Block',
leading: true,
trailing: false,
value: escapedComment,
};
});
return recastComments;
}
/**
* Returns true if the given program contains any expressions that write to the
* global "settings" object.
*/
export function containsWriteToGlobalSettingsObject(program: estree.Program) {
let containsWriteToGlobalSettingsObject = false;
// Note that we look for writes to these objects exactly, not to writes to
// members of these objects.
const globalSettingsObjects =
new Set<string>(['Polymer', 'Polymer.Settings', 'ShadyDOM']);
function getNamespacedName(node: estree.Node) {
if (node.type === 'Identifier') {
return node.name;
}
const memberPath = getMemberPath(node);
if (memberPath) {
return memberPath.join('.');
}
return undefined;
}
astTypes.visit(program, {
visitAssignmentExpression(path: NodePath<estree.AssignmentExpression>) {
const name = getNamespacedName(path.node.left);
if (globalSettingsObjects.has(name!)) {
containsWriteToGlobalSettingsObject = true;
}
return false;
},
});
return containsWriteToGlobalSettingsObject;
}
/**
* Create an array of statements that correctly insert the given parse5 (HTML)
* nodes into JavaScript.
*/
export function createDomNodeInsertStatements(
nodes: parse5.ASTNode[], activeInBody = false): estree.Statement[] {
const varName = `$_documentContainer`;
const fragment = {
nodeName: '#document-fragment',
attrs: [],
childNodes: nodes,
__location: {} as parse5.ElementLocationInfo,
};
const templateValue = serializeNodeToTemplateLiteral(fragment, false);
const createElementTemplate = jsc.variableDeclaration(
'const',
[jsc.variableDeclarator(
jsc.identifier(varName),
jsc.callExpression(
jsc.memberExpression(
jsc.identifier('document'), jsc.identifier('createElement')),
[jsc.literal('template')]))]);
const setDocumentContainerStatement =
jsc.expressionStatement(jsc.assignmentExpression(
'=',
jsc.memberExpression(
jsc.identifier(varName), jsc.identifier('innerHTML')),
templateValue));
const targetNode = activeInBody ? 'body' : 'head';
return [
createElementTemplate,
setDocumentContainerStatement,
jsc.expressionStatement(jsc.callExpression(
jsc.memberExpression(
jsc.memberExpression(
jsc.identifier('document'), jsc.identifier(targetNode)),
jsc.identifier('appendChild')),
[jsc.memberExpression(
jsc.identifier(varName), jsc.identifier('content'))]))
];
}
/**
* Insert an array of statements into the program at the correct location. The
* correct location for new statements is after ImportDeclarations, if any
* exist.
*/
export function insertStatementsIntoProgramBody(
statements: estree.Statement[], program: estree.Program) {
let insertionPoint = 0;
for (let i = 0; i < program.body.length; i++) {
const bodyStatement = program.body[i];
if (bodyStatement.type === 'ImportDeclaration') {
// cover the case where the import is at the end
insertionPoint = i + 1;
} else {
// otherwise, break
insertionPoint = i;
break;
}
}
program.body.splice(insertionPoint, 0, ...statements);
} | the_stack |
'use strict';
import * as chai from 'chai';
import * as sinonChai from 'sinon-chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as vscode from 'vscode';
import { ExtensionCommands } from '../../ExtensionCommands';
import { FabricRuntimeUtil, FabricNode, FabricEnvironmentRegistryEntry, FabricEnvironmentRegistry, EnvironmentType } from 'ibm-blockchain-platform-common';
import { IBlockchainQuickPickItem, UserInputUtil } from '../../extension/commands/UserInputUtil';
import { TimerUtil } from '../../extension/util/TimerUtil';
import { LocalMicroEnvironmentManager } from '../../extension/fabric/environments/LocalMicroEnvironmentManager';
import { LocalMicroEnvironment } from '../../extension/fabric/environments/LocalMicroEnvironment';
// tslint:disable:no-unused-expression
chai.use(sinonChai);
chai.use(chaiAsPromised);
let opsToolsAllNodesQuickPick: IBlockchainQuickPickItem<FabricNode>[] = [];
module.exports = function(): any {
/**
* Given
*/
this.Given(/the ?('[a-zA-Z]*?')? ?(?:capability)? ?(.*?) environment is running/, this.timeout, async (capability: string, environmentName: string) => {
const runtimeManager: LocalMicroEnvironmentManager = LocalMicroEnvironmentManager.instance();
let runtime: LocalMicroEnvironment = runtimeManager.getRuntime(environmentName);
let isRunning: boolean;
if (!runtime) {
isRunning = false;
} else {
isRunning = await runtime.isRunning();
}
if (!isRunning) {
if (!runtime) {
await this.fabricEnvironmentHelper.createEnvironment(environmentName, undefined, true, capability);
runtime = runtimeManager.getRuntime(environmentName);
} else {
const environmentEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(environmentName);
await vscode.commands.executeCommand(ExtensionCommands.START_FABRIC, environmentEntry);
}
isRunning = await runtime.isRunning();
}
await runtime.waitFor();
isRunning.should.equal(true);
this.capability = (capability === UserInputUtil.V1_4_2 ? UserInputUtil.V1_4_2 : UserInputUtil.V2_0);
});
this.Given(`a 2 org local environment called '{string}' has been created with {string} capabilities`, this.timeout, async (environmentName: string, capability: string) => {
const runtimeManager: LocalMicroEnvironmentManager = LocalMicroEnvironmentManager.instance();
const runtime: LocalMicroEnvironment = runtimeManager.getRuntime(environmentName);
if (!runtime) {
await this.fabricEnvironmentHelper.createEnvironment(environmentName, undefined, undefined, capability);
}
});
this.Given("the '{string}' environment is connected", this.timeout, async (environment: string) => {
await TimerUtil.sleep(3000);
this.environmentName = environment;
await this.fabricEnvironmentHelper.connectToEnvironment(environment);
await TimerUtil.sleep(3000);
});
// this one
this.Given(/(a local environment|an environment) '(.*?)' ?(?:of type '(.*?)')? ?(?:with (.*?) capabilities)? exists/, this.timeout, async (localString: string, environmentName: string, opsType: string, capability?: string) => {
const args: any[] = [environmentName, opsType];
const isLocal: boolean = localString === 'a local environment';
args.push(isLocal);
if (capability) {
args.push(capability);
}
opsToolsAllNodesQuickPick = await this.fabricEnvironmentHelper.createEnvironment(...args);
this.environmentName = environmentName;
this.capability = (capability === UserInputUtil.V1_4_2 ? UserInputUtil.V1_4_2 : UserInputUtil.V2_0);
await TimerUtil.sleep(3000);
});
this.Given('the environment is setup', this.timeout, async () => {
const nodes: string[] = ['ca.example.com', 'orderer.example.com', 'peer0.org1.example.com'];
let wallet: string;
if (this.environmentName === 'v1Fabric') {
wallet = 'v1Wallet';
} else {
wallet = this.environmentName === 'myFabric2' ? 'myWallet2' : 'myWallet';
}
let identity: string;
for (const node of nodes) {
if (node === 'ca.example.com') {
identity = 'conga2';
} else {
identity = 'conga';
}
await this.fabricEnvironmentHelper.associateNodeWithIdentitiy(this.environmentName, node, identity, wallet);
}
});
this.Given("the '{string}' opstools environment is setup", this.timeout, async (environmentType: string) => {
const nodeMap: Map<string, string> = new Map<string, string>();
let wallet: string;
if (environmentType === 'software') {
nodeMap.set('Ordering Org CA', 'Ordering Org CA Admin');
nodeMap.set('Ordering Service_1', 'Ordering Org Admin');
nodeMap.set('Org1 CA', 'Org1 CA Admin');
nodeMap.set('Org2 CA', 'Org2 CA Admin');
nodeMap.set('Org1 Peer', 'Org1 Admin');
nodeMap.set('Org2 Peer', 'Org2 Admin');
wallet = 'opsToolsWallet';
} else if (environmentType === 'SaaS') {
nodeMap.set('Ordering Org Saas CA', 'Ordering Org Saas CA Admin');
nodeMap.set('Ordering Service Saas_1', 'Ordering Org Saas Admin');
nodeMap.set('Org1 CA Saas', 'Org1 CA Saas Admin');
nodeMap.set('Org2 CA Saas', 'Org2 CA Saas Admin');
nodeMap.set('Org1 Peer Saas', 'Org1Saas Admin');
nodeMap.set('Org2 Peer Saas', 'Org2Saas Admin');
wallet = 'SaaSOpsToolsWallet';
}
for (const node of nodeMap.entries()) {
await this.fabricEnvironmentHelper.associateNodeWithIdentitiy(this.environmentName, node[0], node[1], wallet);
}
});
this.Given("I have edited filters and imported all nodes to environment '{string}'", this.timeout, async (environmentName: string) => {
await this.fabricEnvironmentHelper.editNodeFilters(opsToolsAllNodesQuickPick, environmentName);
});
this.Given('there are no IBM Cloud environments', this.timeout, async () => {
const environments: FabricEnvironmentRegistryEntry[] = await FabricEnvironmentRegistry.instance().getAll();
for (const env of environments) {
if (env.environmentType === EnvironmentType.SAAS_OPS_TOOLS_ENVIRONMENT) {
await this.fabricEnvironmentHelper.deleteEnvironment(env.name);
}
}
});
/**
* When
*/
this.When(/I create an environment '(.*?)' ?(?:of type '(.*?)')?/, this.timeout, async (environmentName: string, opsType: string) => {
opsToolsAllNodesQuickPick = await this.fabricEnvironmentHelper.createEnvironment(environmentName, opsType);
await TimerUtil.sleep(3000);
});
this.When("I associate identity '{string}' in wallet '{string}' with node '{string}'", this.timeout, async (identity: string, wallet: string, node: string) => {
await this.fabricEnvironmentHelper.associateNodeWithIdentitiy(this.environmentName, node, identity, wallet);
});
this.When("I connect to the environment '{string}'", this.timeout, async (environment: string) => {
await this.fabricEnvironmentHelper.connectToEnvironment(environment);
await TimerUtil.sleep(3000);
});
this.When("I delete node '{string}'", this.timeout, async (nodeName: string) => {
await this.fabricEnvironmentHelper.deleteNode(nodeName, this.environmentName);
});
this.When("I hide the node '{string}'", this.timeout, async (nodeName: string) => {
await this.fabricEnvironmentHelper.hideNode(nodeName, this.environmentName);
});
this.When("I delete an environment '{string}'", this.timeout, async (environmentName: string) => {
await this.fabricEnvironmentHelper.deleteEnvironment(environmentName);
});
this.When(`I stop the ${FabricRuntimeUtil.LOCAL_FABRIC}`, this.timeout, async () => {
await vscode.commands.executeCommand(ExtensionCommands.STOP_FABRIC);
const runtimeManager: LocalMicroEnvironmentManager = LocalMicroEnvironmentManager.instance();
const runtime: LocalMicroEnvironment = runtimeManager.getRuntime(FabricRuntimeUtil.LOCAL_FABRIC);
const isRunning: boolean = await runtime.isRunning();
isRunning.should.equal(false);
});
this.When(`I start the ${FabricRuntimeUtil.LOCAL_FABRIC}`, this.timeout, async () => {
await vscode.commands.executeCommand(ExtensionCommands.START_FABRIC);
const runtimeManager: LocalMicroEnvironmentManager = LocalMicroEnvironmentManager.instance();
const runtime: LocalMicroEnvironment = runtimeManager.getRuntime(FabricRuntimeUtil.LOCAL_FABRIC);
const isRunning: boolean = await runtime.isRunning();
isRunning.should.equal(true);
});
this.When(`I teardown the ${FabricRuntimeUtil.LOCAL_FABRIC}`, this.timeout, async () => {
await vscode.commands.executeCommand(ExtensionCommands.TEARDOWN_FABRIC, undefined, true, FabricRuntimeUtil.LOCAL_FABRIC);
const runtimeManager: LocalMicroEnvironmentManager = LocalMicroEnvironmentManager.instance();
const runtime: LocalMicroEnvironment = runtimeManager.getRuntime(FabricRuntimeUtil.LOCAL_FABRIC);
const isRunning: boolean = await runtime.isRunning();
isRunning.should.equal(false);
});
this.When("I edit filters and import all nodes to environment '{string}'", this.timeout, async (environmentName: string) => {
await this.fabricEnvironmentHelper.editNodeFilters(opsToolsAllNodesQuickPick, environmentName);
});
this.When('I log in to IBM Cloud', this.timeout, async () => {
await vscode.commands.executeCommand(ExtensionCommands.LOG_IN_AND_DISCOVER);
});
}; | the_stack |
module Kiwi.Geom {
/**
* Contains a collection of STATIC methods for determining intersections between geometric objects.
*
* May methods contained here store the results of the intersections in a 'IntersectResult' Object,
* which is either created for you (by the methods which require it) OR you can pass one to use instead.
*
* If you are using the Intersect methods a lot, you may want to consider
* creating a IntersectResult class a reusing it (by passing it to the methods on the Intersect class)
* instead of having new IntersectResults created.
*
* @class Intersect
* @namespace Kiwi.Geom
* @static
*/
export class Intersect {
/**
* The type of this object.
* @method objType
* @return {String} "Intersect"
* @public
*/
public objType() {
return "Intersect";
}
/**
* -------------------------------------------------------------------------------------------
* Distance
* -------------------------------------------------------------------------------------------
**/
/**
* Returns the distance between two sets of coordinates that you specify.
* @method distance
* @param x1 {Number} The x position of the first coordinate.
* @param y1 {Number} The y position of the first coordinate.
* @param x2 {Number} The x position of the second coordinate.
* @param y2 {Number} The y position of the second coordinate.
* @return {Number} The distance between the two points.
* @public
* @static
*/
static distance(x1: number, y1: number, x2: number, y2: number) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
/**
* Returns the distance squared between two sets of coordinates that you specify.
*
* @method distanceSquared
* @param x1 {Number} The x position of the first coordinate.
* @param y1 {Number} The y position of the first coordinate.
* @param x2 {Number} The x position of the second coordinate.
* @param y2 {Number} The y position of the second coordinate.
* @return {Number} The distance between the two points squared.
* @public
* @static
*/
static distanceSquared(x1: number, y1: number, x2: number, y2: number) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
}
/**
* ---------------------------------------------------------------------
* Lines
* ---------------------------------------------------------------------
**/
/**
* Check to see if any two Lines intersect at any point.
* Both lines are treated as if they extend infintely through space.
*
* @method lineToLine
* @param line1 {Kiwi.Geom.Line} The first line object to check.
* @param line2 {Kiwi.Geom.Line} The second line object to check.
* @param [output] {Kiwi.Geom.IntersectResult} An optional
IntersectResult object to store the intersection values in. One is
created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object
containing the results of this intersection in x/y
* @public
* @static
*/
static lineToLine(line1: Line, line2: Line, output: IntersectResult =
new IntersectResult): IntersectResult {
output.result = false;
var denom = (line1.x1 - line1.x2) * (line2.y1 - line2.y2) -
(line1.y1 - line1.y2) * (line2.x1 - line2.x2);
if ( denom !== 0 ) {
output.result = true;
output.x = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) *
(line2.x1 - line2.x2) - (line1.x1 - line1.x2) *
(line2.x1 * line2.y2 - line2.y1 * line2.x2)) / denom;
output.y = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) *
(line2.y1 - line2.y2) - (line1.y1 - line1.y2) *
(line2.x1 * line2.y2 - line2.y1 * line2.x2)) / denom;
}
return output;
}
/**
* Check to see if a Line and a Line Segment intersect at any point.
* Note: The first line passed is treated as if it extends infinitely
* though space. The second is treated as if it only exists between
* its two points.
*
* @method lineToLineSegment
* @param line1 {Kiwi.Geom.Line} The first line to check.
This is the one that will extend through space infinately.
* @param seg {Kiwi.Geom.Line} The second line to check.
This is the one that will only exist between its two coordinates.
* @param [output] {Kiwi.Geom.IntersectResult} An optional
IntersectResult object to store the intersection values in. One is
created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object
containing the results of this intersection.
* @public
* @static
*/
static lineToLineSegment( line1: Line, seg: Line, output: IntersectResult = new IntersectResult ): IntersectResult {
output.result = false;
var denom = ( line1.x1 - line1.x2 ) * ( seg.y1 - seg.y2 ) -
( line1.y1 - line1.y2 ) * ( seg.x1 - seg.x2 );
if ( denom !== 0 ) {
output.x = ( ( line1.x1 * line1.y2 - line1.y1 * line1.x2 ) *
( seg.x1 - seg.x2 ) - ( line1.x1 - line1.x2 ) *
( seg.x1 * seg.y2 - seg.y1 * seg.x2 ) ) / denom;
output.y = ( ( line1.x1 * line1.y2 - line1.y1 * line1.x2 ) *
( seg.y1 - seg.y2 ) - (line1.y1 - line1.y2 ) *
( seg.x1 * seg.y2 - seg.y1 * seg.x2 ) ) / denom;
var maxX = Math.max( seg.x1, seg.x2 );
var minX = Math.min( seg.x1, seg.x2 );
var maxY = Math.max( seg.y1, seg.y2 );
var minY = Math.min( seg.y1, seg.y2 );
if ( ( output.x <= maxX && output.x >= minX ) === true &&
( output.y <= maxY && output.y >= minY ) === true ) {
output.result = true;
}
}
return output;
}
/**
* Checks to see if a Line that is passed, intersects at any point with a Line that is made by passing a set of coordinates to this method.
* Note: The first line will extend infinately through space.
* And the second line will only exist between the two points passed.
*
* @method lineToRawSegment
* @param line {Kiwi.Geom.Line} The line object that extends infinitely through space.
* @param x1 {number} The x coordinate of the first point in the second line.
* @param y1 {number} The y coordinate of the first point in the second line.
* @param x2 {number} The x coordinate of the second point in the second line.
* @param y2 {number} The y coordinate of the second point in the second line.
* @param [output] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection in x/y
* @static
* @public
*/
static lineToRawSegment(line: Line, x1: number, y1: number, x2: number, y2: number, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
var denom = (line.x1 - line.x2) * (y1 - y2) - (line.y1 - line.y2) * (x1 - x2);
if (denom !== 0) {
output.x = ((line.x1 * line.y2 - line.y1 * line.x2) * (x1 - x2) - (line.x1 - line.x2) * (x1 * y2 - y1 * x2)) / denom;
output.y = ((line.x1 * line.y2 - line.y1 * line.x2) * (y1 - y2) - (line.y1 - line.y2) * (x1 * y2 - y1 * x2)) / denom;
var maxX = Math.max(x1, x2);
var minX = Math.min(x1, x2);
var maxY = Math.max(y1, y2);
var minY = Math.min(y1, y2);
if ( output.x <= maxX && output.x >= minX &&
output.y <= maxY && output.y >= minY ) {
output.result = true;
}
}
return output;
}
/**
* Checks to see if a Line that is passed intersects with a Line that is made by passing a set of coordinates to this method.
* Note: The lines will only exist between the two points passed.
*
* @method lineSegmentToRawSegment
* @param line {Kiwi.Geom.Line} The line object that extends infinitely through space.
* @param x1 {number} The x coordinate of the first point in the second line.
* @param y1 {number} The y coordinate of the first point in the second line.
* @param x2 {number} The x coordinate of the second point in the second line.
* @param y2 {number} The y coordinate of the second point in the second line.
* @param [output] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection in x/y
* @static
* @public
*/
static lineSegmentToRawSegment(line: Line, x1: number, y1: number, x2: number, y2: number, output: IntersectResult = new IntersectResult): IntersectResult {
// Determine whether the line intersects the raw segment
output = Intersect.lineToRawSegment( line, x1, y1, x2, y2, output );
// Determine whether the intersection point is within the line segment
var maxX = Math.max( line.x1, line.x2 );
var minX = Math.min( line.x1, line.x2 );
var maxY = Math.max( line.y1, line.y2 );
var minY = Math.min( line.y1, line.y2 );
if ( output.x <= maxX && output.x >= minX && output.y <= maxY && output.y >= minY ) {
return output;
}
// Intersection point isn't within the line segment
output.result = false;
return output;
}
/**
* Checks to see if a Line and Ray object intersects at any point.
* Note: The line in this case extends infinately through space.
*
* @method lineToRay
* @param line1 {Kiwi.Geom.Line} The Line object that extends infinatly through space.
* @param ray {Kiwi.Geom.Ray} The Ray object that you want to check it against.
* @param [output] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection in x/y
* @public
* @static
*/
static lineToRay(line1: Line, ray: Ray, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
var denom = (line1.x1 - line1.x2) * (ray.y1 - ray.y2) - (line1.y1 - line1.y2) * (ray.x1 - ray.x2);
if (denom !== 0)
{
output.x = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (ray.x1 - ray.x2) - (line1.x1 - line1.x2) * (ray.x1 * ray.y2 - ray.y1 * ray.x2)) / denom;
output.y = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (ray.y1 - ray.y2) - (line1.y1 - line1.y2) * (ray.x1 * ray.y2 - ray.y1 * ray.x2)) / denom;
output.result = true; // true unless either of the 2 following conditions are met
if (!(ray.x1 >= ray.x2) && output.x < ray.x1)
{
output.result = false;
}
if (!(ray.y1 >= ray.y2) && output.y < ray.y1)
{
output.result = false;
}
}
return output;
}
/**
* Checks to see if a Line and a Circle intersect at any point.
* Note: The line passed is assumed to extend infinately through space.
*
* @method lineToCircle
* @param line {Kiwi.Geom.Line} The Line object that you want to check it against.
* @param circle {Kiwi.Geom.Circle} The Circle object to check.
* @param [output] {IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection
* @public
* @static
*/
static lineToCircle(line: Line, circle: Circle, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
// Get a perpendicular line running to the center of the circle
if (line.perp(circle.x, circle.y).length <= circle.radius)
{
output.result = true;
}
return output;
}
/**
* Check if the Line intersects with each side of a Rectangle.
* Note: The Line is assumned to extend infinately through space.
*
* @method lineToRectangle
* @param line {Kiwi.Geom.Line} The Line object to check
* @param rectangle {Kiwi.Geom.Rectangle} The Rectangle object to check
* @param [output] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection
* @public
* @static
*/
static lineToRectangle(line: any, rect: Rectangle, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
// Top of the Rectangle vs the Line
Intersect.lineToRawSegment(line, rect.x, rect.y, rect.right, rect.y, output);
if (output.result === true)
{
return output;
}
// Left of the Rectangle vs the Line
Intersect.lineToRawSegment(line, rect.x, rect.y, rect.x, rect.bottom, output);
if (output.result === true)
{
return output;
}
// Bottom of the Rectangle vs the Line
Intersect.lineToRawSegment(line, rect.x, rect.bottom, rect.right, rect.bottom, output);
if (output.result === true)
{
return output;
}
// Right of the Rectangle vs the Line
Intersect.lineToRawSegment(line, rect.right, rect.y, rect.right, rect.bottom, output);
return output;
}
/**
* ---------------------------------------------------------------------
* Line Segment
* ---------------------------------------------------------------------
**/
/**
* Checks to see if two Line Segments intersect at any point in space.
* Note: Both lines are treated as if they only exist between their two
* line coordinates.
*
* @method lineSegmentToLineSegment
* @param line1 {Kiwi.Geom.Line} The first line object to check.
* @param line2 {Kiwi.Geom.Line} The second line object to check.
* @param [output]{Kiwi.Geom.IntersectResult} An optional
IntersectResult object to store the intersection values in.
One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object
containing the results of this intersection in x/y.
* @public
* @static
*/
static lineSegmentToLineSegment(line1: Line, line2: Line, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
Intersect.lineToLineSegment( line1, line2, output );
if ( output.result === true ) {
if ( !( output.x >= Math.min( line1.x1, line1.x2 ) &&
output.x <= Math.max( line1.x1, line1.x2 ) &&
output.y >= Math.min( line1.y1, line1.y2 ) &&
output.y <= Math.max( line1.y1, line1.y2 ) ) ) {
output.result = false;
}
}
return output;
}
/**
* Check if the Line Segment intersects with the Ray.
* Note: The Line only exists between its two points.
*
* @method lineSegmentToRay
* @param line1 {Kiwi.Geom.Line} The Line object to check.
* @param ray {Kiwi.Geom.Line} The Ray object to check.
* @param [output] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection in x/y
* @public
* @static
*/
static lineSegmentToRay(line1: Line, ray: Ray, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
Intersect.lineToRay(line1, ray, output);
if (output.result === true)
{
if (!(output.x >= Math.min(line1.x1, line1.x2) && output.x <= Math.max(line1.x1, line1.x2)
&& output.y >= Math.min(line1.y1, line1.y2) && output.y <= Math.max(line1.y1, line1.y2)))
{
output.result = false;
}
}
return output;
}
/**
* Check if the Line Segment intersects with the Circle.
* Note the Line only exists between its point points.
*
* @method lineSegmentToCircle
* @param seg {Kiwi.Geom.Line} The Line object to check
* @param circle {Kiwi.Geom.Circle} The Circle object to check
* @param [ouput] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection in x/y
* @public
* @static
*/
static lineSegmentToCircle(seg: Line, circle: Circle, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
var perp = seg.perp(circle.x, circle.y);
if ( perp.length <= circle.radius ) {
// Line intersects circle - check if segment does
var maxX = Math.max(seg.x1, seg.x2);
var minX = Math.min(seg.x1, seg.x2);
var maxY = Math.max(seg.y1, seg.y2);
var minY = Math.min(seg.y1, seg.y2);
if ((perp.x2 <= maxX && perp.x2 >= minX) && (perp.y2 <= maxY && perp.y2 >= minY)) {
output.result = true;
} else {
// Worst case - segment doesn't traverse center, so no perpendicular connection.
if ( Intersect.circleContainsPoint(
circle, <Point> { x: seg.x1, y: seg.y1 } ).result ||
Intersect.circleContainsPoint(
circle, <Point> { x: seg.x2, y: seg.y2 } ).result ) {
output.result = true;
}
}
}
return output;
}
/**
* Check if the Line Segment intersects with any side of a Rectangle,
* or is entirely within the Rectangle.
* Note: The Line only exists between its two points.
*
* @method lineSegmentToRectangle
* @param seg {Kiwi.Geom.Line} The Line object to check.
* @param rect {Kiwi.Geom.Rectangle} The Rectangle object to check.
* @param [output] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection in x/y.
* @public
* @static
*/
static lineSegmentToRectangle(seg: Line, rect: Rectangle, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
if ( rect.contains( seg.x1, seg.y1 ) && rect.contains( seg.x2, seg.y2 ) ) {
// Rectangle completely encloses Line; report back line centroid
output.x = ( seg.x1 + seg.x2 ) / 2;
output.y = ( seg.y1 + seg.y2 ) / 2;
output.result = true;
} else {
// Top of the Rectangle vs the Line
Intersect.lineSegmentToRawSegment(seg, rect.x, rect.y, rect.right, rect.y, output);
if (output.result === true) {
return output;
}
// Left of the Rectangle vs the Line
Intersect.lineSegmentToRawSegment(seg, rect.x, rect.y, rect.x, rect.bottom, output);
if (output.result === true) {
return output;
}
// Bottom of the Rectangle vs the Line
Intersect.lineSegmentToRawSegment(seg, rect.x, rect.bottom, rect.right, rect.bottom, output);
if (output.result === true) {
return output;
}
// Right of the Rectangle vs the Line
Intersect.lineSegmentToRawSegment(seg, rect.right, rect.y, rect.right, rect.bottom, output);
}
return output;
}
/**
* -------------------------------------------------------------------------------------------
* Ray
* -------------------------------------------------------------------------------------------
**/
/**
* Check to see if a Ray intersects at any point with a Circle.
*
* @method rayToCircle
* @param ray {Kiwi.Geom.Ray} Ray object to check
* @param circle {Kiwi.Geom.Circle} Circle object to check
* @param [output] {Kiwi.Geom.IntersectResult} Optional object
* to store the intersection values. Created if not supplied.
* @return {Kiwi.Geom.IntersectResult} Results of this intersection
* @public
* @static
*/
static rayToCircle( ray: Ray, circle: Circle, output: IntersectResult = new IntersectResult ): IntersectResult {
var dx = circle.x - ray.x1,
dy = circle.y - ray.y1;
output.result = false;
// Does the Ray begin within the Circle?
if ( Math.sqrt( dx * dx + dy * dy ) <= circle.radius ) {
output.result = true;
return output;
}
// Is the Ray aiming towards the Circle?
if ( Math.abs( Kiwi.Utils.GameMath.nearestAngleBetween(
ray.angle, Math.atan2( dy, dx ) ) ) >= Math.PI / 2 ) {
return output;
}
// Inefficient, but the quickest way to get Line functions on a Ray
Intersect.lineToCircle( ray, circle, output );
return output;
}
/**
* Check to see if a Ray intersects at any point with a Rectangle.
*
* @method rayToRectangle
* @param ray {Kiwi.Geom.Ray} The Ray object to check.
* @param rect {Kiwi.Geom.Rectangle} The Rectangle to check.
* @param [output] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection
* @public
* @static
*/
static rayToRectangle(ray: Ray, rect: Rectangle, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
// Currently just finds first intersection - might not be closest to ray pt1
Intersect.lineToRectangle(ray, rect, output);
return output;
}
/**
* Check whether a Ray intersects a Line segment, returns the parametric value where the intersection occurs.
* Note: The Line only exists between its two points.
*
* @method rayToLineSegment
* @static
* @param rayx1 {Number} The origin point of the ray on the x axis.
* @param rayy1 {Number} The origin point of the ray on the y axis.
* @param rayx2 {Number} The direction of the ray on the x axis.
* @param rayy2 {Number} The direction of the ray on the y axis.
* @param linex1 {Number} The x of the first point of the line segment.
* @param liney1 {Number} The y of the first point of the line segment.
* @param linex2 {Number} The x of the second point of the line segment.
* @param liney2 {Number} The y of the second point of the line segment.
* @param [output] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection stored in x
* @public
*/
static rayToLineSegment(rayx1, rayy1, rayx2, rayy2, linex1, liney1, linex2, liney2, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
var r, s, d;
// Check lines are not parallel
if ((rayy2 - rayy1) / (rayx2 - rayx1) != (liney2 - liney1) / (linex2 - linex1))
{
d = (((rayx2 - rayx1) * (liney2 - liney1)) - (rayy2 - rayy1) * (linex2 - linex1));
if (d != 0)
{
r = (((rayy1 - liney1) * (linex2 - linex1)) - (rayx1 - linex1) * (liney2 - liney1)) / d;
s = (((rayy1 - liney1) * (rayx2 - rayx1)) - (rayx1 - linex1) * (rayy2 - rayy1)) / d;
if (r >= 0)
{
if (s >= 0 && s <= 1)
{
output.result = true;
output.x = rayx1 + r * (rayx2 - rayx1), rayy1 + r * (rayy2 - rayy1);
}
}
}
}
return output;
}
/**
* -------------------------------------------------------------------------------------------
* Circle
* -------------------------------------------------------------------------------------------
**/
/**
* Check if the two given Circle objects intersect at any point.
*
* @method circleToCircle
* @param circle1 {Kiwi.Geom.Circle} The first circle object to check.
* @param circle2 {Kiwi.Geom.Circle} The second circle object to check.
* @param [output] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection
* @public
* @static
*/
static circleToCircle(circle1: Circle, circle2: Circle, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
output.result = ((circle1.radius + circle2.radius) * (circle1.radius + circle2.radius)) >= Intersect.distanceSquared(circle1.x, circle1.y, circle2.x, circle2.y);
return output;
}
/**
* Check if a Circle and a Rectangle intersect with each other at any point.
*
* @method circleToRectangle
* @param circle {Kiwi.Geom.Circle} The circle object to check.
* @param rect {Kiwi.Geom.Rectangle} The Rectangle object to check.
* @param [output] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection
* @public
* @static
*/
static circleToRectangle(circle: Circle, rect: Rectangle, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
var cornerDistX, cornerDistY,
circleRelativeX, circleRelativeY,
halfRectWidth, halfRectHeight,
rectRangeX, rectRangeY;
// If circle is not in the rect X range, it can't overlap.
halfRectWidth = rect.width / 2;
circleRelativeX = Math.abs( circle.x - rect.x - halfRectWidth );
rectRangeX = circle.radius + halfRectWidth;
if ( circleRelativeX > rectRangeX ) {
output.result = false;
return output;
}
// If circle is not in the rect Y range, it can't overlap.
halfRectHeight = rect.height / 2;
circleRelativeY = Math.abs( circle.y - rect.y - halfRectHeight );
rectRangeY = circle.radius + halfRectHeight;
if ( circleRelativeY > rectRangeY ) {
output.result = false;
return output;
}
// If circle centroid is within the rect, it overlaps.
if ( circleRelativeX <= halfRectWidth ||
circleRelativeY <= rect.height / 2 ) {
output.result = true;
return output;
}
// Because relative coordinates are normalized, we can consider
// a single ideal corner. If the circle centroid is within its
// own radius of this ideal corner, it overlaps.
cornerDistX = circleRelativeX - halfRectWidth;
cornerDistY = circleRelativeY - halfRectHeight;
output.result = cornerDistX * cornerDistX + cornerDistY * cornerDistY <=
circle.radius * circle.radius;
return output;
}
/**
* Check if the given Point is found within the given Circle.
*
* @method circleContainsPoint
* @param circle {Kiwi.Geom.Circle} The circle object to check
* @param point {Kiwi.Geom.Point} The point object to check
* @param [output] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection
* @public
* @static
*/
static circleContainsPoint(circle: Circle, point: Point, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
output.result = circle.radius * circle.radius >= Intersect.distanceSquared(circle.x, circle.y, point.x, point.y);
return output;
}
/**
* -------------------------------------------------------------------------------------------
* Rectangles
* -------------------------------------------------------------------------------------------
**/
/**
* Determines whether the specified point is contained within a given Rectangle object.
*
* @method pointToRectangle
* @param point {Kiwi.Geom.Point} The point object being checked.
* @param rect {Kiwi.Geom.Rectangle} The rectangle object being checked.
* @param [output] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection in x/y/result
* @public
* @static
*/
static pointToRectangle(point: Point, rect: Rectangle, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
output.setTo(point.x, point.y);
output.result = rect.containsPoint(point);
return output;
}
/**
* Check whether two axis aligned rectangles intersect. Return the intersecting rectangle dimensions if they do.
*
* @method rectangleToRectangle
* @param rect1 {Kiwi.Geom.Rectangle} The first Rectangle object.
* @param rect2 {Kiwi.Geom.Rectangle} The second Rectangle object.
* @param [output] {Kiwi.Geom.IntersectResult} An optional IntersectResult object to store the intersection values in. One is created if none given.
* @return {Kiwi.Geom.IntersectResult} An IntersectResult object containing the results of this intersection in x/y/width/height
* @public
* @static
*/
static rectangleToRectangle(rect1: Rectangle, rect2: Rectangle, output: IntersectResult = new IntersectResult): IntersectResult {
output.result = false;
var leftX = Math.max(rect1.x, rect2.x);
var rightX = Math.min(rect1.right, rect2.right);
var topY = Math.max(rect1.y, rect2.y);
var bottomY = Math.min(rect1.bottom, rect2.bottom);
output.setTo(leftX, topY, rightX - leftX, bottomY - topY, rightX - leftX, bottomY - topY);
var cx = output.x + output.width * .5;
var cy = output.y + output.height * .5;
if ((cx > rect1.x && cx < rect1.right) && (cy > rect1.y && cy < rect1.bottom))
{
output.result = true;
}
return output;
}
}
} | the_stack |
import 'chrome://resources/cr_elements/md_select_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';
import '../settings_shared_css.js';
import '../settings_vars_css.js';
import '../i18n_setup.js';
import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js';
import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js';
import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {ContentSetting, ContentSettingsTypes, SiteSettingSource} from './constants.js';
import {SiteSettingsMixin} from './site_settings_mixin.js';
import {RawSiteException} from './site_settings_prefs_browser_proxy.js';
export interface SiteDetailsPermissionElement {
$: {
details: HTMLElement,
permission: HTMLSelectElement,
permissionItem: HTMLElement,
permissionSecondary: HTMLElement,
};
}
const SiteDetailsPermissionElementBase =
SiteSettingsMixin(WebUIListenerMixin(I18nMixin(PolymerElement)));
export class SiteDetailsPermissionElement extends
SiteDetailsPermissionElementBase {
static get is() {
return 'site-details-permission';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* If this is a sound content setting, then this controls whether it
* should use "Automatic" instead of "Allow" as the default setting
* allow label.
*/
useAutomaticLabel: {type: Boolean, value: false},
/**
* The site that this widget is showing details for, or null if this
* widget should be hidden.
*/
site: Object,
/**
* The default setting for this permission category.
*/
defaultSetting_: String,
label: String,
icon: String,
/**
* Expose ContentSetting enum to HTML bindings.
*/
contentSettingEnum_: {
type: Object,
value: ContentSetting,
},
};
}
static get observers() {
return ['siteChanged_(site)'];
}
useAutomaticLabel: boolean;
site: RawSiteException;
private defaultSetting_: ContentSetting;
label: string;
icon: string;
connectedCallback() {
super.connectedCallback();
this.addWebUIListener(
'contentSettingCategoryChanged',
(category: ContentSettingsTypes) =>
this.onDefaultSettingChanged_(category));
}
/**
* Updates the drop-down value after |site| has changed. If |site| is null,
* this element will hide.
* @param site The site to display.
*/
private siteChanged_(site: RawSiteException|null) {
if (!site) {
return;
}
if (site.source === SiteSettingSource.DEFAULT) {
this.defaultSetting_ = site.setting;
this.$.permission.value = ContentSetting.DEFAULT;
} else {
// The default setting is unknown, so consult the C++ backend for it.
this.updateDefaultPermission_();
this.$.permission.value = site.setting;
}
if (this.isNonDefaultAsk_(site.setting, site.source)) {
assert(
this.$.permission.value === ContentSetting.ASK,
'\'Ask\' should only show up when it\'s currently selected.');
}
}
/**
* Updates the default permission setting for this permission category.
*/
private updateDefaultPermission_() {
this.browserProxy.getDefaultValueForContentType(this.category)
.then((defaultValue) => {
this.defaultSetting_ = defaultValue.setting;
});
}
/**
* Handles the category permission changing for this origin.
* @param category The permission category that has changed default
* permission.
*/
private onDefaultSettingChanged_(category: ContentSettingsTypes) {
if (category === this.category) {
this.updateDefaultPermission_();
}
}
/**
* Handles the category permission changing for this origin.
*/
private onPermissionSelectionChange_() {
this.browserProxy.setOriginPermissions(
this.site.origin, this.category,
this.$.permission.value as ContentSetting);
}
/**
* @param category The permission type.
* @return if we should use the custom labels for the sound type.
*/
private useCustomSoundLabels_(category: ContentSettingsTypes): boolean {
return category === ContentSettingsTypes.SOUND;
}
/**
* Updates the string used for this permission category's default setting.
* @param defaultSetting Value of the default setting for this permission
* category.
* @param category The permission type.
* @param useAutomaticLabel Whether to use the automatic label if the default
* setting value is allow.
*/
private defaultSettingString_(
defaultSetting: ContentSetting, category: ContentSettingsTypes,
useAutomaticLabel: boolean): string {
if (defaultSetting === undefined || category === undefined ||
useAutomaticLabel === undefined) {
return '';
}
if (defaultSetting === ContentSetting.ASK ||
defaultSetting === ContentSetting.IMPORTANT_CONTENT) {
return this.i18n('siteSettingsActionAskDefault');
} else if (defaultSetting === ContentSetting.ALLOW) {
if (this.useCustomSoundLabels_(category) && useAutomaticLabel) {
return this.i18n('siteSettingsActionAutomaticDefault');
}
return this.i18n('siteSettingsActionAllowDefault');
} else if (defaultSetting === ContentSetting.BLOCK) {
if (this.useCustomSoundLabels_(category)) {
return this.i18n('siteSettingsActionMuteDefault');
}
return this.i18n('siteSettingsActionBlockDefault');
}
assertNotReached(
`No string for ${this.category}'s default of ${defaultSetting}`);
return '';
}
/**
* Updates the string used for this permission category's block setting.
* @param category The permission type.
* @param blockString 'Block' label.
* @param muteString 'Mute' label.
*/
private blockSettingString_(
category: ContentSettingsTypes, blockString: string,
muteString: string): string {
if (this.useCustomSoundLabels_(category)) {
return muteString;
}
return blockString;
}
/**
* @return true if |this| should be hidden.
*/
private shouldHideCategory_() {
return !this.site;
}
/**
* Returns true if there's a string to display that provides more information
* about this permission's setting. Currently, this only gets called when
* |this.site| is updated.
* @param source The source of the permission.
* @param category The permission type.
* @param setting The permission setting.
* @return Whether the permission will have a source string to display.
*/
private hasPermissionInfoString_(
source: SiteSettingSource, category: ContentSettingsTypes,
setting: ContentSetting): boolean {
// This method assumes that an empty string will be returned for categories
// that have no permission info string.
return this.permissionInfoString_(
source, category, setting,
// Set all permission info string arguments as null. This is OK
// because there is no need to know what the information string
// will be, just whether there is one or not.
null, null, null, null, null, null, null, null, null, null, null,
null) !== '';
}
/**
* Checks if there's a additional information to display, and returns the
* class name to apply to permissions if so.
* @param source The source of the permission.
* @param category The permission type.
* @param setting The permission setting.
* @return CSS class applied when there is an additional description string.
*/
private permissionInfoStringClass_(
source: SiteSettingSource, category: ContentSettingsTypes,
setting: ContentSetting): string {
return this.hasPermissionInfoString_(source, category, setting) ?
'two-line' :
'';
}
/**
* @param source The source of the permission.
* @return Whether this permission can be controlled by the user.
*/
private isPermissionUserControlled_(source: SiteSettingSource): boolean {
return !(
source === SiteSettingSource.ALLOWLIST ||
source === SiteSettingSource.POLICY ||
source === SiteSettingSource.EXTENSION ||
source === SiteSettingSource.KILL_SWITCH ||
source === SiteSettingSource.INSECURE_ORIGIN);
}
/**
* @param category The permission type.
* @return Whether if the 'allow' option should be shown.
*/
private showAllowedSetting_(category: ContentSettingsTypes) {
return !(
category === ContentSettingsTypes.SERIAL_PORTS ||
category === ContentSettingsTypes.USB_DEVICES ||
category === ContentSettingsTypes.BLUETOOTH_SCANNING ||
category === ContentSettingsTypes.FILE_SYSTEM_WRITE ||
category === ContentSettingsTypes.HID_DEVICES ||
category === ContentSettingsTypes.BLUETOOTH_DEVICES);
}
/**
* @param category The permission type.
* @param setting The setting of the permission.
* @param source The source of the permission.
* @return Whether the 'ask' option should be shown.
*/
private showAskSetting_(
category: ContentSettingsTypes, setting: ContentSetting,
source: SiteSettingSource): boolean {
// For chooser-based permissions 'ask' takes the place of 'allow'.
if (category === ContentSettingsTypes.SERIAL_PORTS ||
category === ContentSettingsTypes.USB_DEVICES ||
category === ContentSettingsTypes.HID_DEVICES ||
category === ContentSettingsTypes.BLUETOOTH_DEVICES) {
return true;
}
// For Bluetooth scanning permission and File System write permission
// 'ask' takes the place of 'allow'.
if (category === ContentSettingsTypes.BLUETOOTH_SCANNING ||
category === ContentSettingsTypes.FILE_SYSTEM_WRITE) {
return true;
}
return this.isNonDefaultAsk_(setting, source);
}
/**
* Returns true if the permission is set to a non-default 'ask'. Currently,
* this only gets called when |this.site| is updated.
* @param setting The setting of the permission.
* @param source The source of the permission.
*/
private isNonDefaultAsk_(setting: ContentSetting, source: SiteSettingSource) {
if (setting !== ContentSetting.ASK ||
source === SiteSettingSource.DEFAULT) {
return false;
}
assert(
source === SiteSettingSource.EXTENSION ||
source === SiteSettingSource.POLICY ||
source === SiteSettingSource.PREFERENCE,
'Only extensions, enterprise policy or preferences can change ' +
'the setting to ASK.');
return true;
}
/**
* Updates the information string for the current permission.
* Currently, this only gets called when |this.site| is updated.
* @param source The source of the permission.
* @param category The permission type.
* @param setting The permission setting.
* @param allowlistString The string to show if the permission is
* allowlisted.
* @param adsBlacklistString The string to show if the site is
* blacklisted for showing bad ads.
* @param adsBlockString The string to show if ads are blocked, but
* the site is not blacklisted.
* @return The permission information string to display in the HTML.
*/
private permissionInfoString_(
source: SiteSettingSource, category: ContentSettingsTypes,
setting: ContentSetting, allowlistString: string|null,
adsBlacklistString: string|null, adsBlockString: string|null,
embargoString: string|null, insecureOriginString: string|null,
killSwitchString: string|null, extensionAllowString: string|null,
extensionBlockString: string|null, extensionAskString: string|null,
policyAllowString: string|null, policyBlockString: string|null,
policyAskString: string|null): (string|null) {
if (source === undefined || category === undefined ||
setting === undefined) {
return null;
}
const extensionStrings: {[key: string]: string|null} = {};
extensionStrings[ContentSetting.ALLOW] = extensionAllowString;
extensionStrings[ContentSetting.BLOCK] = extensionBlockString;
extensionStrings[ContentSetting.ASK] = extensionAskString;
const policyStrings: {[key: string]: string|null} = {};
policyStrings[ContentSetting.ALLOW] = policyAllowString;
policyStrings[ContentSetting.BLOCK] = policyBlockString;
policyStrings[ContentSetting.ASK] = policyAskString;
if (source === SiteSettingSource.ALLOWLIST) {
return allowlistString;
} else if (source === SiteSettingSource.ADS_FILTER_BLACKLIST) {
assert(
ContentSettingsTypes.ADS === category,
'The ads filter blacklist only applies to Ads.');
return adsBlacklistString;
} else if (
category === ContentSettingsTypes.ADS &&
setting === ContentSetting.BLOCK) {
return adsBlockString;
} else if (source === SiteSettingSource.EMBARGO) {
assert(
ContentSetting.BLOCK === setting,
'Embargo is only used to block permissions.');
return embargoString;
} else if (source === SiteSettingSource.EXTENSION) {
return extensionStrings[setting];
} else if (source === SiteSettingSource.INSECURE_ORIGIN) {
assert(
ContentSetting.BLOCK === setting,
'Permissions can only be blocked due to insecure origins.');
return insecureOriginString;
} else if (source === SiteSettingSource.KILL_SWITCH) {
assert(
ContentSetting.BLOCK === setting,
'The permissions kill switch can only be used to block permissions.');
return killSwitchString;
} else if (source === SiteSettingSource.POLICY) {
return policyStrings[setting];
} else if (
source === SiteSettingSource.DEFAULT ||
source === SiteSettingSource.PREFERENCE) {
return '';
}
assertNotReached(`No string for ${category} setting source '${source}'`);
return '';
}
}
declare global {
interface HTMLElementTagNameMap {
'site-details-permission': SiteDetailsPermissionElement;
}
}
customElements.define(
SiteDetailsPermissionElement.is, SiteDetailsPermissionElement); | the_stack |
import dispatcher from "../dispatcher";
import { File, Directory, Project } from "../models";
import { Template } from "../components/NewProjectDialog";
import { View, ViewType } from "../components/editor/View";
import appStore from "../stores/AppStore";
import { Service } from "../service";
import Group from "../utils/group";
import { Errors } from "../errors";
import { runTask as runGulpTask, RunTaskExternals } from "../utils/taskRunner";
import getConfig from "../config";
import { KeyPair } from "nearlib";
import { gaEvent } from "../utils/ga";
export enum AppActionType {
ADD_FILE_TO = "ADD_FILE_TO",
LOAD_PROJECT = "LOAD_PROJECT",
CLEAR_PROJECT_MODIFIED = "CLEAR_PROJECT_MODIFIED",
INIT_STORE = "INIT_STORE",
UPDATE_FILE_NAME_AND_DESCRIPTION = "UPDATE_FILE_NAME_AND_DESCRIPTION",
DELETE_FILE = "DELETE_FILE",
SPLIT_GROUP = "SPLIT_GROUP",
SET_VIEW_TYPE = "SET_VIEW_TYPE",
OPEN_FILE = "OPEN_FILE",
OPEN_FILES = "OPEN_PROJECT_FILES",
FOCUS_TAB_GROUP = "FOCUS_TAB_GROUP",
LOG_LN = "LOG_LN",
CLEAR_LOG = "CLEAR_LOG",
PUSH_STATUS = "PUSH_STATUS",
POP_STATUS = "POP_STATUS",
SANDBOX_RUN = "SANDBOX_RUN",
CLOSE_VIEW = "CLOSE_VIEW",
CLOSE_TABS = "CLOSE_TABS",
OPEN_VIEW = "OPEN_VIEW",
}
export interface AppAction {
type: AppActionType;
}
export interface AddFileToAction extends AppAction {
type: AppActionType.ADD_FILE_TO;
file: File;
parent: Directory;
}
export function addFileTo(file: File, parent: Directory) {
dispatcher.dispatch({
type: AppActionType.ADD_FILE_TO,
file,
parent,
} as AddFileToAction);
}
export interface LoadProjectAction extends AppAction {
type: AppActionType.LOAD_PROJECT;
project: Project;
}
export function loadProject(project: Project) {
dispatcher.dispatch({
type: AppActionType.LOAD_PROJECT,
project,
} as LoadProjectAction);
}
export function initStore() {
dispatcher.dispatch({
type: AppActionType.INIT_STORE,
} as AppAction);
}
export interface UpdateFileNameAndDescriptionAction extends AppAction {
type: AppActionType.UPDATE_FILE_NAME_AND_DESCRIPTION;
file: File;
name: string;
description: string;
}
export function updateFileNameAndDescription(file: File, name: string, description: string) {
dispatcher.dispatch({
type: AppActionType.UPDATE_FILE_NAME_AND_DESCRIPTION,
file,
name,
description,
} as UpdateFileNameAndDescriptionAction);
}
export interface DeleteFileAction extends AppAction {
type: AppActionType.DELETE_FILE;
file: File;
}
export function deleteFile(file: File) {
dispatcher.dispatch({
type: AppActionType.DELETE_FILE,
file,
} as DeleteFileAction);
}
export interface LogLnAction extends AppAction {
type: AppActionType.LOG_LN;
message: string;
kind: ("" | "info" | "warn" | "error");
}
export type logKind = "" | "info" | "warn" | "error";
export function logLn(message: string, kind: logKind = "") {
dispatcher.dispatch({
type: AppActionType.LOG_LN,
message,
kind,
} as LogLnAction);
}
export interface ClearLogAction extends AppAction {
type: AppActionType.CLEAR_LOG;
}
export function clearLog() {
dispatcher.dispatch({
type: AppActionType.CLEAR_LOG,
} as ClearLogAction);
}
export interface SplitGroupAction extends AppAction {
type: AppActionType.SPLIT_GROUP;
}
export function splitGroup() {
dispatcher.dispatch({
type: AppActionType.SPLIT_GROUP
} as SplitGroupAction);
}
export interface OpenViewAction extends AppAction {
type: AppActionType.OPEN_VIEW;
view: View;
preview: boolean;
}
export function openView(view: View, preview = true) {
dispatcher.dispatch({
type: AppActionType.OPEN_VIEW,
view,
preview
} as OpenViewAction);
}
export interface CloseViewAction extends AppAction {
type: AppActionType.CLOSE_VIEW;
view: View;
}
export function closeView(view: View) {
dispatcher.dispatch({
type: AppActionType.CLOSE_VIEW,
view
} as CloseViewAction);
}
export interface CloseTabsAction extends AppAction {
type: AppActionType.CLOSE_TABS;
file: File;
}
export function closeTabs(file: File) {
dispatcher.dispatch({
type: AppActionType.CLOSE_TABS,
file
} as CloseTabsAction);
}
export interface OpenFileAction extends AppAction {
type: AppActionType.OPEN_FILE;
file: File;
viewType: ViewType;
preview: boolean;
// TODO: Add the location where the file should open.
}
export function openFile(file: File, type: ViewType = ViewType.Editor, preview = true) {
dispatcher.dispatch({
type: AppActionType.OPEN_FILE,
file,
viewType: type,
preview
} as OpenFileAction);
}
export function openFiles(files: string[][]) {
dispatcher.dispatch({
type: AppActionType.OPEN_FILES,
files
} as OpenFilesAction);
}
export interface OpenFilesAction extends AppAction {
type: AppActionType.OPEN_FILES;
files: string[][];
}
export async function openProjectFiles(template: Template) {
const newProject = new Project();
await Service.loadFilesIntoProject(template.files, newProject, template.baseUrl);
dispatcher.dispatch({
type: AppActionType.LOAD_PROJECT,
project: newProject
} as LoadProjectAction);
if (newProject.getFile("README.md")) {
openFiles([["README.md"]]);
}
}
export async function saveProject(fiddle: string): Promise<string> {
const tabGroups = appStore.getTabGroups();
const projectModel = appStore.getProject().getModel();
const openedFiles = tabGroups.map((group) => {
return group.views.map((view) => view.file.getPath());
});
pushStatus("Saving Project ...");
try {
const uri = await Service.saveProject(projectModel, openedFiles, fiddle);
dispatcher.dispatch({
type: AppActionType.CLEAR_PROJECT_MODIFIED,
} as AppAction);
return uri;
} finally {
popStatus();
}
}
export interface FocusTabGroupAction extends AppAction {
type: AppActionType.FOCUS_TAB_GROUP;
group: Group;
}
export function focusTabGroup(group: Group) {
dispatcher.dispatch({
type: AppActionType.FOCUS_TAB_GROUP,
group
} as FocusTabGroupAction);
}
export interface PushStatusAction extends AppAction {
type: AppActionType.PUSH_STATUS;
status: string;
}
export interface PopStatusAction extends AppAction {
type: AppActionType.POP_STATUS;
}
export function pushStatus(status: string) {
dispatcher.dispatch({
type: AppActionType.PUSH_STATUS,
status,
} as PushStatusAction);
}
export function popStatus() {
dispatcher.dispatch({
type: AppActionType.POP_STATUS,
} as PopStatusAction);
}
export async function runTask(
name: string,
optional: boolean = false,
externals: RunTaskExternals = RunTaskExternals.Default
) {
// Runs the provided source in our fantasy gulp context
const run = async (src: string) => {
const getProject = () => appStore.getProject().getModel();
return await runGulpTask(src, name, optional, getProject, logLn, externals);
};
let gulpfile = appStore.getFileByName("gulpfile.js");
if (gulpfile) {
return await run(appStore.getFileSource(gulpfile));
} else {
if (gulpfile = appStore.getFileByName("build.ts")) {
const output = await gulpfile.getModel().getEmitOutput();
return await run(output.outputFiles[0].text);
} else {
if (gulpfile = appStore.getFileByName("build.js")) {
return await run(appStore.getFileSource(gulpfile));
} else {
logLn(Errors.BuildFileMissing, "error");
return false;
}
}
}
}
async function deploy(contractName: string) {
const mainFileName = "out/main.wasm";
const projectModel = appStore.getProject().getModel();
await Service.deployContract(contractName, projectModel.getFile(mainFileName), this);
projectModel.getFile(mainFileName);
}
async function createAccountForContract(contractName: string) {
// TODO: Remove ugly hack with window
const app = (window as any).app;
let keyPair = await app.state.keyStore.getKey("default", contractName);
// if no keypair in keystore, it means the account does not exist.
// maybe there is a better way to check this?
if (!keyPair || !keyPair.getPublicKey()) {
keyPair = await KeyPair.fromRandom("ed25519");
await createAccount(contractName, keyPair.publicKey.toString());
app.state.keyStore.setKey("default", contractName, keyPair);
}
return keyPair;
}
async function reportError(error: any) {
console.error("Unexpected error:", error);
alert(`Unexpected error: ${error}`);
}
async function saveAll() {
try {
pushStatus("Saving Project");
const excludeTransient = true;
const recurse = true;
const dirtyFiles: File[] = [];
appStore.getProject().getModel().forEachFile(file => {
if (file.isDirty) {
dirtyFiles.push(file);
}
}, excludeTransient, recurse);
for (const file of dirtyFiles) {
await file.save({
push: pushStatus,
pop: popStatus,
logLn: logLn
});
}
} finally {
popStatus();
}
}
export async function deployAndRun(fiddleName: string, pageName: string = "", contractSuffix: string = "") {
gaEvent(pageName === "test.html" ? "deployAndTest" : "deployAndRun");
// TODO: Remove ugly hack with window
const app = (window as any).app;
if (await app.forkIfNeeded()) {
fiddleName = app.state.fiddle;
} else {
// User rejected fork
return;
}
pushStatus("Deploying Contract");
const config = await getConfig();
// NOTE: Page opened beforehand to avoid popup blocking
// TODO: Show something better than empty window, e.g. stream compiler output?
const page = window.open(`${config.pages}/${fiddleName}/loader.html`, "pageDevWindow");
try {
await saveAll();
clearLog();
if (await build()) {
const contractName = `studio-${fiddleName}${contractSuffix}`;
const keyPair = await createAccountForContract(contractName);
await deploy(contractName);
const queryString = contractSuffix ? `?contractName=${contractName}&privateKey=${keyPair}` : "";
if (page && !page.closed) {
page.location.replace(`${config.pages}/${fiddleName}/${pageName}${queryString}`);
}
} else if (page && !page.closed) {
page.close();
}
} catch (e) {
if (page && !page.closed) {
page.close();
}
reportError(e);
}
popStatus();
}
export async function build() {
pushStatus("Building Project");
const buildSucceeded = await runTask("build");
popStatus();
return buildSucceeded;
}
export interface SetViewType extends AppAction {
type: AppActionType.SET_VIEW_TYPE;
view: View;
viewType: ViewType;
}
export function setViewType(view: View, type: ViewType) {
dispatcher.dispatch({
type: AppActionType.SET_VIEW_TYPE,
view,
viewType: type
} as SetViewType);
}
export async function createAccount(newAccountId: string, newAccountKey: string) {
const createAccountResponse = await Service.createAccount(newAccountId, newAccountKey, this);
return createAccountResponse;
} | the_stack |
import { browser, element, by, protractor, $} from 'protractor';
import { Login } from '../page-objects/login.po';
import { OverviewCompliance } from '../page-objects/overview.po';
import { TaggingCompliance } from '../page-objects/tagging-compliance.po';
import { PolicyViolations } from '../page-objects/policy-violations.po';
import { VulnerabilityCompliance } from '../page-objects/vulnerability-compliance.po';
import { PatchingCompliance } from '../page-objects/patching-compliance.po';
import { CertificateCompliance } from '../page-objects/certificate-compliance.po';
import { CompliancePolicy } from '../page-objects/compliance-policy.po';
import { CONFIGURATIONS } from '../../src/config/configurations';
const timeOutHigh = 180000;
const emailId = CONFIGURATIONS.optional.general.e2e.EMAIL_ID;
describe('Overview', () => {
let login_po: Login;
let OverviewCompliance_po: OverviewCompliance;
let taggingcompliance_po: TaggingCompliance;
let policyviolations_po: PolicyViolations;
let vulnerabilitycompliance_po: VulnerabilityCompliance;
let patchingcompliance_po: PatchingCompliance;
let certificatecompliance_po: CertificateCompliance;
let CompliancePolicy_po: CompliancePolicy;
const EC = protractor.ExpectedConditions;
let tagging_count;
let vuln_count;
let patch_count;
let cert_count;
let violation_count;
let critical_violation_count;
let Temp;
beforeAll(() => {
login_po = new Login();
OverviewCompliance_po = new OverviewCompliance();
taggingcompliance_po = new TaggingCompliance();
policyviolations_po = new PolicyViolations();
vulnerabilitycompliance_po = new VulnerabilityCompliance();
certificatecompliance_po = new CertificateCompliance();
patchingcompliance_po = new PatchingCompliance();
CompliancePolicy_po = new CompliancePolicy();
});
it('Verify Tagging count in Overall Compliance', () => {
browser.wait(EC.visibilityOf(OverviewCompliance_po.getTaggingClick()), timeOutHigh);
tagging_count = OverviewCompliance_po.getTaggingClick().getText();
element(by.xpath('//app-compliance/div/div/div[1]/app-contextual-menu/div/ul/li[3]')).click();
browser.wait(EC.visibilityOf(taggingcompliance_po.getOverallunTagging()), timeOutHigh);
Temp = taggingcompliance_po.getOverallunTagging().getText().then(function (text) {
text = text.replace(/,/g, '');
expect(text).toEqual(tagging_count);
browser.wait(EC.visibilityOf(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
OverviewCompliance_po.navigateToOverviewCompliance().click();
});
});
it('Verify Vulnerability count in Overall Compliance', () => {
browser.wait(EC.visibilityOf(OverviewCompliance_po.getVulnerabilitiesClick()), timeOutHigh);
vuln_count = OverviewCompliance_po.getVulnerabilitiesClick().getText();
element(by.xpath('//app-compliance/div/div/div[1]/app-contextual-menu/div/ul/li[2]')).click();
browser.wait(EC.visibilityOf(vulnerabilitycompliance_po.getOverallVulnerabilities()), timeOutHigh);
Temp = vulnerabilitycompliance_po.getOverallVulnerabilities().getText().then(function (text) {
text = text.replace(/,/g, '');
expect(text).toEqual(vuln_count);
browser.wait(EC.visibilityOf(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
OverviewCompliance_po.navigateToOverviewCompliance().click();
});
});
it('Verify Certificate count in Overall Compliance', () => {
browser.wait(EC.visibilityOf(OverviewCompliance_po.getCertificateTotalClick()), timeOutHigh);
OverviewCompliance_po.getCertificateTotalClick().getText().then(function (text) {
text = text.replace(/[a-zA-Z ]/g, '');
cert_count = text;
});
const elm = OverviewCompliance_po.getCertificateTotalClick();
browser.executeScript('arguments[0].scrollIntoView();', elm.getWebElement());
browser.actions().mouseMove(OverviewCompliance_po.getCertificateTotalClick()).perform();
element(by.xpath('//app-compliance/div/div/div[1]/app-contextual-menu/div/ul/li[4]')).click();
browser.wait(EC.visibilityOf(certificatecompliance_po.getOverallcertificate()), timeOutHigh);
Temp = certificatecompliance_po.getOverallcertificate().getText().then(function (text) {
text = text.replace(/,/g, '');
expect(cert_count).toContain(text);
browser.wait(EC.visibilityOf(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
OverviewCompliance_po.navigateToOverviewCompliance().click();
});
});
it('Verify Patching count in Overall Compliance', () => {
browser.wait(EC.visibilityOf(OverviewCompliance_po.getPatchingClick()), timeOutHigh);
patch_count = OverviewCompliance_po.getPatchingClick().getText();
element(by.xpath('//app-compliance/div/div/div[1]/app-contextual-menu/div/ul/li[5]')).click();
browser.wait(EC.visibilityOf(patchingcompliance_po.getUnPatching()), timeOutHigh);
Temp = patchingcompliance_po.getUnPatching().getText().then(function (text) {
text = text.replace(/,/g, '');
expect(text).toEqual(patch_count);
});
browser.wait(EC.visibilityOf(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
OverviewCompliance_po.navigateToOverviewCompliance().click();
});
it('Verify Total Violations count in Overall Compliance', () => {
browser.wait(EC.presenceOf(OverviewCompliance_po.getTotalViolations()), timeOutHigh);
violation_count = OverviewCompliance_po.getTotalViolations().getText();
browser.actions().mouseMove(OverviewCompliance_po.getTotalViolations()).perform();
browser.actions().click(protractor.Button.LEFT).perform();
browser.wait(EC.visibilityOf(policyviolations_po.getpolicyviolationscount()), timeOutHigh);
Temp = policyviolations_po.getpolicyviolationscount().getText();
expect(Temp).toEqual(violation_count);
browser.wait(EC.visibilityOf(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
OverviewCompliance_po.navigateToOverviewCompliance().click();
});
it('Verify Critical Violations count in Overall Compliance', () => {
browser.wait(EC.presenceOf(OverviewCompliance_po.getTotalCriticalViolations()), timeOutHigh);
critical_violation_count = OverviewCompliance_po.getTotalCriticalViolations().getText();
browser.actions().mouseMove(OverviewCompliance_po.getTotalCriticalViolations()).perform();
browser.actions().click(protractor.Button.LEFT).perform();
browser.wait(EC.visibilityOf(policyviolations_po.getpolicyviolationscount()), timeOutHigh);
Temp = policyviolations_po.getpolicyviolationscount().getText();
expect(Temp).toEqual(critical_violation_count);
browser.wait(EC.visibilityOf(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
OverviewCompliance_po.navigateToOverviewCompliance().click();
});
it('Verify length of table rows in Overall Compliance equal to total length', () => {
browser.wait(EC.presenceOf( OverviewCompliance_po.getTotalDataTableCnt()), timeOutHigh);
const total_count = OverviewCompliance_po.getTotalDataTableCnt().getText();
const total_rows = OverviewCompliance_po.getNumberOfRows().count();
expect(total_count).toContain(total_rows);
});
it('Verify table tabs functionality', () => {
browser.wait(EC.presenceOf( OverviewCompliance_po.getTotalDataTableCnt()), timeOutHigh);
OverviewCompliance_po.getSecondTab().click();
const total_count = OverviewCompliance_po.getTotalDataTableCnt().getText();
const total_rows = OverviewCompliance_po.getNumberOfRows().count();
expect(total_count).toContain(total_rows);
OverviewCompliance_po.getFirstTab().click();
});
it('Verify search functionality', () => {
browser.wait(EC.presenceOf( OverviewCompliance_po.getPolicyName()), timeOutHigh);
OverviewCompliance_po.getSearchLabel().click();
browser.sleep(401);
browser.wait(EC.visibilityOf(OverviewCompliance_po.getSearchInput()), timeOutHigh);
OverviewCompliance_po.getSearchInput().sendKeys('amazon');
browser.actions().sendKeys(protractor.Key.ENTER).perform();
browser.wait(EC.presenceOf( OverviewCompliance_po.getPolicyName()), timeOutHigh);
OverviewCompliance_po.getFirstRowCell().getText().then(function (text) {
expect(text.toLowerCase()).toContain('amazon');
});
browser.sleep(401);
OverviewCompliance_po.getSearchInput().sendKeys('');
browser.actions().sendKeys(protractor.Key.ENTER).perform();
$('label.search-label img').click();
});
it('Redirect to Compliance details on click of policy name', () => {
browser.wait(EC.presenceOf( OverviewCompliance_po.getPolicyName()), timeOutHigh);
OverviewCompliance_po.getPolicyName().click();
const compliance_policy_title = CompliancePolicy_po.getTitle().getText();
expect(compliance_policy_title).toEqual('Policy Compliance');
browser.wait(EC.visibilityOf(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
OverviewCompliance_po.navigateToOverviewCompliance().click();
});
it('Verify help text modal is opening', () => {
browser.wait(EC.visibilityOf( OverviewCompliance_po.openHelp()), timeOutHigh);
browser.wait(EC.elementToBeClickable( OverviewCompliance_po.openHelp()), timeOutHigh);
OverviewCompliance_po.openHelp().click();
browser.wait(EC.visibilityOf( OverviewCompliance_po.getHelpTitle()), timeOutHigh);
const help_title = OverviewCompliance_po.getHelpTitle().getText();
expect(help_title).toEqual('Help');
$('.help-text-modal .close-popup').click();
});
it('Check policy violations percentages sum to 100', () => {
const each_violation = OverviewCompliance_po.getPolicyViolationPercents();
let percent_total = 0;
each_violation.then(function(items){
for (let i = 0; i < items.length; i++) {
$('.enclosure-issue .flex.flex-align-center:nth-child(' + (1 + i) + ') .total-issues-text-issue').getText().then(function (text) {
percent_total = percent_total + parseInt(text, 10);
if ( i === items.length - 1) {
expect(percent_total).toEqual(100);
}
});
}
});
});
it('Check table sort functionality', () => {
browser.wait(EC.presenceOf( OverviewCompliance_po.getPolicyName()), timeOutHigh);
OverviewCompliance_po.policyTitleSort().click();
let first_row;
OverviewCompliance_po.getFirstRowCell().getText().then(function (text) {
first_row = text.toLowerCase();
});
let second_row;
OverviewCompliance_po.getSecondRowCell().getText().then(function (text) {
second_row = text.toLowerCase();
expect(first_row < second_row).toEqual(true);
});
});
it('Check table row compliance matches policy compliance summary', () => {
browser.wait(EC.presenceOf( OverviewCompliance_po.getPolicyName()), timeOutHigh);
let table_policy_compliance;
OverviewCompliance_po.getPolicyCompliancePercent().getText().then(function (text) {
table_policy_compliance = text;
});
OverviewCompliance_po.getPolicyName().click();
browser.wait(EC.presenceOf( CompliancePolicy_po.getPolicyCompliancePercent()), timeOutHigh);
const policy_percent = CompliancePolicy_po.getPolicyCompliancePercent().getText().then(function (text) {
text = text.replace(/ /g, '');
expect(text).toEqual(table_policy_compliance);
});
browser.wait(EC.visibilityOf(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
OverviewCompliance_po.navigateToOverviewCompliance().click();
});
it('Verify table tabs All total is sum of other tabs total policies', () => {
browser.wait(EC.presenceOf( OverviewCompliance_po.getTotalDataTableCnt()), timeOutHigh);
let total_count;
OverviewCompliance_po.getTotalDataTableCnt().getText().then(function (text) {
total_count = text.replace(/[a-zA-z ]/g, '');
});
OverviewCompliance_po.getAllTabs().then(function(items) {
let total_rows = 0;
for (let i = 2; i < items.length; i++) {
$('.tabs-header .individual-tag-header:nth-child(' + (1 + i) + ')').click();
OverviewCompliance_po.getTotalDataTableCnt().getText().then(function (text) {
total_rows = total_rows + parseInt(text.replace(/[a-zA-z ]/g, ''), 10);
if ( i === items.length - 1) {
expect(total_count).toEqual(total_rows.toString());
}
});
}
});
OverviewCompliance_po.getFirstTab().click();
});
it('Verify policy violation % click is redirecting to violations page', () => {
browser.wait(EC.presenceOf( OverviewCompliance_po.getViolationFirstPercent()), timeOutHigh);
OverviewCompliance_po.getViolationFirstPercent().click();
browser.wait(EC.presenceOf( policyviolations_po.getPolicyViolationsHeaderText()), timeOutHigh);
const policy_violation_title = policyviolations_po.getPolicyViolationsHeaderText().getText();
expect(policy_violation_title).toEqual('Policy Violations');
browser.wait(EC.visibilityOf(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
browser.wait(EC.elementToBeClickable(OverviewCompliance_po.navigateToOverviewCompliance()), timeOutHigh);
OverviewCompliance_po.navigateToOverviewCompliance().click();
});
it('Check if percentage lies in range 0-100', () => {
browser.wait(EC.visibilityOf( OverviewCompliance_po.getOverallPercent()), timeOutHigh);
OverviewCompliance_po.getOverallPercent().getText().then(function (text) {
let checkPercentRange = false;
if (parseInt(text, 10) >= 0 && parseInt(text, 10) <= 100) {
checkPercentRange = true;
}
expect(checkPercentRange).toEqual(true);
});
});
it('verify csv download', () => {
let download_successful = false;
browser.wait(EC.presenceOf( OverviewCompliance_po.getTotalDataTableCnt()), timeOutHigh);
const filename = process.cwd() + '/e2e/downloads/Policy Compliance Overview.csv';
const fs = require('fs');
const myDir = process.cwd() + '/e2e/downloads';
if (!OverviewCompliance_po.checkDirExists(myDir)) {
fs.mkdirSync(myDir);
} else if ((fs.readdirSync(myDir).length) > 0 && fs.existsSync(filename)) {
fs.unlinkSync(filename);
}
browser.wait(EC.visibilityOf(OverviewCompliance_po.getdownloadIcon()), timeOutHigh);
OverviewCompliance_po.getdownloadIcon().click();
browser.wait(EC.visibilityOf(OverviewCompliance_po.getToastMsg()), timeOutHigh).then(function() {
browser.wait(EC.invisibilityOf(OverviewCompliance_po.getDownloadRunningIcon()), 600000).then(function() {
browser.sleep(4000);
browser.driver.wait(function() {
if (fs.existsSync(filename)) {
download_successful = true;
const fileContent = fs.readFileSync(filename, { encoding: 'utf8' });
expect(fileContent.toString().indexOf('\n')).toBeGreaterThan(0);
}
expect(download_successful).toEqual(true);
return fs.existsSync(filename);
}, timeOutHigh);
});
});
});
}); | the_stack |
import * as fs from "fs-extra";
import * as junk from "junk";
import * as micromatch from "micromatch";
import * as path from "path";
import
{
CONFIGURATION_EXCLUDED_EXTENSIONS,
CONFIGURATION_EXCLUDED_SETTINGS,
CONFIGURATION_KEY,
CONFIGURATION_POKA_YOKE_THRESHOLD,
CONFIGURATION_SEPARATE_KEYBINDINGS,
SETTING_EXCLUDED_EXTENSIONS,
SETTING_EXCLUDED_SETTINGS,
VSCODE_SETTINGS_LIST
} from "../constants";
import { diff } from "../utils/diffPatch";
import { Environment } from "./Environment";
import { excludeSettings, mergeSettings, parse } from "../utils/jsonc";
import { Extension } from "./Extension";
import { getVSCodeSetting } from "../utils/vscodeAPI";
import { IExtension, ISetting, ISyncedItem, SettingType } from "../types/SyncingTypes";
import { localize } from "../i18n";
import { readLastModified, writeLastModified } from "../utils/file";
import * as GitHubTypes from "../types/GitHubTypes";
import * as Toast from "./Toast";
/**
* `VSCode Settings` wrapper.
*/
export class VSCodeSetting
{
private static _instance: VSCodeSetting;
/**
* Suffix of remote mac files.
*/
private static readonly _MAC_SUFFIX: string = "-mac";
/**
* Prefix of remote snippet files.
*/
private static readonly _SNIPPET_PREFIX: string = "snippet-";
private _env: Environment;
private _ext: Extension;
private constructor()
{
this._env = Environment.create();
this._ext = Extension.create();
}
/**
* Creates an instance of singleton class `VSCodeSetting`.
*/
public static create(): VSCodeSetting
{
if (!VSCodeSetting._instance)
{
VSCodeSetting._instance = new VSCodeSetting();
}
return VSCodeSetting._instance;
}
/**
* Gets `VSCode Settings` (which will be uploaded or downloaded, anyway).
*
* For example:
```
[
{
name: "settings",
path: "/Users/Library/Application Support/Code/User/settings.json",
remote: "settings.json",
...
},
...
]
```
*
* @param {boolean} [loadFileContent=false] Whether to load the content of `VSCode Settings` files.
* Defaults to `false`.
* @param {boolean} [showIndicator=false] Whether to show the progress indicator. Defaults to `false`.
* @param {SettingType[]} [settingsList=VSCODE_SETTINGS_LIST] Specifies the settings to get.
*/
public async getSettings(
loadFileContent: boolean = false,
showIndicator: boolean = false,
settingsList: SettingType[] = VSCODE_SETTINGS_LIST
): Promise<ISetting[]>
{
if (showIndicator)
{
Toast.showSpinner(localize("toast.settings.gathering.local"));
}
let results: ISetting[] = [];
let localFilename: string;
let remoteFilename: string;
let tempSettings: ISetting[];
for (const settingType of settingsList)
{
if (settingType === SettingType.Snippets)
{
// Attention: Snippets may be empty.
tempSettings = await this._getSnippets(this._env.snippetsDirectory);
}
else
{
localFilename = `${settingType}.json`;
remoteFilename = localFilename;
if (settingType === SettingType.Keybindings)
{
// Separate the keybindings.
const separateKeybindings = getVSCodeSetting<boolean>(
CONFIGURATION_KEY,
CONFIGURATION_SEPARATE_KEYBINDINGS
);
if (separateKeybindings && this._env.isMac)
{
remoteFilename = `${settingType}${VSCodeSetting._MAC_SUFFIX}.json`;
}
}
tempSettings = [
{
localFilePath: this._env.getSettingsFilePath(localFilename),
remoteFilename,
type: settingType
}
];
}
results.push(...tempSettings);
}
if (loadFileContent)
{
const contents = await this._loadContent(results);
const errorFiles: string[] = [];
results = [];
contents.forEach((value: ISetting) =>
{
// Success if the content is not `null`.
if (value.content != null)
{
results.push(value);
}
else
{
errorFiles.push(value.localFilePath);
}
});
if (errorFiles.length > 0)
{
console.error(localize("error.invalid.settings", errorFiles.join("\r\n")));
}
}
if (showIndicator)
{
Toast.clearSpinner("");
}
return results;
}
/**
* Gets the last modified time (in milliseconds) of VSCode settings.
*
* @param {ISetting[]} vscodeSettings VSCode settings.
*/
public getLastModified(vscodeSettings: ISetting[]): number
{
return Math.max.apply(
null,
vscodeSettings
.filter((s) => s.lastModified != null)
.map((s) => s.lastModified)
);
}
/**
* Save `VSCode Settings` to files.
*
* @param gist `VSCode Settings` from GitHub Gist.
* @param showIndicator Whether to show the progress indicator. Defaults to `false`.
*/
public async saveSettings(gist: GitHubTypes.IGist, showIndicator: boolean = false): Promise<{
updated: ISyncedItem[];
removed: ISyncedItem[];
}>
{
if (showIndicator)
{
Toast.showSpinner(localize("toast.settings.downloading"));
}
try
{
const { files, updated_at: lastModified } = gist;
if (files)
{
const existsFileKeys: string[] = [];
const settingsToRemove: ISetting[] = [];
const settingsToSave: ISetting[] = [];
let extensionsSetting: ISetting | undefined;
let gistFile: GitHubTypes.IGistFile;
const settings = await this.getSettings();
for (const setting of settings)
{
gistFile = files[setting.remoteFilename];
if (gistFile)
{
// If the file exists in both remote and local, it should be synchronized.
if (setting.type === SettingType.Extensions)
{
// Temp extensions file.
extensionsSetting = {
...setting,
content: gistFile.content
};
}
else
{
// Temp other file.
settingsToSave.push({
...setting,
content: gistFile.content
});
}
existsFileKeys.push(setting.remoteFilename);
}
else
{
// File exists in local but not remote.
// Delete if it's a snippet file.
if (setting.type === SettingType.Snippets)
{
settingsToRemove.push(setting);
}
}
}
let filename: string;
for (const key of Object.keys(files))
{
if (!existsFileKeys.includes(key))
{
gistFile = files[key];
if (gistFile.filename.startsWith(VSCodeSetting._SNIPPET_PREFIX))
{
// Snippets.
filename = gistFile.filename.slice(VSCodeSetting._SNIPPET_PREFIX.length);
if (filename)
{
settingsToSave.push({
content: gistFile.content,
localFilePath: this._env.getSnippetFilePath(filename),
remoteFilename: gistFile.filename,
type: SettingType.Snippets
});
}
}
else
{
// Unknown files, don't care.
}
}
}
// Put extensions file to the last.
if (extensionsSetting)
{
settingsToSave.push(extensionsSetting);
}
// poka-yoke - Determines whether there're too much changes since the last downloading.
const value = await this._shouldContinue(settings, settingsToSave, settingsToRemove);
if (value)
{
const syncedItems: {
updated: ISyncedItem[];
removed: ISyncedItem[];
} = { updated: [], removed: [] };
// Save settings.
for (const setting of settingsToSave)
{
try
{
const saved = await this._saveSetting(setting, lastModified);
syncedItems.updated.push(saved);
}
catch (error: any)
{
throw new Error(localize("error.save.file", setting.remoteFilename, error.message));
}
}
// Remove settings.
const removed = await this.removeSettings(settingsToRemove);
syncedItems.removed = removed;
if (showIndicator)
{
Toast.clearSpinner("");
}
return syncedItems;
}
else
{
throw new Error(localize("error.abort.synchronization"));
}
}
else
{
throw new Error(localize("error.gist.files.notfound"));
}
}
catch (error: any)
{
if (showIndicator)
{
Toast.statusError(localize("toast.settings.downloading.failed", error.message));
}
throw error;
}
}
/**
* Synchronizes the last modified time of the `VSCodeSetting`.
*
* @param {ISetting} setting The `VSCodeSetting`.
* @param {(Date | number | string)} lastModified The last modified time.
*/
public async saveLastModifiedTime(setting: ISetting, lastModified: Date | number | string)
{
if (setting.type === SettingType.Extensions)
{
await writeLastModified(this._env.extensionsDirectory, lastModified);
}
else
{
await writeLastModified(setting.localFilePath, lastModified);
}
}
/**
* Deletes the physical files corresponding to the `VSCode Settings`.
*
* @param settings `VSCode Settings`.
*/
public async removeSettings(settings: ISetting[]): Promise<ISyncedItem[]>
{
const removed: ISyncedItem[] = [];
for (const setting of settings)
{
try
{
await fs.remove(setting.localFilePath);
removed.push({ setting });
}
catch (error: any)
{
throw new Error(localize("error.remove.file", setting.remoteFilename, error.message));
}
}
return removed;
}
/**
* Gets all local snippet files.
*
* @param snippetsDir Snippets dir.
*/
private async _getSnippets(snippetsDir: string): Promise<ISetting[]>
{
const results: ISetting[] = [];
try
{
const filenames = await fs.readdir(snippetsDir);
filenames.filter(junk.not).forEach((filename: string) =>
{
// Add prefix to all snippets.
results.push({
localFilePath: path.join(snippetsDir, filename),
remoteFilename: `${VSCodeSetting._SNIPPET_PREFIX}${filename}`,
type: SettingType.Snippets
});
});
}
catch
{
console.error(localize("error.loading.snippets"));
}
return results;
}
/**
* Load the content of `VSCode Settings` files. The `content` will exactly be `undefined` when failure happens.
*
* @param settings `VSCode Settings`.
* @param exclude Default is `true`, exclude some `VSCode Settings` base on the exclude list of `Syncing`.
*/
private async _loadContent(settings: ISetting[], exclude: boolean = true): Promise<ISetting[]>
{
const result: ISetting[] = [];
for (const setting of settings)
{
let content: string | undefined;
let lastModified: number | undefined;
try
{
if (setting.type === SettingType.Extensions)
{
// Exclude extensions.
let extensions = this._ext.getAll();
if (exclude && extensions.length > 0)
{
const patterns = getVSCodeSetting<string[]>(
CONFIGURATION_KEY,
CONFIGURATION_EXCLUDED_EXTENSIONS
);
extensions = this._getExcludedExtensions(extensions, patterns);
}
content = JSON.stringify(extensions, null, 4);
lastModified = await readLastModified(this._env.extensionsDirectory);
}
else
{
content = await fs.readFile(setting.localFilePath, "utf8");
// Exclude settings.
if (exclude && content && setting.type === SettingType.Settings)
{
const settingsJSON = parse(content);
if (settingsJSON)
{
const patterns = getVSCodeSetting<string[]>(
CONFIGURATION_KEY,
CONFIGURATION_EXCLUDED_SETTINGS
);
content = excludeSettings(content, settingsJSON, patterns);
}
}
lastModified = await readLastModified(setting.localFilePath);
}
}
catch (err: any)
{
content = undefined;
console.error(localize("error.loading.settings", setting.remoteFilename, err));
}
result.push({ ...setting, content, lastModified });
}
return result;
}
/**
* Save `VSCode Setting` to file or sync extensions.
*
* @param setting `VSCode Setting`.
*/
private async _saveSetting(setting: ISetting, lastModified: string): Promise<ISyncedItem>
{
let result: ISyncedItem;
if (setting.type === SettingType.Extensions)
{
// Sync extensions.
const extensions: IExtension[] = parse(setting.content ?? "[]");
result = await this._ext.sync(extensions, true);
}
else
{
let settingsToSave = setting.content;
if (setting.type === SettingType.Settings && settingsToSave)
{
// Sync settings.
const localFiles = await this._loadContent([setting], false);
const localSettings = localFiles[0] && localFiles[0].content;
if (localSettings)
{
// Merge remote and local settings.
settingsToSave = mergeSettings(settingsToSave, localSettings);
}
}
// Save to disk.
result = await this._saveToFile({ ...setting, content: settingsToSave });
}
// Synchronize last modified time.
await this.saveLastModifiedTime(setting, lastModified);
return result;
}
/**
* Save the `VSCode Setting` to disk.
*/
private _saveToFile(setting: ISetting)
{
return fs.outputFile(setting.localFilePath, setting.content ?? "{}").then(() => ({ setting } as ISyncedItem));
}
/**
* Determines whether the downloading should continue.
*/
private async _shouldContinue(
settings: ISetting[],
settingsToSave: ISetting[],
settingsToRemove: ISetting[]
): Promise<boolean>
{
let result = true;
const threshold = getVSCodeSetting<number>(CONFIGURATION_KEY, CONFIGURATION_POKA_YOKE_THRESHOLD);
if (threshold > 0)
{
const localSettings = await this._loadContent(settings, false);
// poka-yoke - Determines whether there're too much changes since the last uploading.
// 1. Excluded settings.
// Here clone the settings to avoid manipulation.
let excludedSettings = this._excludeSettings(
localSettings,
settingsToSave.map((setting) => ({ ...setting })),
SettingType.Settings
);
// 2. Excluded extensions.
excludedSettings = this._excludeSettings(
excludedSettings.localSettings,
excludedSettings.remoteSettings,
SettingType.Extensions
);
// 3. Diff settings.
const changes = settingsToRemove.length
+ this._diffSettings(excludedSettings.localSettings, excludedSettings.remoteSettings);
if (changes >= threshold)
{
const okButton = localize("pokaYoke.continue.download");
const message = localize("pokaYoke.continue.download.message");
const selection = await Toast.showConfirmBox(message, okButton, localize("pokaYoke.cancel"));
result = (selection === okButton);
}
}
return result;
}
/**
* Excludes settings based on the excluded setting of remote settings.
*/
private _excludeSettings(localSettings: ISetting[], remoteSettings: ISetting[], type: SettingType)
{
const lSetting = localSettings.find((setting) => (setting.type === type));
const rSetting = remoteSettings.find((setting) => (setting.type === type));
if (lSetting && lSetting.content && rSetting && rSetting.content)
{
const lSettingJSON = parse(lSetting.content);
const rSettingJSON = parse(rSetting.content);
if (lSettingJSON && rSettingJSON)
{
if (type === SettingType.Settings)
{
// Exclude settings.
const patterns = rSettingJSON[SETTING_EXCLUDED_SETTINGS] || [];
lSetting.content = excludeSettings(lSetting.content, lSettingJSON, patterns);
rSetting.content = excludeSettings(rSetting.content, rSettingJSON, patterns);
}
else if (type === SettingType.Extensions)
{
// Exclude extensions.
const rVSCodeSettings = remoteSettings.find((setting) => (setting.type === SettingType.Settings));
if (rVSCodeSettings && rVSCodeSettings.content)
{
const rVSCodeSettingsJSON = parse(rVSCodeSettings.content);
if (rVSCodeSettingsJSON)
{
const patterns: string[] = rVSCodeSettingsJSON[SETTING_EXCLUDED_EXTENSIONS] || [];
lSetting.content = JSON.stringify(this._getExcludedExtensions(lSettingJSON, patterns));
rSetting.content = JSON.stringify(this._getExcludedExtensions(rSettingJSON, patterns));
}
}
}
}
}
return { localSettings, remoteSettings };
}
/**
* Gets excluded extensions based on the excluded setting of remote settings.
*/
private _getExcludedExtensions(extensions: IExtension[], patterns: string[])
{
return extensions.filter((ext) =>
{
return !patterns.some((pattern) => micromatch.isMatch(ext.id, pattern));
});
}
/**
* Calculates the number of differences between the local and remote settings.
*/
private _diffSettings(localSettings: ISetting[], remoteSettings: ISetting[]): number
{
const left = this._parseToJSON(localSettings);
const right = this._parseToJSON(remoteSettings);
return diff(left, right);
}
/**
* Converts the `content` of `ISetting[]` into a `JSON object`.
*/
private _parseToJSON(settings: ISetting[]): Record<string, any>
{
let parsed: any;
let content: string;
const result: Record<string, any> = {};
for (const setting of settings)
{
content = setting.content ?? "";
parsed = parse(content);
if (setting.type === SettingType.Extensions && Array.isArray(parsed))
{
for (const ext of parsed)
{
if (ext["id"] != null)
{
ext["id"] = ext["id"].toLocaleLowerCase();
}
// Only compares id and version.
delete ext["name"];
delete ext["publisher"];
delete ext["uuid"];
}
}
result[setting.remoteFilename] = parsed || content;
}
return result;
}
} | the_stack |
import React, { useState, createElement } from "react";
import { use100vh } from "react-div-100vh";
import { SwitchTransition } from "react-transition-group";
import type { ISetupStep } from "./types";
import {
useMediaQuery,
Paper,
Stepper,
Step,
StepButton,
MobileStepper,
IconButton,
Typography,
Stack,
DialogActions,
} from "@mui/material";
import { alpha } from "@mui/material/styles";
import LoadingButton from "@mui/lab/LoadingButton";
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
import BrandedBackground, { Wrapper } from "@src/assets/BrandedBackground";
import Logo from "@src/assets/Logo";
import ScrollableDialogContent from "@src/components/Modal/ScrollableDialogContent";
import { SlideTransition } from "@src/components/Modal/SlideTransition";
import { analytics } from "analytics";
const BASE_WIDTH = 1024;
export interface ISetupLayoutProps {
steps: ISetupStep[];
completion: Record<string, boolean>;
setCompletion: React.Dispatch<React.SetStateAction<Record<string, boolean>>>;
continueButtonLoading?: boolean | string;
onContinue?: (
completion: Record<string, boolean>
) => Promise<Record<string, boolean>>;
logo?: React.ReactNode;
}
export default function SetupLayout({
steps,
completion,
setCompletion,
continueButtonLoading = false,
onContinue,
logo,
}: ISetupLayoutProps) {
const fullScreenHeight = use100vh() ?? 0;
const isMobile = useMediaQuery((theme: any) => theme.breakpoints.down("sm"));
// Store current step’s ID to prevent confusion
const [stepId, setStepId] = useState("welcome");
// Get current step object
const step =
steps.find((step) => step.id === (stepId || steps[0].id)) ?? steps[0];
// Get current step index
const stepIndex = steps.indexOf(step);
const listedSteps = steps.filter((step) => step.layout !== "centered");
// Continue goes to the next incomplete step
const handleContinue = async () => {
let updatedCompletion = completion;
if (onContinue && step.layout !== "centered")
updatedCompletion = await onContinue(completion);
let nextIncompleteStepIndex = stepIndex + 1;
while (updatedCompletion[steps[nextIncompleteStepIndex]?.id]) {
// console.log("iteration", steps[nextIncompleteStepIndex]?.id);
nextIncompleteStepIndex++;
}
const nextStepId = steps[nextIncompleteStepIndex].id;
analytics.logEvent("setup_step", { step: nextStepId });
setStepId(nextStepId);
};
// Inject props into step.body
const body = createElement(step.body, {
completion,
setCompletion,
isComplete: completion[step.id],
setComplete: (value: boolean = true) =>
setCompletion((c) => ({ ...c, [step.id]: value })),
});
return (
<Wrapper>
<BrandedBackground />
<form
onSubmit={(e) => {
e.preventDefault();
try {
handleContinue();
} catch (e: any) {
throw new Error(e.message);
}
return false;
}}
>
<Paper
component="main"
elevation={4}
sx={{
backgroundColor: (theme) =>
alpha(theme.palette.background.paper, 0.75),
backdropFilter: "blur(20px) saturate(150%)",
maxWidth: BASE_WIDTH,
width: (theme) => `calc(100vw - ${theme.spacing(2)})`,
height: (theme) =>
`calc(${
fullScreenHeight > 0 ? `${fullScreenHeight}px` : "100vh"
} - ${theme.spacing(
2
)} - env(safe-area-inset-top) - env(safe-area-inset-bottom))`,
resize: "both",
p: 0,
"& > *, & > .MuiDialogContent-root": { px: { xs: 2, sm: 4 } },
display: "flex",
flexDirection: "column",
"& .MuiTypography-inherit, & .MuiDialogContent-root": {
typography: "body1",
},
"& p": {
maxWidth: "80ch",
},
}}
>
{stepId === "welcome" ? null : !isMobile ? (
<Stepper
activeStep={stepIndex - 1}
nonLinear
sx={{
mt: 2.5,
mb: 3,
"& .MuiStep-root:first-child": { pl: 0 },
"& .MuiStep-root:last-child": { pr: 0 },
userSelect: "none",
}}
>
{listedSteps.map(({ id, shortTitle }, i) => (
<Step key={id} completed={completion[id]}>
<StepButton
onClick={() => setStepId(id)}
disabled={i > 0 && !completion[listedSteps[i - 1]?.id]}
sx={{ py: 2, my: -2, borderRadius: 1 }}
>
{shortTitle}
</StepButton>
</Step>
))}
</Stepper>
) : (
<MobileStepper
variant="dots"
steps={listedSteps.length}
activeStep={stepIndex - 1}
backButton={
<IconButton
aria-label="Previous step"
disabled={stepIndex === 0}
onClick={() => setStepId(steps[stepIndex - 1].id)}
>
<ChevronLeftIcon />
</IconButton>
}
nextButton={
<IconButton
aria-label="Next step"
disabled={!completion[stepId]}
onClick={() => setStepId(steps[stepIndex + 1].id)}
>
<ChevronRightIcon />
</IconButton>
}
position="static"
sx={{
background: "none",
p: 0,
"& .MuiMobileStepper-dot": { mx: 0.5 },
}}
/>
)}
{step.layout === "centered" ? (
<ScrollableDialogContent disableTopDivider disableBottomDivider>
<Stack
alignItems="center"
justifyContent="center"
spacing={3}
sx={{
minHeight: "100%",
maxWidth: 440,
margin: "0 auto",
textAlign: "center",
py: 3,
}}
>
{stepId === "welcome" && (
<SwitchTransition mode="out-in">
<SlideTransition key={stepId} appear timeout={25}>
{logo || <Logo size={2} />}
</SlideTransition>
</SwitchTransition>
)}
<SwitchTransition mode="out-in">
<SlideTransition key={stepId} appear timeout={50}>
<Typography
variant="h4"
component="h1"
sx={{ mb: 1, typography: { xs: "h5", md: "h4" } }}
>
{step.title}
</Typography>
</SlideTransition>
</SwitchTransition>
<SwitchTransition mode="out-in">
<SlideTransition key={stepId} appear timeout={100}>
<Typography variant="inherit">
{step.description}
</Typography>
</SlideTransition>
</SwitchTransition>
<SwitchTransition mode="out-in">
<SlideTransition key={stepId} appear timeout={150}>
<Stack spacing={4} alignItems="center">
{body}
</Stack>
</SlideTransition>
</SwitchTransition>
</Stack>
</ScrollableDialogContent>
) : (
<>
<SwitchTransition mode="out-in">
<SlideTransition key={stepId} appear timeout={50}>
<Typography
variant="h4"
component="h1"
sx={{ mb: 1, typography: { xs: "h5", md: "h4" } }}
>
{step.title}
</Typography>
</SlideTransition>
</SwitchTransition>
<ScrollableDialogContent
disableTopDivider={step.layout === "centered"}
sx={{ overflowX: "auto", pb: 3 }}
>
<SwitchTransition mode="out-in">
<SlideTransition key={stepId} appear timeout={100}>
<Typography variant="inherit">
{step.description}
</Typography>
</SlideTransition>
</SwitchTransition>
<SwitchTransition mode="out-in">
<SlideTransition key={stepId} appear timeout={150}>
<Stack spacing={4}>{body}</Stack>
</SlideTransition>
</SwitchTransition>
</ScrollableDialogContent>
</>
)}
{step.layout !== "centered" && (
<DialogActions>
<LoadingButton
variant="contained"
color="primary"
size="large"
type="submit"
loading={Boolean(continueButtonLoading)}
loadingPosition={
typeof continueButtonLoading === "string" ? "start" : "center"
}
startIcon={
typeof continueButtonLoading === "string" && (
<div style={{ width: 24 }} />
)
}
disabled={!completion[stepId]}
>
{typeof continueButtonLoading === "string"
? continueButtonLoading
: "Continue"}
</LoadingButton>
</DialogActions>
)}
</Paper>
</form>
</Wrapper>
);
} | the_stack |
* This is an autogenerated file created by the Stencil compiler.
* It contains typing information for all components that exist in this project.
*/
import { HTMLStencilElement, JSXBase } from "@stencil/core/internal";
import { EntityId } from "@reduxjs/toolkit";
import { O } from "fp-ts";
import { LogMessage } from "electron-log";
export namespace Components {
interface AppDocumentEditor {
"documentId": EntityId;
}
interface AppDocumentPane {
"paneId": EntityId;
}
interface AppDocumentPaneActionBar {
"docId": EntityId;
"paneId": EntityId;
}
interface AppDocumentPaneEmpty {
}
interface AppDocumentPaneTab {
"isActive": boolean;
"paneId": EntityId;
"viewId": EntityId;
}
interface AppDocumentPaneTabs {
"activeDocument": O.Option<EntityId>;
"paneId": EntityId;
}
interface AppDocumentPreview {
"documentId": EntityId;
}
interface AppLauncher {
}
interface AppLogsItem {
"logMessage": LogMessage;
}
interface AppLogsList {
}
interface AppLogsRoot {
}
interface AppOnboardingEnd {
}
interface AppOnboardingPlugins {
}
interface AppOnboardingReporting {
}
interface AppOnboardingRoot {
}
interface AppOnboardingWelcome {
}
interface AppProjectGraph {
"projectPath": string;
}
interface AppProjectRoot {
}
interface AppProjectSidebarFile {
"filePath": string;
"isMain": boolean;
}
interface AppProjectSidebarFiles {
"projectDir": string;
}
interface AppProjectSidebarNav {
}
interface AppRoot {
}
interface AppSettingsAdvanced {
}
interface AppSettingsEditor {
}
interface AppSettingsGeneral {
}
interface AppSettingsPluginCard {
"pluginName": string;
}
interface AppSettingsPlugins {
}
interface AppSettingsRoot {
}
interface AppSettingsSidebar {
}
interface AppSidebarEmpty {
}
}
declare global {
interface HTMLAppDocumentEditorElement extends Components.AppDocumentEditor, HTMLStencilElement {
}
var HTMLAppDocumentEditorElement: {
prototype: HTMLAppDocumentEditorElement;
new (): HTMLAppDocumentEditorElement;
};
interface HTMLAppDocumentPaneElement extends Components.AppDocumentPane, HTMLStencilElement {
}
var HTMLAppDocumentPaneElement: {
prototype: HTMLAppDocumentPaneElement;
new (): HTMLAppDocumentPaneElement;
};
interface HTMLAppDocumentPaneActionBarElement extends Components.AppDocumentPaneActionBar, HTMLStencilElement {
}
var HTMLAppDocumentPaneActionBarElement: {
prototype: HTMLAppDocumentPaneActionBarElement;
new (): HTMLAppDocumentPaneActionBarElement;
};
interface HTMLAppDocumentPaneEmptyElement extends Components.AppDocumentPaneEmpty, HTMLStencilElement {
}
var HTMLAppDocumentPaneEmptyElement: {
prototype: HTMLAppDocumentPaneEmptyElement;
new (): HTMLAppDocumentPaneEmptyElement;
};
interface HTMLAppDocumentPaneTabElement extends Components.AppDocumentPaneTab, HTMLStencilElement {
}
var HTMLAppDocumentPaneTabElement: {
prototype: HTMLAppDocumentPaneTabElement;
new (): HTMLAppDocumentPaneTabElement;
};
interface HTMLAppDocumentPaneTabsElement extends Components.AppDocumentPaneTabs, HTMLStencilElement {
}
var HTMLAppDocumentPaneTabsElement: {
prototype: HTMLAppDocumentPaneTabsElement;
new (): HTMLAppDocumentPaneTabsElement;
};
interface HTMLAppDocumentPreviewElement extends Components.AppDocumentPreview, HTMLStencilElement {
}
var HTMLAppDocumentPreviewElement: {
prototype: HTMLAppDocumentPreviewElement;
new (): HTMLAppDocumentPreviewElement;
};
interface HTMLAppLauncherElement extends Components.AppLauncher, HTMLStencilElement {
}
var HTMLAppLauncherElement: {
prototype: HTMLAppLauncherElement;
new (): HTMLAppLauncherElement;
};
interface HTMLAppLogsItemElement extends Components.AppLogsItem, HTMLStencilElement {
}
var HTMLAppLogsItemElement: {
prototype: HTMLAppLogsItemElement;
new (): HTMLAppLogsItemElement;
};
interface HTMLAppLogsListElement extends Components.AppLogsList, HTMLStencilElement {
}
var HTMLAppLogsListElement: {
prototype: HTMLAppLogsListElement;
new (): HTMLAppLogsListElement;
};
interface HTMLAppLogsRootElement extends Components.AppLogsRoot, HTMLStencilElement {
}
var HTMLAppLogsRootElement: {
prototype: HTMLAppLogsRootElement;
new (): HTMLAppLogsRootElement;
};
interface HTMLAppOnboardingEndElement extends Components.AppOnboardingEnd, HTMLStencilElement {
}
var HTMLAppOnboardingEndElement: {
prototype: HTMLAppOnboardingEndElement;
new (): HTMLAppOnboardingEndElement;
};
interface HTMLAppOnboardingPluginsElement extends Components.AppOnboardingPlugins, HTMLStencilElement {
}
var HTMLAppOnboardingPluginsElement: {
prototype: HTMLAppOnboardingPluginsElement;
new (): HTMLAppOnboardingPluginsElement;
};
interface HTMLAppOnboardingReportingElement extends Components.AppOnboardingReporting, HTMLStencilElement {
}
var HTMLAppOnboardingReportingElement: {
prototype: HTMLAppOnboardingReportingElement;
new (): HTMLAppOnboardingReportingElement;
};
interface HTMLAppOnboardingRootElement extends Components.AppOnboardingRoot, HTMLStencilElement {
}
var HTMLAppOnboardingRootElement: {
prototype: HTMLAppOnboardingRootElement;
new (): HTMLAppOnboardingRootElement;
};
interface HTMLAppOnboardingWelcomeElement extends Components.AppOnboardingWelcome, HTMLStencilElement {
}
var HTMLAppOnboardingWelcomeElement: {
prototype: HTMLAppOnboardingWelcomeElement;
new (): HTMLAppOnboardingWelcomeElement;
};
interface HTMLAppProjectGraphElement extends Components.AppProjectGraph, HTMLStencilElement {
}
var HTMLAppProjectGraphElement: {
prototype: HTMLAppProjectGraphElement;
new (): HTMLAppProjectGraphElement;
};
interface HTMLAppProjectRootElement extends Components.AppProjectRoot, HTMLStencilElement {
}
var HTMLAppProjectRootElement: {
prototype: HTMLAppProjectRootElement;
new (): HTMLAppProjectRootElement;
};
interface HTMLAppProjectSidebarFileElement extends Components.AppProjectSidebarFile, HTMLStencilElement {
}
var HTMLAppProjectSidebarFileElement: {
prototype: HTMLAppProjectSidebarFileElement;
new (): HTMLAppProjectSidebarFileElement;
};
interface HTMLAppProjectSidebarFilesElement extends Components.AppProjectSidebarFiles, HTMLStencilElement {
}
var HTMLAppProjectSidebarFilesElement: {
prototype: HTMLAppProjectSidebarFilesElement;
new (): HTMLAppProjectSidebarFilesElement;
};
interface HTMLAppProjectSidebarNavElement extends Components.AppProjectSidebarNav, HTMLStencilElement {
}
var HTMLAppProjectSidebarNavElement: {
prototype: HTMLAppProjectSidebarNavElement;
new (): HTMLAppProjectSidebarNavElement;
};
interface HTMLAppRootElement extends Components.AppRoot, HTMLStencilElement {
}
var HTMLAppRootElement: {
prototype: HTMLAppRootElement;
new (): HTMLAppRootElement;
};
interface HTMLAppSettingsAdvancedElement extends Components.AppSettingsAdvanced, HTMLStencilElement {
}
var HTMLAppSettingsAdvancedElement: {
prototype: HTMLAppSettingsAdvancedElement;
new (): HTMLAppSettingsAdvancedElement;
};
interface HTMLAppSettingsEditorElement extends Components.AppSettingsEditor, HTMLStencilElement {
}
var HTMLAppSettingsEditorElement: {
prototype: HTMLAppSettingsEditorElement;
new (): HTMLAppSettingsEditorElement;
};
interface HTMLAppSettingsGeneralElement extends Components.AppSettingsGeneral, HTMLStencilElement {
}
var HTMLAppSettingsGeneralElement: {
prototype: HTMLAppSettingsGeneralElement;
new (): HTMLAppSettingsGeneralElement;
};
interface HTMLAppSettingsPluginCardElement extends Components.AppSettingsPluginCard, HTMLStencilElement {
}
var HTMLAppSettingsPluginCardElement: {
prototype: HTMLAppSettingsPluginCardElement;
new (): HTMLAppSettingsPluginCardElement;
};
interface HTMLAppSettingsPluginsElement extends Components.AppSettingsPlugins, HTMLStencilElement {
}
var HTMLAppSettingsPluginsElement: {
prototype: HTMLAppSettingsPluginsElement;
new (): HTMLAppSettingsPluginsElement;
};
interface HTMLAppSettingsRootElement extends Components.AppSettingsRoot, HTMLStencilElement {
}
var HTMLAppSettingsRootElement: {
prototype: HTMLAppSettingsRootElement;
new (): HTMLAppSettingsRootElement;
};
interface HTMLAppSettingsSidebarElement extends Components.AppSettingsSidebar, HTMLStencilElement {
}
var HTMLAppSettingsSidebarElement: {
prototype: HTMLAppSettingsSidebarElement;
new (): HTMLAppSettingsSidebarElement;
};
interface HTMLAppSidebarEmptyElement extends Components.AppSidebarEmpty, HTMLStencilElement {
}
var HTMLAppSidebarEmptyElement: {
prototype: HTMLAppSidebarEmptyElement;
new (): HTMLAppSidebarEmptyElement;
};
interface HTMLElementTagNameMap {
"app-document-editor": HTMLAppDocumentEditorElement;
"app-document-pane": HTMLAppDocumentPaneElement;
"app-document-pane-action-bar": HTMLAppDocumentPaneActionBarElement;
"app-document-pane-empty": HTMLAppDocumentPaneEmptyElement;
"app-document-pane-tab": HTMLAppDocumentPaneTabElement;
"app-document-pane-tabs": HTMLAppDocumentPaneTabsElement;
"app-document-preview": HTMLAppDocumentPreviewElement;
"app-launcher": HTMLAppLauncherElement;
"app-logs-item": HTMLAppLogsItemElement;
"app-logs-list": HTMLAppLogsListElement;
"app-logs-root": HTMLAppLogsRootElement;
"app-onboarding-end": HTMLAppOnboardingEndElement;
"app-onboarding-plugins": HTMLAppOnboardingPluginsElement;
"app-onboarding-reporting": HTMLAppOnboardingReportingElement;
"app-onboarding-root": HTMLAppOnboardingRootElement;
"app-onboarding-welcome": HTMLAppOnboardingWelcomeElement;
"app-project-graph": HTMLAppProjectGraphElement;
"app-project-root": HTMLAppProjectRootElement;
"app-project-sidebar-file": HTMLAppProjectSidebarFileElement;
"app-project-sidebar-files": HTMLAppProjectSidebarFilesElement;
"app-project-sidebar-nav": HTMLAppProjectSidebarNavElement;
"app-root": HTMLAppRootElement;
"app-settings-advanced": HTMLAppSettingsAdvancedElement;
"app-settings-editor": HTMLAppSettingsEditorElement;
"app-settings-general": HTMLAppSettingsGeneralElement;
"app-settings-plugin-card": HTMLAppSettingsPluginCardElement;
"app-settings-plugins": HTMLAppSettingsPluginsElement;
"app-settings-root": HTMLAppSettingsRootElement;
"app-settings-sidebar": HTMLAppSettingsSidebarElement;
"app-sidebar-empty": HTMLAppSidebarEmptyElement;
}
}
declare namespace LocalJSX {
interface AppDocumentEditor {
"documentId"?: EntityId;
}
interface AppDocumentPane {
"paneId": EntityId;
}
interface AppDocumentPaneActionBar {
"docId": EntityId;
"paneId": EntityId;
}
interface AppDocumentPaneEmpty {
}
interface AppDocumentPaneTab {
"isActive"?: boolean;
"paneId"?: EntityId;
"viewId"?: EntityId;
}
interface AppDocumentPaneTabs {
"activeDocument"?: O.Option<EntityId>;
"paneId"?: EntityId;
}
interface AppDocumentPreview {
"documentId"?: EntityId;
}
interface AppLauncher {
}
interface AppLogsItem {
"logMessage": LogMessage;
}
interface AppLogsList {
}
interface AppLogsRoot {
}
interface AppOnboardingEnd {
}
interface AppOnboardingPlugins {
}
interface AppOnboardingReporting {
}
interface AppOnboardingRoot {
}
interface AppOnboardingWelcome {
}
interface AppProjectGraph {
"projectPath"?: string;
}
interface AppProjectRoot {
}
interface AppProjectSidebarFile {
"filePath"?: string;
"isMain"?: boolean;
}
interface AppProjectSidebarFiles {
"projectDir"?: string;
}
interface AppProjectSidebarNav {
}
interface AppRoot {
}
interface AppSettingsAdvanced {
}
interface AppSettingsEditor {
}
interface AppSettingsGeneral {
}
interface AppSettingsPluginCard {
"pluginName"?: string;
}
interface AppSettingsPlugins {
}
interface AppSettingsRoot {
}
interface AppSettingsSidebar {
}
interface AppSidebarEmpty {
}
interface IntrinsicElements {
"app-document-editor": AppDocumentEditor;
"app-document-pane": AppDocumentPane;
"app-document-pane-action-bar": AppDocumentPaneActionBar;
"app-document-pane-empty": AppDocumentPaneEmpty;
"app-document-pane-tab": AppDocumentPaneTab;
"app-document-pane-tabs": AppDocumentPaneTabs;
"app-document-preview": AppDocumentPreview;
"app-launcher": AppLauncher;
"app-logs-item": AppLogsItem;
"app-logs-list": AppLogsList;
"app-logs-root": AppLogsRoot;
"app-onboarding-end": AppOnboardingEnd;
"app-onboarding-plugins": AppOnboardingPlugins;
"app-onboarding-reporting": AppOnboardingReporting;
"app-onboarding-root": AppOnboardingRoot;
"app-onboarding-welcome": AppOnboardingWelcome;
"app-project-graph": AppProjectGraph;
"app-project-root": AppProjectRoot;
"app-project-sidebar-file": AppProjectSidebarFile;
"app-project-sidebar-files": AppProjectSidebarFiles;
"app-project-sidebar-nav": AppProjectSidebarNav;
"app-root": AppRoot;
"app-settings-advanced": AppSettingsAdvanced;
"app-settings-editor": AppSettingsEditor;
"app-settings-general": AppSettingsGeneral;
"app-settings-plugin-card": AppSettingsPluginCard;
"app-settings-plugins": AppSettingsPlugins;
"app-settings-root": AppSettingsRoot;
"app-settings-sidebar": AppSettingsSidebar;
"app-sidebar-empty": AppSidebarEmpty;
}
}
export { LocalJSX as JSX };
declare module "@stencil/core" {
export namespace JSX {
interface IntrinsicElements {
"app-document-editor": LocalJSX.AppDocumentEditor & JSXBase.HTMLAttributes<HTMLAppDocumentEditorElement>;
"app-document-pane": LocalJSX.AppDocumentPane & JSXBase.HTMLAttributes<HTMLAppDocumentPaneElement>;
"app-document-pane-action-bar": LocalJSX.AppDocumentPaneActionBar & JSXBase.HTMLAttributes<HTMLAppDocumentPaneActionBarElement>;
"app-document-pane-empty": LocalJSX.AppDocumentPaneEmpty & JSXBase.HTMLAttributes<HTMLAppDocumentPaneEmptyElement>;
"app-document-pane-tab": LocalJSX.AppDocumentPaneTab & JSXBase.HTMLAttributes<HTMLAppDocumentPaneTabElement>;
"app-document-pane-tabs": LocalJSX.AppDocumentPaneTabs & JSXBase.HTMLAttributes<HTMLAppDocumentPaneTabsElement>;
"app-document-preview": LocalJSX.AppDocumentPreview & JSXBase.HTMLAttributes<HTMLAppDocumentPreviewElement>;
"app-launcher": LocalJSX.AppLauncher & JSXBase.HTMLAttributes<HTMLAppLauncherElement>;
"app-logs-item": LocalJSX.AppLogsItem & JSXBase.HTMLAttributes<HTMLAppLogsItemElement>;
"app-logs-list": LocalJSX.AppLogsList & JSXBase.HTMLAttributes<HTMLAppLogsListElement>;
"app-logs-root": LocalJSX.AppLogsRoot & JSXBase.HTMLAttributes<HTMLAppLogsRootElement>;
"app-onboarding-end": LocalJSX.AppOnboardingEnd & JSXBase.HTMLAttributes<HTMLAppOnboardingEndElement>;
"app-onboarding-plugins": LocalJSX.AppOnboardingPlugins & JSXBase.HTMLAttributes<HTMLAppOnboardingPluginsElement>;
"app-onboarding-reporting": LocalJSX.AppOnboardingReporting & JSXBase.HTMLAttributes<HTMLAppOnboardingReportingElement>;
"app-onboarding-root": LocalJSX.AppOnboardingRoot & JSXBase.HTMLAttributes<HTMLAppOnboardingRootElement>;
"app-onboarding-welcome": LocalJSX.AppOnboardingWelcome & JSXBase.HTMLAttributes<HTMLAppOnboardingWelcomeElement>;
"app-project-graph": LocalJSX.AppProjectGraph & JSXBase.HTMLAttributes<HTMLAppProjectGraphElement>;
"app-project-root": LocalJSX.AppProjectRoot & JSXBase.HTMLAttributes<HTMLAppProjectRootElement>;
"app-project-sidebar-file": LocalJSX.AppProjectSidebarFile & JSXBase.HTMLAttributes<HTMLAppProjectSidebarFileElement>;
"app-project-sidebar-files": LocalJSX.AppProjectSidebarFiles & JSXBase.HTMLAttributes<HTMLAppProjectSidebarFilesElement>;
"app-project-sidebar-nav": LocalJSX.AppProjectSidebarNav & JSXBase.HTMLAttributes<HTMLAppProjectSidebarNavElement>;
"app-root": LocalJSX.AppRoot & JSXBase.HTMLAttributes<HTMLAppRootElement>;
"app-settings-advanced": LocalJSX.AppSettingsAdvanced & JSXBase.HTMLAttributes<HTMLAppSettingsAdvancedElement>;
"app-settings-editor": LocalJSX.AppSettingsEditor & JSXBase.HTMLAttributes<HTMLAppSettingsEditorElement>;
"app-settings-general": LocalJSX.AppSettingsGeneral & JSXBase.HTMLAttributes<HTMLAppSettingsGeneralElement>;
"app-settings-plugin-card": LocalJSX.AppSettingsPluginCard & JSXBase.HTMLAttributes<HTMLAppSettingsPluginCardElement>;
"app-settings-plugins": LocalJSX.AppSettingsPlugins & JSXBase.HTMLAttributes<HTMLAppSettingsPluginsElement>;
"app-settings-root": LocalJSX.AppSettingsRoot & JSXBase.HTMLAttributes<HTMLAppSettingsRootElement>;
"app-settings-sidebar": LocalJSX.AppSettingsSidebar & JSXBase.HTMLAttributes<HTMLAppSettingsSidebarElement>;
"app-sidebar-empty": LocalJSX.AppSidebarEmpty & JSXBase.HTMLAttributes<HTMLAppSidebarEmptyElement>;
}
}
} | the_stack |
import {
__String,
Declaration,
Decorator,
Expression,
Identifier,
isArrayTypeNode,
isEnumDeclaration,
isIdentifier,
isImportDeclaration,
isImportSpecifier,
isIndexSignatureDeclaration,
isLiteralTypeNode,
isMethodDeclaration,
isNamedImports,
isParameter,
isParenthesizedTypeNode,
isPropertyDeclaration,
isSourceFile,
isStringLiteral,
isTypeLiteralNode,
isTypeReferenceNode,
isUnionTypeNode,
MethodDeclaration,
Node,
NodeFactory,
ParameterDeclaration,
PropertyAccessExpression,
PropertyDeclaration,
QualifiedName,
ScriptReferenceHost,
SourceFile,
Symbol,
SymbolTable,
SyntaxKind,
TransformationContext,
TransformerFactory,
TypeNode,
visitEachChild,
visitNode
} from 'typescript';
// function getTypeExpressions(f: NodeFactory, t: Identifier, types: NodeArray<TypeNode>): Expression[] {
// const args: Expression[] = [];
// for (const subType of types) {
// if (isLiteralTypeNode(subType)) {
// args.push(subType.literal);
// } else {
// args.push(getTypeExpression(f, t, subType));
// }
// }
// return args;
// }
export class DeepkitTransformer {
protected host!: ScriptReferenceHost;
protected f: NodeFactory;
sourceFile!: SourceFile;
constructor(
protected context: TransformationContext,
) {
this.f = context.factory;
this.host = (context as any).getEmitHost() as ScriptReferenceHost;
}
transform<T extends Node>(sourceFile: T): T {
// const importT = context.factory.createImportDeclaration(
// undefined, undefined,
// context.factory.createImportClause(false, context.factory.createIdentifier('t'), undefined),
// context.factory.createIdentifier('@deepkit/type')
// );
// context.factory.updateSourceFile(fileNode, [
// importT,
// ...fileNode.statements,
// ]);
let importT: Identifier | undefined = undefined;
if (isSourceFile(sourceFile)) {
this.sourceFile = sourceFile;
for (const statement of sourceFile.statements) {
if (isImportDeclaration(statement) && statement.importClause) {
if (isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text === '@deepkit/type') {
if (statement.importClause.namedBindings && isNamedImports(statement.importClause.namedBindings)) {
for (const element of statement.importClause.namedBindings.elements) {
if (element.name.text === 't') {
importT = element.name;
}
}
}
}
}
}
} else {
return sourceFile;
}
if (!importT) return sourceFile;
const visitor = (node: Node): Node => {
if ((isPropertyDeclaration(node) || isMethodDeclaration(node)) && node.type && node.decorators) {
const typeDecorator = this.getDecoratorFromType(importT!, node);
if (isMethodDeclaration(node)) {
return {
...node,
decorators: this.f.createNodeArray([...node.decorators, typeDecorator]),
parameters: this.f.createNodeArray(node.parameters.map(parameter => {
if (!parameter.type) return parameter;
return { ...parameter, decorators: this.f.createNodeArray([...(parameter.decorators || []), this.getDecoratorFromType(importT!, parameter)]) };
}))
} as MethodDeclaration;
}
return { ...node, decorators: this.f.createNodeArray([...node.decorators, typeDecorator]) };
}
return visitEachChild(node, visitor, this.context);
};
return visitNode(sourceFile, visitor);
}
resolveEntityName(e: QualifiedName): PropertyAccessExpression {
return this.f.createPropertyAccessExpression(
isIdentifier(e.left) ? e.left : this.resolveEntityName(e.left),
e.right,
);
}
isNodeWithLocals(node: Node): node is (Node & { locals: SymbolTable | undefined }) {
return 'locals' in node;
}
findSymbol(type: TypeNode): Symbol | undefined {
let current = type.parent;
const name = isIdentifier(type) ? type.text : type.getText();
do {
if (this.isNodeWithLocals(current) && current.locals) {
//check if its here
const symbol = current.locals.get(name as __String);
if (symbol) return symbol;
}
current = current.parent;
} while (current);
return;
}
findDeclaration(symbol: Symbol): Declaration | undefined {
if (symbol && symbol.declarations && symbol.declarations[0]) {
const declaration = symbol.declarations[0];
if (!declaration) return;
if (isImportSpecifier(declaration)) {
const declarationName = declaration.name.text;
const imp = declaration.parent.parent.parent;
if (isImportDeclaration(imp) && isStringLiteral(imp.moduleSpecifier)) {
let fromFile = imp.moduleSpecifier.text;
if (!fromFile.endsWith('.js') && !fromFile.endsWith('.ts')) fromFile += '.ts';
const source = this.host.getSourceFile(fromFile.startsWith('./') ? this.sourceFile.fileName + '/.' + fromFile : fromFile);
if (source && this.isNodeWithLocals(source) && source.locals) {
const declarationSymbol = source.locals.get(declarationName as __String);
if (declarationSymbol && declarationSymbol.declarations) return declarationSymbol.declarations[0];
}
}
}
return declaration;
}
return;
}
getTypeExpression(t: Identifier, type: TypeNode, options: { allowShort?: boolean } = {}): Expression {
if (isParenthesizedTypeNode(type)) return this.getTypeExpression(t, type.type);
let markAsOptional: boolean = !!type.parent && isPropertyDeclaration(type.parent) && !!type.parent.questionToken;
let markAsNullable = false;
let wrap = (e: Expression) => {
if (markAsOptional) {
//its optional
e = this.f.createPropertyAccessExpression(e, 'optional');
}
if (markAsNullable) {
//its optional
e = this.f.createPropertyAccessExpression(e, 'nullable');
}
return e;
};
if (type.kind === SyntaxKind.StringKeyword) return wrap(this.f.createPropertyAccessExpression(t, 'string'));
if (type.kind === SyntaxKind.NumberKeyword) return wrap(this.f.createPropertyAccessExpression(t, 'number'));
if (type.kind === SyntaxKind.BooleanKeyword) return wrap(this.f.createPropertyAccessExpression(t, 'boolean'));
if (type.kind === SyntaxKind.BigIntKeyword) return wrap(this.f.createPropertyAccessExpression(t, 'bigint'));
if (isLiteralTypeNode(type)) {
return wrap(this.f.createCallExpression(this.f.createPropertyAccessExpression(t, 'literal'), [], [
type.literal
]));
}
if (isArrayTypeNode(type)) {
return wrap(this.f.createCallExpression(this.f.createPropertyAccessExpression(t, 'array'), [], [this.getTypeExpression(t, type.elementType)]));
}
if (isTypeLiteralNode(type)) {
//{[name: string]: number} => t.record(t.string, t.number)
const [first] = type.members;
if (first && isIndexSignatureDeclaration(first)) {
const [parameter] = first.parameters;
if (parameter && parameter.type) {
return wrap(this.f.createCallExpression(this.f.createPropertyAccessExpression(t, 'record'), [], [
this.getTypeExpression(t, parameter.type),
this.getTypeExpression(t, first.type),
]));
}
}
}
if (isTypeReferenceNode(type) && isIdentifier(type.typeName) && type.typeName.text === 'Record' && type.typeArguments && type.typeArguments.length === 2) {
//Record<string, number> => t.record(t.string, t.number)
const [key, value] = type.typeArguments;
return wrap(this.f.createCallExpression(this.f.createPropertyAccessExpression(t, 'record'), [], [
this.getTypeExpression(t, key),
this.getTypeExpression(t, value),
]));
}
if (isTypeReferenceNode(type) && isIdentifier(type.typeName) && type.typeName.text === 'Partial' && type.typeArguments && type.typeArguments.length === 1) {
//Record<string, number> => t.record(t.string, t.number)
const [T] = type.typeArguments;
return wrap(this.f.createCallExpression(this.f.createPropertyAccessExpression(t, 'partial'), [], [
this.getTypeExpression(t, T, { allowShort: true }),
]));
}
if (isUnionTypeNode(type)) {
const args: Expression[] = [];
let literalAdded = false;
for (const subType of type.types) {
if (subType.kind === SyntaxKind.NullKeyword) {
markAsNullable = true;
} else if (subType.kind === SyntaxKind.UndefinedKeyword) {
markAsOptional = true;
} else if (isLiteralTypeNode(subType)) {
if (subType.literal.kind === SyntaxKind.NullKeyword) {
markAsNullable = true;
} else {
args.push(subType.literal);
literalAdded = true;
}
} else {
args.push(this.getTypeExpression(t, subType, { allowShort: true }));
}
}
//t.array(t.union(t.number).optional) => t.array(t.number.optional)
if (args.length === 1 && !literalAdded) return wrap(args[0]);
return wrap(this.f.createCallExpression(this.f.createPropertyAccessExpression(t, 'union'), [], args));
}
if (isTypeReferenceNode(type)) {
if (isIdentifier(type.typeName) && type.typeName.text === 'Date') return wrap(this.f.createPropertyAccessExpression(t, 'date'));
const symbol = this.findSymbol(type);
if (symbol) {
const declaration = this.findDeclaration(symbol);
if (declaration && isEnumDeclaration(declaration)) {
return wrap(this.f.createCallExpression(this.f.createPropertyAccessExpression(t, 'enum'), [], [
isIdentifier(type.typeName) ? type.typeName : this.resolveEntityName(type.typeName)
]));
}
}
if (isIdentifier(type.typeName) && type.typeName.text === 'Promise') {
return wrap(this.f.createCallExpression(
this.f.createPropertyAccessExpression(t, 'promise'), [],
type.typeArguments ? type.typeArguments.map(T => this.getTypeExpression(t, T)) : []
));
}
if (options?.allowShort && !type.typeArguments) {
return isIdentifier(type.typeName) ? type.typeName : this.resolveEntityName(type.typeName);
}
let e: Expression = this.f.createCallExpression(this.f.createPropertyAccessExpression(t, 'type'), [], [
isIdentifier(type.typeName) ? type.typeName : this.resolveEntityName(type.typeName)
]);
if (type.typeArguments) {
e = this.f.createCallExpression(
this.f.createPropertyAccessExpression(e, 'generic'), [],
type.typeArguments.map(T => this.getTypeExpression(t, T, { allowShort: true }))
);
}
return wrap(e);
}
return wrap(this.f.createPropertyAccessExpression(t, 'any'));
}
getDecoratorFromType(t: Identifier, node: PropertyDeclaration | MethodDeclaration | ParameterDeclaration): Decorator {
if (!node.type) throw new Error('No type given');
let e = this.getTypeExpression(t, node.type);
if (isParameter(node) && isIdentifier(node.name)) {
e = this.f.createCallExpression(this.f.createPropertyAccessExpression(e, 'name'), [], [this.f.createStringLiteral(node.name.text, true)]);
}
return this.f.createDecorator(e);
}
}
export const transformer: TransformerFactory<SourceFile> = (context) => {
const deepkitTransformer = new DeepkitTransformer(context);
return <T extends Node>(sourceFile: T): T => {
return deepkitTransformer.transform(sourceFile);
};
}; | the_stack |
import { sleep } from '@celo/base'
import { StableToken } from '@celo/contractkit'
import { GoldTokenWrapper } from '@celo/contractkit/lib/wrappers/GoldTokenWrapper'
import { StableTokenWrapper } from '@celo/contractkit/lib/wrappers/StableTokenWrapper'
import { describe, test } from '@jest/globals'
import BigNumber from 'bignumber.js'
import Logger from 'bunyan'
import { EnvTestContext } from '../context'
import {
fundAccountWithCELO,
fundAccountWithStableToken,
getKey,
getValidatorKey,
ONE,
TestAccounts,
} from '../scaffold'
export function runGrandaMentoTest(context: EnvTestContext, stableTokensToTest: StableToken[]) {
const celoAmountToFund = ONE.times(61000)
const stableTokenAmountToFund = ONE.times(61000)
const celoAmountToSell = ONE.times(60000)
const stableTokenAmountToSell = ONE.times(60000)
describe('Granda Mento Test', () => {
beforeAll(async () => {
await fundAccountWithCELO(context, TestAccounts.GrandaMentoExchanger, celoAmountToFund)
})
const baseLogger = context.logger.child({ test: 'grandaMento' })
for (const sellCelo of [true, false]) {
for (const stableToken of stableTokensToTest) {
const sellTokenStr = sellCelo ? 'CELO' : stableToken
const buyTokenStr = sellCelo ? stableToken : 'CELO'
describe(`selling ${sellTokenStr} for ${buyTokenStr}`, () => {
beforeAll(async () => {
if (!sellCelo) {
await fundAccountWithStableToken(
context,
TestAccounts.GrandaMentoExchanger,
stableTokenAmountToFund,
stableToken
)
}
})
let buyToken: GoldTokenWrapper | StableTokenWrapper
let sellToken: GoldTokenWrapper | StableTokenWrapper
let stableTokenAddress: string
let sellAmount: BigNumber
beforeEach(async () => {
const goldTokenWrapper = await context.kit.contracts.getGoldToken()
const stableTokenWrapper = await context.kit.celoTokens.getWrapper(
stableToken as StableToken
)
stableTokenAddress = stableTokenWrapper.address
if (sellCelo) {
buyToken = stableTokenWrapper
sellToken = goldTokenWrapper
sellAmount = celoAmountToSell
} else {
buyToken = goldTokenWrapper
sellToken = stableTokenWrapper
sellAmount = stableTokenAmountToSell
}
})
const createExchangeProposal = async (logger: Logger, fromAddress: string) => {
const grandaMento = await context.kit.contracts.getGrandaMento()
const tokenApprovalReceipt = await sellToken
.approve(grandaMento.address, sellAmount.toFixed())
.sendAndWaitForReceipt({
from: fromAddress,
})
logger.debug(
{
sellAmount,
sellTokenStr,
spender: grandaMento.address,
},
'Approved GrandaMento to spend sell token'
)
const minedTokenApprovalTx = await context.kit.web3.eth.getTransaction(
tokenApprovalReceipt.transactionHash
)
const tokenApprovalCeloFees = new BigNumber(tokenApprovalReceipt.gasUsed).times(
minedTokenApprovalTx.gasPrice
)
// Some flakiness has been observed after approving, so we sleep
await sleep(5000)
const creationTx = await grandaMento.createExchangeProposal(
context.kit.celoTokens.getContract(stableToken as StableToken),
sellAmount,
sellCelo
)
const creationReceipt = await creationTx.sendAndWaitForReceipt({
from: fromAddress,
})
// Some flakiness has been observed after proposing, so we sleep
await sleep(5000)
const proposalId = creationReceipt.events!.ExchangeProposalCreated.returnValues
.proposalId
logger.debug(
{
sellAmount,
sellCelo,
proposalId,
},
'Created exchange proposal'
)
const minedCreationTx = await context.kit.web3.eth.getTransaction(
creationReceipt.transactionHash
)
const creationCeloFees = new BigNumber(creationReceipt.gasUsed).times(
minedCreationTx.gasPrice
)
return {
creationReceipt,
minedCreationTx,
proposalId,
celoFees: tokenApprovalCeloFees.plus(creationCeloFees),
}
}
test('exchanger creates and cancels an exchange proposal', async () => {
const from = await getKey(context.mnemonic, TestAccounts.GrandaMentoExchanger)
context.kit.connection.addAccount(from.privateKey)
context.kit.defaultAccount = from.address
const logger = baseLogger.child({ from: from.address })
const grandaMento = await context.kit.contracts.getGrandaMento()
const sellTokenBalanceBeforeCreation = await sellToken.balanceOf(from.address)
const creationInfo = await createExchangeProposal(logger, from.address)
let celoFees = creationInfo.celoFees
const sellTokenBalanceAfterCreation = await sellToken.balanceOf(from.address)
// If we are looking at the CELO balance, take the fees spent into consideration.
const expectedBalanceDifference = sellCelo ? sellAmount.plus(celoFees) : sellAmount
expect(
sellTokenBalanceBeforeCreation.minus(sellTokenBalanceAfterCreation).toString()
).toBe(expectedBalanceDifference.toString())
const cancelReceipt = await grandaMento
.cancelExchangeProposal(creationInfo.proposalId)
.sendAndWaitForReceipt({
from: from.address,
})
const minedCancelTx = await context.kit.web3.eth.getTransaction(
cancelReceipt.transactionHash
)
logger.debug(
{
proposalId: creationInfo.proposalId,
},
'Cancelled exchange proposal'
)
celoFees = celoFees.plus(
new BigNumber(cancelReceipt.gasUsed).times(minedCancelTx.gasPrice)
)
const sellTokenBalanceAfterCancel = await sellToken.balanceOf(from.address)
// If we are looking at the CELO balance, take the fees spent into consideration.
const expectedBalance = sellCelo
? sellTokenBalanceBeforeCreation.minus(celoFees)
: sellTokenBalanceBeforeCreation
expect(sellTokenBalanceAfterCancel.toString()).toBe(expectedBalance.toString())
})
test('exchanger creates and executes an approved exchange proposal', async () => {
const from = await getKey(context.mnemonic, TestAccounts.GrandaMentoExchanger)
context.kit.connection.addAccount(from.privateKey)
context.kit.defaultAccount = from.address
const logger = baseLogger.child({ from: from.address })
const grandaMento = await context.kit.contracts.getGrandaMento()
const sellTokenBalanceBefore = await sellToken.balanceOf(from.address)
const buyTokenBalanceBefore = await buyToken.balanceOf(from.address)
const creationInfo = await createExchangeProposal(logger, from.address)
const approver = await getValidatorKey(context.mnemonic, 0)
await grandaMento
.approveExchangeProposal(creationInfo.proposalId)
.sendAndWaitForReceipt({
from: approver.address,
})
const vetoPeriodSeconds = await grandaMento.vetoPeriodSeconds()
// Sleep for the veto period, add 5 seconds for extra measure
const sleepPeriodMs = vetoPeriodSeconds.plus(5).times(1000).toNumber()
logger.debug(
{
sleepPeriodMs,
vetoPeriodSeconds,
},
'Sleeping so the veto period elapses'
)
await sleep(sleepPeriodMs)
// Executing from the approver to avoid needing to calculate additional gas paid
// by the approver in this test.
await grandaMento
.executeExchangeProposal(creationInfo.proposalId)
.sendAndWaitForReceipt({
from: approver.address,
})
logger.debug(
{
proposalId: creationInfo.proposalId,
},
'Executed exchange proposal'
)
const sellTokenBalanceAfter = await sellToken.balanceOf(from.address)
let expectedSellTokenBalanceAfter = sellTokenBalanceBefore.minus(sellAmount)
if (sellCelo) {
expectedSellTokenBalanceAfter = expectedSellTokenBalanceAfter.minus(
creationInfo.celoFees
)
}
expect(sellTokenBalanceAfter.toString()).toBe(expectedSellTokenBalanceAfter.toString())
const sortedOracles = await context.kit.contracts.getSortedOracles()
const celoStableTokenRate = (await sortedOracles.medianRate(stableTokenAddress)).rate
const exchangeRate = sellCelo
? celoStableTokenRate
: new BigNumber(1).div(celoStableTokenRate)
const buyAmount = getBuyAmount(exchangeRate, sellAmount, await grandaMento.spread())
const buyTokenBalanceAfter = await buyToken.balanceOf(from.address)
let expectedBuyTokenBalanceAfter = buyTokenBalanceBefore.plus(buyAmount)
if (!sellCelo) {
expectedBuyTokenBalanceAfter = expectedBuyTokenBalanceAfter.minus(
creationInfo.celoFees
)
}
expect(buyTokenBalanceAfter.toString()).toBe(expectedBuyTokenBalanceAfter.toString())
})
})
}
}
})
}
// exchangeRate is the price of the sell token quoted in buy token
function getBuyAmount(exchangeRate: BigNumber, sellAmount: BigNumber, spread: BigNumber.Value) {
return sellAmount.times(new BigNumber(1).minus(spread)).times(exchangeRate)
} | the_stack |
import * as maptalks from 'maptalks';
import BaseObject from './BaseObject';
import { ThreeLayer } from './index';
import { getBaseObjectMaterialType, Queue } from './type';
import { generateImage } from './util/CanvasUtil';
/**
*
*/
class BaseVectorTileLayer extends maptalks.TileLayer {
_opts: any;
_layer: ThreeLayer;
material: THREE.Material;
getMaterial: getBaseObjectMaterialType;
_baseObjectKeys: { [key: string]: Array<BaseObject> };
_loadTiles: { [key: string]: any };
_add: boolean;
_layerLaodTime: number;
intervalId: any;
constructor(url, options = {}) {
super(maptalks.Util.GUID(), maptalks.Util.extend({ urlTemplate: url }, options));
this._opts = null;
this._layer = null;
this.material = null;
this.getMaterial = null;
this._baseObjectKeys = {};
this._loadTiles = {};
this._add = null;
this._layerLaodTime = new Date().getTime();
}
isAsynchronous(): boolean {
return this._opts.worker;
}
/**
*get current all baseobject
*/
getBaseObjects(): BaseObject[] {
const loadTiles = this._loadTiles;
const baseos = [];
for (let key in loadTiles) {
const baseobjects = this._baseObjectKeys[key];
if (baseobjects && Array.isArray(baseobjects) && baseobjects.length) {
for (let i = 0, len = baseobjects.length; i < len; i++) {
baseos.push(baseobjects[i]);
}
}
}
return baseos;
}
/**
* This method should be overridden for event handling
* @param {*} type
* @param {*} e
*/
// eslint-disable-next-line no-unused-vars
onSelectMesh(type: string, e: any): void {
}
/**
* this is can override
* @param {*} index
* @param {*} json
*/
// eslint-disable-next-line no-unused-vars
formatBaseObjects(index: string, json: any): BaseObject[] {
return [];
}
//queue loop
// eslint-disable-next-line no-unused-vars
loopMessage(q: Queue): void {
}
/**
*
* @param {*} q
*/
getTileData(q: Queue): void {
const { key, url, callback, img } = q;
maptalks.Ajax.getJSON(url, {}, function (error, res) {
if (error) {
console.error(error);
callback(key, null, img);
} else {
callback(key, res, img);
}
});
}
_getCurentTileKeys() {
const tileGrids = this.getTiles().tileGrids || [];
const keys: Array<string> = [], keysMap: { [key: string]: boolean } = {};
for (let i = 0, len = tileGrids.length; i < len; i++) {
const d = tileGrids[i];
const tiles = d.tiles || [];
for (let j = 0, len1 = tiles.length; j < len1; j++) {
const { id } = tiles[j];
keys.push(id);
keysMap[id] = true;
}
}
return { keys, keysMap };
}
_isLoad(): boolean {
const { keys } = this._getCurentTileKeys();
const keys1 = Object.keys(this._renderer.tilesInView);
if (keys.length === keys1.length) {
return true;
}
return false;
}
_layerOnLoad(): void {
// This event will be triggered multiple times per unit time
const time = new Date().getTime();
const offsetTime = time - this._layerLaodTime;
if (offsetTime < 20) {
return;
}
this._layerLaodTime = time;
const tilesInView = this._renderer.tilesInView, loadTiles = this._loadTiles, threeLayer = this._layer, keys = this._baseObjectKeys;
const tilesInViewLen = Object.keys(tilesInView).length, loadTilesLen = Object.keys(loadTiles).length;
const needsRemoveBaseObjects: BaseObject[] = [];
if (tilesInViewLen && loadTilesLen) {
for (let index in loadTiles) {
if (!tilesInView[index]) {
if (keys[index]) {
(keys[index] || []).forEach(baseobject => {
needsRemoveBaseObjects.push(baseobject);
});
}
}
}
}
if (needsRemoveBaseObjects.length) {
threeLayer.removeMesh(needsRemoveBaseObjects, false);
}
if (tilesInViewLen && loadTilesLen) {
for (let index in tilesInView) {
if (!loadTiles[index]) {
if (keys[index]) {
const baseobject = keys[index];
threeLayer.addMesh(baseobject);
} else {
const { x, y, z } = this._getXYZOfIndex(index);
this.getTileUrl(x, y, z);
}
}
}
}
this._loadTiles = Object.assign({}, tilesInView);
this._diffCache();
}
_init(): void {
}
_workerLoad(e: any) {
const baseobject = e.target;
const img = baseobject._img;
img.currentCount++;
if (img.currentCount === img.needCount) {
img.src = generateImage(img._key, this._opts.debug);
}
}
_generateBaseObjects(index: string, res: any, img: any) {
if (res && img) {
const { keysMap } = this._getCurentTileKeys();
//not in current ,ignore
if (!keysMap[index]) {
img.src = generateImage(index, this._opts.debug);
return;
}
const baseobjects = this.formatBaseObjects(index, res);
if (baseobjects.length) {
img.needCount = baseobjects.length;
img.currentCount = 0;
for (let i = 0, len = baseobjects.length; i < len; i++) {
const baseobject = baseobjects[i];
baseobject._img = img;
baseobject._vt = this;
if (!this.isVisible()) {
baseobject.hide();
}
this._cachetile(index, baseobject);
if (!baseobject.isAsynchronous()) {
img.currentCount++;
}
}
this._layer.addMesh(baseobjects, false);
if (img.needCount === img.currentCount) {
img.src = generateImage(index, this._opts.debug);
}
if (this.isAsynchronous()) {
baseobjects.filter(baseobject => {
return baseobject.isAsynchronous();
}).forEach(baseobject => {
baseobject.on('workerload', this._workerLoad, this);
});
} else {
img.src = generateImage(index, this._opts.debug);
}
} else {
img.src = generateImage(index, this._opts.debug);
}
this._loadTiles[index] = true;
} else if (img) {
img.src = generateImage(index, this._opts.debug);
}
}
_diffCache(): void {
// if (this._layer.getMap().isInteracting()) {
// return;
// }
if (Object.keys(this._baseObjectKeys).length > this._renderer.tileCache.max) {
const tileCache = this._renderer.tileCache.data;
const tilesInView = this._renderer.tilesInView;
const needsRemoveBaseObjects: BaseObject[] = [];
for (let index in this._baseObjectKeys) {
if (!tileCache[index] && !tilesInView[index]) {
(this._baseObjectKeys[index] || []).forEach(baseobject => {
if (baseobject.isAdd) {
needsRemoveBaseObjects.push(baseobject);
}
});
this._diposeBaseObject(index);
delete this._baseObjectKeys[index];
}
}
// Batch deletion can have better performance
if (needsRemoveBaseObjects.length) {
this._layer.removeMesh(needsRemoveBaseObjects, false);
}
}
}
_diposeBaseObject(index: string): void {
const baseobjects = this._baseObjectKeys[index];
if (baseobjects && baseobjects.length) {
baseobjects.forEach(baseobject => {
(baseobject.getObject3d() as any).geometry.dispose();
if (baseobject._geometryCache) {
baseobject._geometryCache.dispose();
}
const bos = baseobject._baseObjects;
if (bos && bos.length) {
bos.forEach(bo => {
(bo.getObject3d() as any).geometry.dispose();
bo = null;
});
}
baseobject._datas = null;
baseobject._geometriesAttributes = null;
baseobject._faceMap = null;
baseobject._colorMap = null;
if (baseobject.pickObject3d) {
(baseobject.pickObject3d as any).geometry.dispose();
// baseobject.pickObject3d.material.dispose();
}
baseobject = null;
});
}
}
_cachetile(index: string, baseobject: BaseObject): void {
if (!this._baseObjectKeys[index]) {
this._baseObjectKeys[index] = [];
}
this._baseObjectKeys[index].push(baseobject);
}
_getXYZOfIndex(index: string) {
const splitstr = index.indexOf('_') > -1 ? '_' : '-';
let [y, x, z] = index.split(splitstr).slice(1, 4);
const x1 = parseInt(x);
const y1 = parseInt(y);
const z1 = parseInt(z);
return { x: x1, y: y1, z: z1 };
}
_getTileExtent(x: number, y: number, z: number): maptalks.Extent {
const map = this.getMap(),
res = map._getResolution(z),
tileConfig = this._getTileConfig(),
tileExtent = tileConfig.getTilePrjExtent(x, y, res);
return tileExtent;
}
/**
*
* @param {} x
* @param {*} y
* @param {*} z
*/
_getTileLngLatExtent(x: number, y: number, z: number): maptalks.Extent {
const tileExtent = this._getTileExtent(x, y, z);
let max = tileExtent.getMax(),
min = tileExtent.getMin();
const map = this.getMap();
const projection = map.getProjection();
min = projection.unproject(min);
max = projection.unproject(max);
return new maptalks.Extent(min, max);
}
}
export default BaseVectorTileLayer; | the_stack |
import {
chain,
externalSchematic,
noop,
Rule,
SchematicContext,
SchematicsException,
Tree,
} from '@angular-devkit/schematics';
import {
ArrowFunction,
CallExpression,
Expression,
Identifier,
Node,
SourceFile,
ts as tsMorph,
} from 'ts-morph';
import { Schema as SpartacusOptions } from '../../add-spartacus/schema';
import { Schema as SpartacusWrapperOptions } from '../../wrapper-module/schema';
import { ANGULAR_CORE } from '../constants';
import {
SPARTACUS_FEATURES_MODULE,
SPARTACUS_FEATURES_NG_MODULE,
SPARTACUS_SCHEMATICS,
} from '../libs-constants';
import {
featureFeatureModuleMapping,
featureSchematicConfigMapping,
getKeyByMappingValueOrThrow,
getSchematicsConfigByFeatureOrThrow,
} from '../schematics-config-mappings';
import { crossFeatureInstallationOrder } from './graph-utils';
import {
findDynamicImport,
getDynamicImportImportPath,
isImportedFrom,
isRelative,
staticImportExists,
} from './import-utils';
import {
addLibraryFeature,
checkAppStructure,
LibraryOptions,
Module,
SchematicConfig,
} from './lib-utils';
import { getModulePropertyInitializer, Import } from './new-module-utils';
import { createProgram } from './program';
import { getProjectTsConfigPaths } from './project-tsconfig-paths';
export interface FeatureModuleImports {
importPath: string;
moduleNode: Expression | Identifier;
}
/**
* Custom schematics configuration providers.
*/
export interface AdditionalProviders {
import: Import[];
content: string;
}
/**
* Additional schematics configurations / overrides.
*/
export interface AdditionalFeatureConfiguration<T = LibraryOptions> {
/**
* If specified, provides the specified configuration.
*/
providers?: AdditionalProviders | AdditionalProviders[];
/**
* If specified, overrides the pre-defined schematics options.
*/
options?: T;
}
/**
* Analysis result of wrapper module configuration.
*/
interface WrapperAnalysisResult {
/**
* Marker name.
*/
markerModuleName: string;
/**
* Options.
*/
wrapperOptions: SpartacusWrapperOptions;
}
/**
* Configures feature modules for the given array of features.
*
* Optionally, an override can be provided for the default
* schematics options and/or feature-schematics configuration.
*/
export function addFeatures<OPTIONS extends LibraryOptions>(
options: OPTIONS,
features: string[]
): Rule {
return (_tree: Tree, context: SchematicContext): Rule => {
if (options.debug) {
let message = `\n******************************\n`;
message += `Cross feature graph:\n`;
message += crossFeatureInstallationOrder.join(', ');
message += `\n******************************\n`;
context.logger.info(message);
}
/**
* In an existing Spartacus application, we don't want to
* force-install the dependent features.
*/
const featuresToInstall = options.internal?.existingSpartacusApplication
? options.features ?? []
: features;
const rules: Rule[] = [];
for (const feature of featuresToInstall) {
const schematicsConfiguration =
featureSchematicConfigMapping.get(feature);
if (!schematicsConfiguration) {
throw new SchematicsException(
`[Internal] No feature config found for ${feature}. ` +
`Please check if the schematics config is added to projects/schematics/src/shared/schematics-config-mappings.ts`
);
}
// TODO:#schematics - fix the interactivity for the CDS / ASM, etc.
const libraryOptions =
schematicsConfiguration.customConfig?.(options).options ?? options;
rules.push(addLibraryFeature(libraryOptions, schematicsConfiguration));
const wrappers = analyzeWrappers(schematicsConfiguration, libraryOptions);
for (const { wrapperOptions } of wrappers) {
rules.push(
externalSchematic(
SPARTACUS_SCHEMATICS,
'wrapper-module',
wrapperOptions
)
);
}
}
return chain(rules);
};
}
/**
* Analyzes the given schematics configuration for the wrapper modules.
* It builds the options for the wrapper schematic run,
* including the execution sequence.
*/
function analyzeWrappers<OPTIONS extends LibraryOptions>(
schematicsConfiguration: SchematicConfig,
options: OPTIONS
): WrapperAnalysisResult[] {
if (!schematicsConfiguration.importAfter?.length) {
return [];
}
const result: WrapperAnalysisResult[] = [];
for (const importAfterConfig of schematicsConfiguration.importAfter) {
const wrapperOptions: SpartacusWrapperOptions = {
scope: options.scope,
interactive: options.interactive,
project: options.project,
markerModuleName: importAfterConfig.markerModuleName,
featureModuleName: importAfterConfig.featureModuleName,
debug: options.debug,
};
const analysis: WrapperAnalysisResult = {
markerModuleName: importAfterConfig.markerModuleName,
wrapperOptions,
};
result.push(analysis);
}
return result;
}
/**
* If exists, it returns the spartacus-features.module.ts' source.
* Otherwise, it returns undefined.
*/
export function getSpartacusFeaturesModule(
tree: Tree,
basePath: string,
tsconfigPath: string
): SourceFile | undefined {
const { appSourceFiles } = createProgram(tree, basePath, tsconfigPath);
for (const sourceFile of appSourceFiles) {
if (
sourceFile
.getFilePath()
.includes(`${SPARTACUS_FEATURES_MODULE}.module.ts`)
) {
if (getSpartacusFeaturesNgModuleDecorator(sourceFile)) {
return sourceFile;
}
}
}
return undefined;
}
/**
* Returns the NgModule decorator, if exists.
*/
function getSpartacusFeaturesNgModuleDecorator(
sourceFile: SourceFile
): CallExpression | undefined {
let spartacusFeaturesModule: CallExpression | undefined;
function visitor(node: Node) {
if (Node.isCallExpression(node)) {
const expression = node.getExpression();
if (
Node.isIdentifier(expression) &&
expression.getText() === 'NgModule' &&
isImportedFrom(expression, ANGULAR_CORE)
) {
const classDeclaration = node.getFirstAncestorByKind(
tsMorph.SyntaxKind.ClassDeclaration
);
if (classDeclaration) {
const identifier = classDeclaration.getNameNode();
if (
identifier &&
identifier.getText() === SPARTACUS_FEATURES_NG_MODULE
) {
spartacusFeaturesModule = node;
}
}
}
}
node.forEachChild(visitor);
}
sourceFile.forEachChild(visitor);
return spartacusFeaturesModule;
}
/**
* For the given feature module name,
* returns the module configuration part
* of the given schematics feature config
*/
export function getModuleConfig(
featureModuleName: string,
featureConfig: SchematicConfig
): Module | undefined {
const featureModuleConfigs = ([] as Module[]).concat(
featureConfig.featureModule
);
for (const featureModuleConfig of featureModuleConfigs) {
if (featureModuleConfig.name === featureModuleName) {
return featureModuleConfig;
}
}
return undefined;
}
/**
* Analyzes the customers' application.
* It checks for presence of Spartacus features and
* whether they're configured or present in package.json.
*/
export function analyzeApplication<OPTIONS extends LibraryOptions>(
options: OPTIONS,
allFeatures: string[]
): Rule {
return (tree: Tree, context: SchematicContext) => {
const spartacusFeatureModuleExists = checkAppStructure(
tree,
options.project
);
/**
* Mutates the options, and sets the internal properties
* for later usage in other rules.
*/
options.internal = {
...options.internal,
existingSpartacusApplication: spartacusFeatureModuleExists,
};
if (!options.internal.existingSpartacusApplication) {
const dependentFeaturesMessage = createDependentFeaturesLog(
options,
allFeatures
);
if (dependentFeaturesMessage) {
context.logger.info(dependentFeaturesMessage);
}
return noop();
}
if (options.debug) {
context.logger.info(`⌛️ Analyzing application...`);
}
for (const targetFeature of options.features ?? []) {
const targetFeatureConfig =
getSchematicsConfigByFeatureOrThrow(targetFeature);
if (!targetFeatureConfig.importAfter?.length) {
continue;
}
const wrappers = analyzeWrappers(targetFeatureConfig, options);
for (const { wrapperOptions } of wrappers) {
const markerFeature = getKeyByMappingValueOrThrow(
featureFeatureModuleMapping,
wrapperOptions.markerModuleName
);
const markerFeatureConfig =
getSchematicsConfigByFeatureOrThrow(markerFeature);
const markerModuleConfig = getModuleConfig(
wrapperOptions.markerModuleName,
markerFeatureConfig
);
if (!markerModuleConfig) {
continue;
}
if (markerModuleExists(options, tree, markerModuleConfig)) {
continue;
}
const targetModuleName = wrapperOptions.featureModuleName;
const targetFeature = getKeyByMappingValueOrThrow(
featureFeatureModuleMapping,
targetModuleName
);
const targetFeatureConfig =
getSchematicsConfigByFeatureOrThrow(targetFeature);
const targetModuleConfig = getModuleConfig(
targetModuleName,
targetFeatureConfig
);
let message = `Attempted to append '${targetModuleName}' module `;
message += `from '${targetModuleConfig?.importPath}' after the `;
message += `'${wrapperOptions.markerModuleName}' from '${markerModuleConfig.importPath}', `;
message += `but could not find '${wrapperOptions.markerModuleName}'.`;
message += `\n`;
message += `Please make sure the '${markerFeature}' is installed by running:\n`;
message += `> ng add @spartacus/schematics --features=${markerFeature}`;
throw new SchematicsException(message);
}
}
if (options.debug) {
context.logger.info(`✅ Application analysis complete.`);
}
};
}
function markerModuleExists<OPTIONS extends LibraryOptions>(
options: OPTIONS,
tree: Tree,
markerModuleConfig: Module
): boolean {
const basePath = process.cwd();
const { buildPaths } = getProjectTsConfigPaths(tree, options.project);
for (const tsconfigPath of buildPaths) {
const { appSourceFiles } = createProgram(tree, basePath, tsconfigPath);
if (findFeatureModule(markerModuleConfig, appSourceFiles)) {
return true;
}
}
return false;
}
/**
* Searches through feature modules,
* and looks for either the static or
* dynamic imports.
*/
export function findFeatureModule(
moduleConfig: Module | Module[],
appSourceFiles: SourceFile[]
): SourceFile | undefined {
const moduleConfigs = ([] as Module[]).concat(moduleConfig);
for (const sourceFile of appSourceFiles) {
for (const moduleConfig of moduleConfigs) {
if (isStaticallyImported(sourceFile, moduleConfig)) {
return sourceFile;
}
if (isDynamicallyImported(sourceFile, moduleConfig)) {
return sourceFile;
}
}
}
return undefined;
}
function isStaticallyImported(
sourceFile: SourceFile,
moduleConfig: Module
): boolean {
if (
!staticImportExists(sourceFile, moduleConfig.importPath, moduleConfig.name)
) {
false;
}
const elements =
getModulePropertyInitializer(sourceFile, 'imports', false)?.getElements() ??
[];
for (const element of elements) {
const moduleName = element.getText().split('.').pop() ?? '';
if (moduleName === moduleConfig.name) {
return true;
}
}
return false;
}
function isDynamicallyImported(
sourceFile: SourceFile,
moduleConfig: Module
): boolean {
return !!findDynamicImport(sourceFile, {
moduleSpecifier: moduleConfig.importPath,
namedImports: [moduleConfig.name],
});
}
/**
* Peeks into the given dynamic import,
* and returns referenced local source file.
*/
export function getDynamicallyImportedLocalSourceFile(
dynamicImport: ArrowFunction
): SourceFile | undefined {
const importPath = getDynamicImportImportPath(dynamicImport) ?? '';
if (!isRelative(importPath)) {
return;
}
const wrapperModuleFileName = `${importPath.split('/').pop()}.ts`;
return dynamicImport
.getSourceFile()
.getProject()
.getSourceFile((s) => s.getFilePath().endsWith(wrapperModuleFileName));
}
function createDependentFeaturesLog(
options: SpartacusOptions,
features: string[]
): string | undefined {
const selectedFeatures = options.features ?? [];
const notSelectedFeatures = features.filter(
(feature) => !selectedFeatures.includes(feature)
);
if (!notSelectedFeatures.length) {
return;
}
return `\n⚙️ Configuring the dependent features of ${selectedFeatures.join(
', '
)}: ${notSelectedFeatures.join(', ')}\n`;
} | the_stack |
import {combine, createStore, Store} from 'effector'
const typecheck = '{global}'
describe('combine cases (should pass)', () => {
test('combine({R,G,B})', () => {
const R = createStore(233)
const G = createStore(88)
const B = createStore(1)
const store: Store<{R: number; G: number; B: number}> = combine({R, G, B})
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test('combine([R,G,B])', () => {
const R = createStore(233)
const G = createStore(88)
const B = createStore(1)
const store: Store<[number, number, number]> = combine([R, G, B])
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test('combine([Store<number>,Store<string>])', () => {
const sn = createStore(0)
const ss = createStore('')
const store = combine([sn, ss]).map(([n, s]) => {
n.toFixed // should have method on type
s.charAt // should have method on type
return null
})
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test('combine({Color})', () => {
const Color = createStore('#e95801')
const store: Store<{Color: string}> = combine({Color})
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test('combine([Color])', () => {
const Color = createStore('#e95801')
const store: Store<[string]> = combine([Color])
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test(`combine({R,G,B}, ({R,G,B}) => '~')`, () => {
const R = createStore(233)
const G = createStore(88)
const B = createStore(1)
const store: Store<string> = combine(
{R, G, B},
({R, G, B}) =>
'#' +
R.toString(16).padStart(2, '0') +
G.toString(16).padStart(2, '0') +
B.toString(16).padStart(2, '0'),
)
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test(`combine([R,G,B], ([R,G,B]) => '~')`, () => {
const R = createStore(233)
const G = createStore(88)
const B = createStore(1)
const store: Store<string> = combine(
[R, G, B],
([R, G, B]) =>
'#' +
R.toString(16).padStart(2, '0') +
G.toString(16).padStart(2, '0') +
B.toString(16).padStart(2, '0'),
)
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test(`combine([Store<number>,Store<string>], ([number,string]) => ...)`, () => {
const sn = createStore(0)
const ss = createStore('')
const store = combine([sn, ss], ([n, s]) => {
n.toFixed // should have method on type
s.charAt // should have method on type
return null
})
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test(`combine({Color}, ({Color}) => '~')`, () => {
const Color = createStore('#e95801')
const store: Store<string> = combine({Color}, ({Color}) => Color)
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test(`combine([Color], ([Color]) => '~')`, () => {
const Color = createStore('#e95801')
const store: Store<string> = combine([Color], ([Color]) => Color)
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test(`combine(Color, (Color) => '~')`, () => {
const Color = createStore('#e95801')
const store: Store<string> = combine(Color, Color => Color)
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test(`combine(R,G,B, (R,G,B) => '~')`, () => {
const R = createStore(233)
const G = createStore(88)
const B = createStore(1)
const store: Store<string> = combine(
R,
G,
B,
(R, G, B) =>
'#' +
R.toString(16).padStart(2, '0') +
G.toString(16).padStart(2, '0') +
B.toString(16).padStart(2, '0'),
)
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test('combine(R,G,B)', () => {
const R = createStore(233)
const G = createStore(88)
const B = createStore(1)
const store: Store<[number, number, number]> = combine(R, G, B)
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test('combine(Color)', () => {
const Color = createStore('#e95801')
const store: Store<[string]> = combine(Color)
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
})
describe('error inference (should fail with number -> string error)', () => {
test('combine({R,G,B})', () => {
const R = createStore(233)
const G = createStore(88)
const B = createStore(1)
//@ts-expect-error
const store: Store<{R: string; G: string; B: string}> = combine({R, G, B})
expect(typecheck).toMatchInlineSnapshot(`
"
Type 'Store<{ R: number; G: number; B: number; }>' is not assignable to type 'Store<{ R: string; G: string; B: string; }>'.
The types returned by 'getState()' are incompatible between these types.
Type '{ R: number; G: number; B: number; }' is not assignable to type '{ R: string; G: string; B: string; }'.
"
`)
})
test('combine([R,G,B])', () => {
const R = createStore(233)
const G = createStore(88)
const B = createStore(1)
//@ts-expect-error
const store: Store<[string, string, string]> = combine([R, G, B])
expect(typecheck).toMatchInlineSnapshot(`
"
Type 'Store<[number, number, number]>' is not assignable to type 'Store<[string, string, string]>'.
The types returned by 'getState()' are incompatible between these types.
Type '[number, number, number]' is not assignable to type '[string, string, string]'.
"
`)
})
test('combine({Color})', () => {
const Color = createStore('#e95801')
//@ts-expect-error
const store: Store<{Color: number}> = combine({Color})
expect(typecheck).toMatchInlineSnapshot(`
"
Type 'Store<{ Color: string; }>' is not assignable to type 'Store<{ Color: number; }>'.
The types returned by 'getState()' are incompatible between these types.
Type '{ Color: string; }' is not assignable to type '{ Color: number; }'.
"
`)
})
test('combine([Color])', () => {
const Color = createStore('#e95801')
//@ts-expect-error
const store: Store<[number]> = combine([Color])
expect(typecheck).toMatchInlineSnapshot(`
"
Type 'Store<[string]>' is not assignable to type 'Store<[number]>'.
The types returned by 'getState()' are incompatible between these types.
Type '[string]' is not assignable to type '[number]'.
"
`)
})
test(`combine({R,G,B}, ({R,G,B}) => '~')`, () => {
const R = createStore(233)
const G = createStore(88)
const B = createStore(1)
//@ts-expect-error
const store: Store<number> = combine(
{R, G, B},
({R, G, B}) =>
'#' +
R.toString(16).padStart(2, '0') +
G.toString(16).padStart(2, '0') +
B.toString(16).padStart(2, '0'),
)
expect(typecheck).toMatchInlineSnapshot(`
"
Type 'Store<string>' is not assignable to type 'Store<number>'.
The types returned by 'getState()' are incompatible between these types.
Type 'string' is not assignable to type 'number'.
"
`)
})
test(`combine([R,G,B], ([R,G,B]) => '~')`, () => {
const R = createStore(233)
const G = createStore(88)
const B = createStore(1)
//@ts-expect-error
const store: Store<number> = combine(
[R, G, B],
([R, G, B]) =>
'#' +
R.toString(16).padStart(2, '0') +
G.toString(16).padStart(2, '0') +
B.toString(16).padStart(2, '0'),
)
expect(typecheck).toMatchInlineSnapshot(`
"
Type 'Store<string>' is not assignable to type 'Store<number>'.
"
`)
})
test(`combine({Color}, ({Color}) => '~')`, () => {
const Color = createStore('#e95801')
//@ts-expect-error
const store: Store<number> = combine({Color}, ({Color}) => Color)
expect(typecheck).toMatchInlineSnapshot(`
"
Type 'Store<string>' is not assignable to type 'Store<number>'.
"
`)
})
test(`combine([Color], ([Color]) => '~')`, () => {
const Color = createStore('#e95801')
//@ts-expect-error
const store: Store<number> = combine([Color], ([Color]) => Color)
expect(typecheck).toMatchInlineSnapshot(`
"
Type 'Store<string>' is not assignable to type 'Store<number>'.
"
`)
})
test(`combine(Color, (Color) => '~')`, () => {
const Color = createStore('#e95801')
//@ts-expect-error
const store: Store<number> = combine(Color, Color => Color)
expect(typecheck).toMatchInlineSnapshot(`
"
Type 'Store<string>' is not assignable to type 'Store<number>'.
"
`)
})
test(`combine(R,G,B, (R,G,B) => '~')`, () => {
const R = createStore(233)
const G = createStore(88)
const B = createStore(1)
//@ts-expect-error
const store: Store<number> = combine(
R,
G,
B,
(R, G, B) =>
'#' +
R.toString(16).padStart(2, '0') +
G.toString(16).padStart(2, '0') +
B.toString(16).padStart(2, '0'),
)
expect(typecheck).toMatchInlineSnapshot(`
"
Type 'Store<string>' is not assignable to type 'Store<number>'.
"
`)
})
test('combine(R,G,B)', () => {
const R = createStore(233)
const G = createStore(88)
const B = createStore(1)
//@ts-expect-error
const store: Store<[string, string, string]> = combine(R, G, B)
expect(typecheck).toMatchInlineSnapshot(`
"
Type 'Store<[number, number, number]>' is not assignable to type 'Store<[string, string, string]>'.
"
`)
})
test('combine(Color)', () => {
const Color = createStore('#e95801')
//@ts-expect-error
const store: Store<number> = combine(Color)
expect(typecheck).toMatchInlineSnapshot(`
"
Type 'Store<[string]>' is not assignable to type 'Store<number>'.
The types returned by 'getState()' are incompatible between these types.
Type '[string]' is not assignable to type 'number'.
"
`)
})
})
test('possibly undefined store error message mismatch (should pass)', () => {
const $vacancyField = createStore<{id: string} | null>(null)
const $hasNotActiveFunnels = createStore<boolean>(true)
const result = combine({
hasNotActiveFunnels: $hasNotActiveFunnels,
vacancyId: $vacancyField.map(v => {
if (v) return v.id
}),
})
const resultType: Store<{
hasNotActiveFunnels: boolean
vacancyId: string | undefined
}> = result
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
describe('support optional parameters of explicit generic type', () => {
test('basic case (should pass)', () => {
type I = {
foo?: string | number
bar: number
}
const $store = createStore<string | number>('')
const $bar = createStore(0)
const result = combine<I>({
foo: $store,
bar: $bar,
})
const resultType: Store<{
foo?: string | number
bar: number
}> = result
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test('omit optional field (should pass)', () => {
type I = {
foo?: string | number
bar: number
}
const $bar = createStore(0)
const result: Store<I> = combine<I>({bar: $bar})
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test('plain values support (should pass)', () => {
type I = {
foo?: string | number
bar: number
}
const $bar = createStore(0)
const result: Store<I> = combine<I>({
foo: 0,
bar: $bar,
})
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
/**
* wide input is not supported because if you explicitly define desired type
* then what's the point in passing more values?
*/
test('wide input is not supported (should fail)', () => {
type I = {
foo?: string | number
bar: number
}
const $bar = createStore(0)
//@ts-expect-error
const result = combine<I>({
foo: 0,
bar: $bar,
baz: $bar,
})
expect(typecheck).toMatchInlineSnapshot(`
"
No overload matches this call.
Overload 1 of 18, '(shape: { foo?: string | number | Store<string | number> | undefined; bar: number | Store<number>; }): Store<I>', gave the following error.
Argument of type '{ foo: number; bar: Store<number>; baz: Store<number>; }' is not assignable to parameter of type '{ foo?: string | number | Store<string | number> | undefined; bar: number | Store<number>; }'.
Object literal may only specify known properties, and 'baz' does not exist in type '{ foo?: string | number | Store<string | number> | undefined; bar: number | Store<number>; }'.
Overload 2 of 18, '(shape: I): Store<{ foo?: string | number | undefined; bar: number; }>', gave the following error.
Type 'Store<number>' is not assignable to type 'number'.
"
`)
})
})
test('support plain values as well as stores', () => {
const $bar = createStore(0)
const result: Store<{foo: number; bar: number}> = combine({
foo: 0,
bar: $bar,
})
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
describe("#531 large unions doesn't brake combine", () => {
test('infinite type', () => {
type Currency =
| 'usd'
| 'eur'
| 'cny'
| 'uah'
| 'byn'
| 'thb'
| 'rub'
| 'azn'
| 'kzt'
| 'kgs'
| 'uzs'
| 'tzs'
| 'kes'
| 'zar'
| 'ron'
| 'mdl'
| 'ils'
| 'inr'
| 'pln'
| 'chf'
| 'gbp'
const initial = 'usd' as Currency
const $currency = createStore(initial)
const $result = combine({
currency: $currency,
})
const $_: Store<{currency: Currency}> = $result
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test('no any', () => {
type Currency =
| 'usd'
| 'eur'
| 'cny'
| 'uah'
| 'byn'
| 'thb'
| 'rub'
| 'azn'
| 'kzt'
| 'kgs'
| 'uzs'
| 'tzs'
| 'kes'
| 'zar'
| 'ron'
| 'mdl'
| 'ils'
| 'inr'
| 'pln'
| 'chf'
| 'gbp'
const initial = 'usd' as Currency
const $currency = createStore(initial)
const $result = combine({
currency: $currency,
})
//@ts-expect-error
const $_: Store<{currency: number}> = $result
expect(typecheck).toMatchInlineSnapshot(`
"
Type 'Store<{ currency: Currency; }>' is not assignable to type 'Store<{ currency: number; }>'.
The types returned by 'getState()' are incompatible between these types.
Type '{ currency: Currency; }' is not assignable to type '{ currency: number; }'.
"
`)
})
}) | the_stack |
module Fayde.Controls {
export interface IIsEnabledListener {
Callback: (newIsEnabled: boolean) => void;
Detach();
}
export class ControlNode extends FENode {
XObject: Control;
TemplateRoot: FrameworkElement;
IsFocused: boolean = false;
LayoutUpdater: minerva.controls.control.ControlUpdater;
constructor(xobj: Control) {
super(xobj);
}
TabTo() {
var xobj = this.XObject;
return xobj.IsEnabled && xobj.IsTabStop && this.Focus();
}
ApplyTemplateWithError(error: BError): boolean {
if (!super.ApplyTemplateWithError(error))
return false;
this.XObject.UpdateValidationState();
return true;
}
DoApplyTemplateWithError(error: BError): boolean {
var xobj = this.XObject;
var t = xobj.Template;
var root: UIElement;
if (t) root = t.GetVisualTree(xobj);
if (!root && !(root = this.GetDefaultVisualTree()))
return false;
if (this.TemplateRoot && this.TemplateRoot !== root)
this.DetachVisualChild(this.TemplateRoot, error)
this.TemplateRoot = <FrameworkElement>root;
if (this.TemplateRoot)
this.AttachVisualChild(this.TemplateRoot, error);
if (error.Message)
return false;
//TODO: Deployment Loaded Event (Async)
return true;
}
GetDefaultVisualTree(): UIElement { return undefined; }
OnIsAttachedChanged(newIsAttached: boolean) {
super.OnIsAttachedChanged(newIsAttached);
if (!newIsAttached)
Media.VSM.VisualStateManager.Deactivate(this.XObject, this.TemplateRoot);
else
Media.VSM.VisualStateManager.Activate(this.XObject, this.TemplateRoot);
}
OnParentChanged(oldParentNode: XamlNode, newParentNode: XamlNode) {
super.OnParentChanged(oldParentNode, newParentNode);
this.IsEnabled = newParentNode ? newParentNode.IsEnabled : true;
}
OnTemplateChanged(oldTemplate: ControlTemplate, newTemplate: ControlTemplate) {
var subtree = this.SubtreeNode;
if (subtree) {
var error = new BError();
if (!this.DetachVisualChild(<UIElement>subtree.XObject, error))
error.ThrowException();
}
this.LayoutUpdater.invalidateMeasure();
}
get IsEnabled(): boolean { return this.XObject.IsEnabled; }
set IsEnabled(value: boolean) {
Providers.IsEnabledStore.EmitInheritedChanged(this, value);
this.OnIsEnabledChanged(undefined, value);
}
OnIsEnabledChanged(oldValue: boolean, newValue: boolean) {
if (!newValue) {
this.IsMouseOver = false;
if (Surface.RemoveFocusFrom(this.XObject)) {
TabNavigationWalker.Focus(this, true);
}
this.ReleaseMouseCapture();
}
super.OnIsEnabledChanged(oldValue, newValue);
}
Focus(recurse?: boolean): boolean {
return Surface.Focus(this.XObject, recurse);
}
CanCaptureMouse(): boolean { return this.XObject.IsEnabled; }
}
export class Control extends FrameworkElement implements Providers.IIsPropertyInheritable {
XamlNode: ControlNode;
CreateNode(): ControlNode { return new ControlNode(this); }
CreateLayoutUpdater() { return new minerva.controls.control.ControlUpdater(); }
constructor() {
super();
UIReaction<boolean>(Control.IsEnabledProperty, (upd, nv, ov, control?: Control) => {
var args = {
Property: Control.IsEnabledProperty,
OldValue: ov,
NewValue: nv
};
control.OnIsEnabledChanged(args);
if (nv !== true)
control.XamlNode.IsMouseOver = false;
control.UpdateVisualState();
control.IsEnabledChanged.raiseAsync(control, args);
}, false, true, this);
//TODO: Do these make sense? These properties are usually bound to child visuals which will invalidate
UIReaction<minerva.Thickness>(Control.PaddingProperty, (upd, nv, ov) => upd.invalidateMeasure(), false, true, this);
UIReaction<minerva.Thickness>(Control.BorderThicknessProperty, (upd, nv, ov) => upd.invalidateMeasure(), false, true, this);
UIReaction<HorizontalAlignment>(Control.HorizontalContentAlignmentProperty, (upd, nv, ov) => upd.invalidateArrange(), false, true, this);
UIReaction<VerticalAlignment>(Control.VerticalContentAlignmentProperty, (upd, nv, ov) => upd.invalidateArrange(), false, true, this);
}
static BackgroundProperty = DependencyProperty.RegisterCore("Background", () => Media.Brush, Control);
static BorderBrushProperty = DependencyProperty.RegisterCore("BorderBrush", () => Media.Brush, Control);
static BorderThicknessProperty = DependencyProperty.RegisterCore("BorderThickness", () => Thickness, Control);
static FontFamilyProperty = InheritableOwner.FontFamilyProperty.ExtendTo(Control);
static FontSizeProperty = InheritableOwner.FontSizeProperty.ExtendTo(Control);
static FontStretchProperty = InheritableOwner.FontStretchProperty.ExtendTo(Control);
static FontStyleProperty = InheritableOwner.FontStyleProperty.ExtendTo(Control);
static FontWeightProperty = InheritableOwner.FontWeightProperty.ExtendTo(Control);
static ForegroundProperty = InheritableOwner.ForegroundProperty.ExtendTo(Control);
static HorizontalContentAlignmentProperty: DependencyProperty = DependencyProperty.Register("HorizontalContentAlignment", () => new Enum(HorizontalAlignment), Control, HorizontalAlignment.Center);
static IsEnabledProperty = DependencyProperty.Register("IsEnabled", () => Boolean, Control, true);
static IsTabStopProperty = DependencyProperty.Register("IsTabStop", () => Boolean, Control, true);
static PaddingProperty = DependencyProperty.RegisterCore("Padding", () => Thickness, Control);
static TabIndexProperty = DependencyProperty.Register("TabIndex", () => Number, Control);
static TabNavigationProperty = DependencyProperty.Register("TabNavigation", () => new Enum(Input.KeyboardNavigationMode), Control, Input.KeyboardNavigationMode.Local);
static TemplateProperty = DependencyProperty.Register("Template", () => ControlTemplate, Control, undefined, (d, args) => (<Control>d).XamlNode.OnTemplateChanged(args.OldValue, args.NewValue));
static VerticalContentAlignmentProperty = DependencyProperty.Register("VerticalContentAlignment", () => new Enum(VerticalAlignment), Control, VerticalAlignment.Center);
IsInheritable(propd: DependencyProperty): boolean {
if (ControlInheritedProperties.indexOf(propd) > -1)
return true;
return super.IsInheritable(propd);
}
Background: Media.Brush;
BorderBrush: Media.Brush;
BorderThickness: Thickness;
FontFamily: string;
FontSize: number;
FontStretch: string;
FontStyle: string;
FontWeight: FontWeight;
Foreground: Media.Brush;
HorizontalContentAlignment: HorizontalAlignment;
IsEnabled: boolean;
IsTabStop: boolean;
Padding: Thickness;
TabIndex: number;
TabNavigation: Input.KeyboardNavigationMode;
Template: ControlTemplate;
VerticalContentAlignment: VerticalAlignment;
get IsFocused() { return this.XamlNode.IsFocused; }
GetTemplateChild(childName: string, type?: Function): DependencyObject {
var root = this.XamlNode.TemplateRoot;
if (!root)
return;
var n = root.XamlNode.FindName(childName);
if (!n)
return;
var xobj = n.XObject;
if (!type || (xobj instanceof type))
return <DependencyObject>xobj;
}
ApplyTemplate(): boolean {
var error = new BError();
var result = this.XamlNode.ApplyTemplateWithError(error);
if (error.Message)
error.ThrowException();
return result;
}
GetDefaultStyle(): Style {
return undefined;
}
IsEnabledChanged = new nullstone.Event<DependencyPropertyChangedEventArgs>();
OnIsEnabledChanged(e: IDependencyPropertyChangedEventArgs) { }
OnGotFocus(e: RoutedEventArgs) {
this.XamlNode.IsFocused = true;
this.UpdateValidationState();
}
OnLostFocus(e: RoutedEventArgs) {
this.XamlNode.IsFocused = false;
this.UpdateValidationState();
}
UpdateVisualState(useTransitions?: boolean) {
useTransitions = useTransitions !== false;
var gotoFunc = (state: string) => Media.VSM.VisualStateManager.GoToState(this, state, useTransitions);
this.GoToStates(gotoFunc);
}
GoToStates(gotoFunc: (state: string) => boolean) {
this.GoToStateCommon(gotoFunc);
this.GoToStateFocus(gotoFunc);
this.GoToStateSelection(gotoFunc);
}
GoToStateCommon(gotoFunc: (state: string) => boolean): boolean {
if (!this.IsEnabled)
return gotoFunc("Disabled");
if (this.IsMouseOver)
return gotoFunc("MouseOver");
return gotoFunc("Normal");
}
GoToStateFocus(gotoFunc: (state: string) => boolean): boolean {
if (this.IsFocused && this.IsEnabled)
return gotoFunc("Focused");
return gotoFunc("Unfocused");
}
GoToStateSelection(gotoFunc: (state: string) => boolean): boolean {
return false;
}
UpdateValidationState (valid?: boolean) {
if (valid === undefined) {
var errors = Validation.GetErrors(this);
valid = errors.Count < 1;
}
var gotoFunc = (state: string) => Media.VSM.VisualStateManager.GoToState(this, state, true);
this.GoToStateValidation(valid, gotoFunc);
}
GoToStateValidation (valid: boolean, gotoFunc: (state: string) => boolean) {
if (valid)
return gotoFunc("Valid");
else if (this.IsFocused)
return gotoFunc("InvalidFocused");
return gotoFunc("InvalidUnfocused");
}
}
Fayde.CoreLibrary.add(Control);
Control.IsEnabledProperty.Store = Providers.IsEnabledStore.Instance;
var ControlInheritedProperties = [
Control.FontFamilyProperty,
Control.FontSizeProperty,
Control.FontStretchProperty,
Control.FontStyleProperty,
Control.FontWeightProperty,
Control.ForegroundProperty
];
export interface ITemplateVisualStateDefinition {
Name: string;
GroupName: string;
}
export var TemplateVisualStates = nullstone.CreateTypedAnnotation<ITemplateVisualStateDefinition>("TemplateVisualState");
export interface ITemplatePartDefinition {
Name: string;
Type: Function;
}
export var TemplateParts = nullstone.CreateTypedAnnotation<ITemplatePartDefinition>("TemplatePart");
} | the_stack |
import type {Mutable, Proto, ObserverType} from "@swim/util";
import type {FastenerOwner, Fastener} from "@swim/component";
import type {AnyModel, Model} from "./Model";
import {ModelRelationInit, ModelRelationClass, ModelRelation} from "./ModelRelation";
/** @internal */
export type ModelRefType<F extends ModelRef<any, any>> =
F extends ModelRef<any, infer M> ? M : never;
/** @public */
export interface ModelRefInit<M extends Model = Model> extends ModelRelationInit<M> {
extends?: {prototype: ModelRef<any, any>} | string | boolean | null;
key?: string | boolean;
}
/** @public */
export type ModelRefDescriptor<O = unknown, M extends Model = Model, I = {}> = ThisType<ModelRef<O, M> & I> & ModelRefInit<M> & Partial<I>;
/** @public */
export interface ModelRefClass<F extends ModelRef<any, any> = ModelRef<any, any>> extends ModelRelationClass<F> {
}
/** @public */
export interface ModelRefFactory<F extends ModelRef<any, any> = ModelRef<any, any>> extends ModelRefClass<F> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): ModelRefFactory<F> & I;
define<O, M extends Model = Model>(className: string, descriptor: ModelRefDescriptor<O, M>): ModelRefFactory<ModelRef<any, M>>;
define<O, M extends Model = Model>(className: string, descriptor: {observes: boolean} & ModelRefDescriptor<O, M, ObserverType<M>>): ModelRefFactory<ModelRef<any, M>>;
define<O, M extends Model = Model, I = {}>(className: string, descriptor: {implements: unknown} & ModelRefDescriptor<O, M, I>): ModelRefFactory<ModelRef<any, M> & I>;
define<O, M extends Model = Model, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & ModelRefDescriptor<O, M, I & ObserverType<M>>): ModelRefFactory<ModelRef<any, M> & I>;
<O, M extends Model = Model>(descriptor: ModelRefDescriptor<O, M>): PropertyDecorator;
<O, M extends Model = Model>(descriptor: {observes: boolean} & ModelRefDescriptor<O, M, ObserverType<M>>): PropertyDecorator;
<O, M extends Model = Model, I = {}>(descriptor: {implements: unknown} & ModelRefDescriptor<O, M, I>): PropertyDecorator;
<O, M extends Model = Model, I = {}>(descriptor: {implements: unknown; observes: boolean} & ModelRefDescriptor<O, M, I & ObserverType<M>>): PropertyDecorator;
}
/** @public */
export interface ModelRef<O = unknown, M extends Model = Model> extends ModelRelation<O, M> {
(): M | null;
(model: AnyModel<M> | null, target?: Model | null, key?: string): O;
/** @override */
get fastenerType(): Proto<ModelRef<any, any>>;
/** @protected @override */
onInherit(superFastener: Fastener): void;
readonly model: M | null;
getModel(): M;
setModel(model: AnyModel<M> | null, target?: Model | null, key?: string): M | null;
attachModel(model?: AnyModel<M>, target?: Model | null): M;
detachModel(): M | null;
insertModel(parent?: Model | null, model?: AnyModel<M>, target?: Model | null, key?: string): M;
removeModel(): M | null;
deleteModel(): M | null;
/** @internal @override */
bindModel(model: Model, target: Model | null): void;
/** @internal @override */
unbindModel(model: Model): void;
/** @override */
detectModel(model: Model): M | null;
/** @internal */
get key(): string | undefined; // optional prototype field
}
/** @public */
export const ModelRef = (function (_super: typeof ModelRelation) {
const ModelRef: ModelRefFactory = _super.extend("ModelRef");
Object.defineProperty(ModelRef.prototype, "fastenerType", {
get: function (this: ModelRef): Proto<ModelRef<any, any>> {
return ModelRef;
},
configurable: true,
});
ModelRef.prototype.onInherit = function (this: ModelRef, superFastener: ModelRef): void {
this.setModel(superFastener.model);
};
ModelRef.prototype.getModel = function <M extends Model>(this: ModelRef<unknown, M>): M {
const model = this.model;
if (model === null) {
let message = model + " ";
if (this.name.length !== 0) {
message += this.name + " ";
}
message += "model";
throw new TypeError(message);
}
return model;
};
ModelRef.prototype.setModel = function <M extends Model>(this: ModelRef<unknown, M>, newModel: AnyModel<M> | null, target?: Model | null, key?: string): M | null {
if (newModel !== null) {
newModel = this.fromAny(newModel);
}
let oldModel = this.model;
if (oldModel !== newModel) {
if (target === void 0) {
target = null;
}
let parent: Model | null;
if (this.binds && (parent = this.parentModel, parent !== null)) {
if (oldModel !== null && oldModel.parent === parent) {
if (target === null) {
target = oldModel.nextSibling;
}
oldModel.remove();
}
if (newModel !== null) {
if (key === void 0) {
key = this.key;
}
this.insertChild(parent, newModel, target, key);
}
oldModel = this.model;
}
if (oldModel !== newModel) {
if (oldModel !== null) {
this.willDetachModel(oldModel);
(this as Mutable<typeof this>).model = null;
this.onDetachModel(oldModel);
this.deinitModel(oldModel);
this.didDetachModel(oldModel);
}
if (newModel !== null) {
this.willAttachModel(newModel, target);
(this as Mutable<typeof this>).model = newModel;
this.onAttachModel(newModel, target);
this.initModel(newModel);
this.didAttachModel(newModel, target);
}
}
}
return oldModel;
};
ModelRef.prototype.attachModel = function <M extends Model>(this: ModelRef<unknown, M>, newModel?: AnyModel<M>, target?: Model | null): M {
const oldModel = this.model;
if (newModel !== void 0 && newModel !== null) {
newModel = this.fromAny(newModel);
} else if (oldModel === null) {
newModel = this.createModel();
} else {
newModel = oldModel;
}
if (newModel !== oldModel) {
if (target === void 0) {
target = null;
}
if (oldModel !== null) {
this.willDetachModel(oldModel);
(this as Mutable<typeof this>).model = null;
this.onDetachModel(oldModel);
this.deinitModel(oldModel);
this.didDetachModel(oldModel);
}
this.willAttachModel(newModel, target);
(this as Mutable<typeof this>).model = newModel;
this.onAttachModel(newModel, target);
this.initModel(newModel);
this.didAttachModel(newModel, target);
}
return newModel;
};
ModelRef.prototype.detachModel = function <M extends Model>(this: ModelRef<unknown, M>): M | null {
const oldModel = this.model;
if (oldModel !== null) {
this.willDetachModel(oldModel);
(this as Mutable<typeof this>).model = null;
this.onDetachModel(oldModel);
this.deinitModel(oldModel);
this.didDetachModel(oldModel);
}
return oldModel;
};
ModelRef.prototype.insertModel = function <M extends Model>(this: ModelRef<unknown, M>, parent?: Model | null, newModel?: AnyModel<M>, target?: Model | null, key?: string): M {
if (newModel !== void 0 && newModel !== null) {
newModel = this.fromAny(newModel);
} else {
const oldModel = this.model;
if (oldModel === null) {
newModel = this.createModel();
} else {
newModel = oldModel;
}
}
if (parent === void 0 || parent === null) {
parent = this.parentModel;
}
if (target === void 0) {
target = null;
}
if (key === void 0) {
key = this.key;
}
if (parent !== null && (newModel.parent !== parent || newModel.key !== key)) {
this.insertChild(parent, newModel, target, key);
}
const oldModel = this.model;
if (newModel !== oldModel) {
if (oldModel !== null) {
this.willDetachModel(oldModel);
(this as Mutable<typeof this>).model = null;
this.onDetachModel(oldModel);
this.deinitModel(oldModel);
this.didDetachModel(oldModel);
oldModel.remove();
}
this.willAttachModel(newModel, target);
(this as Mutable<typeof this>).model = newModel;
this.onAttachModel(newModel, target);
this.initModel(newModel);
this.didAttachModel(newModel, target);
}
return newModel;
};
ModelRef.prototype.removeModel = function <M extends Model>(this: ModelRef<unknown, M>): M | null {
const model = this.model;
if (model !== null) {
model.remove();
}
return model;
};
ModelRef.prototype.deleteModel = function <M extends Model>(this: ModelRef<unknown, M>): M | null {
const model = this.detachModel();
if (model !== null) {
model.remove();
}
return model;
};
ModelRef.prototype.bindModel = function <M extends Model>(this: ModelRef<unknown, M>, model: Model, target: Model | null): void {
if (this.binds && this.model === null) {
const newModel = this.detectModel(model);
if (newModel !== null) {
this.willAttachModel(newModel, target);
(this as Mutable<typeof this>).model = newModel;
this.onAttachModel(newModel, target);
this.initModel(newModel);
this.didAttachModel(newModel, target);
}
}
};
ModelRef.prototype.unbindModel = function <M extends Model>(this: ModelRef<unknown, M>, model: Model): void {
if (this.binds) {
const oldModel = this.detectModel(model);
if (oldModel !== null && this.model === oldModel) {
this.willDetachModel(oldModel);
(this as Mutable<typeof this>).model = null;
this.onDetachModel(oldModel);
this.deinitModel(oldModel);
this.didDetachModel(oldModel);
}
}
};
ModelRef.prototype.detectModel = function <M extends Model>(this: ModelRef<unknown, M>, model: Model): M | null {
const key = this.key;
if (key !== void 0 && key === model.key) {
return model as M;
}
return null;
};
ModelRef.construct = function <F extends ModelRef<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F {
if (fastener === null) {
fastener = function (model?: AnyModel<ModelRefType<F>> | null, target?: Model | null, key?: string): ModelRefType<F> | null | FastenerOwner<F> {
if (model === void 0) {
return fastener!.model;
} else {
fastener!.setModel(model, target, key);
return fastener!.owner;
}
} as F;
delete (fastener as Partial<Mutable<F>>).name; // don't clobber prototype name
Object.setPrototypeOf(fastener, fastenerClass.prototype);
}
fastener = _super.construct(fastenerClass, fastener, owner) as F;
(fastener as Mutable<typeof fastener>).model = null;
return fastener;
};
ModelRef.define = function <O, M extends Model>(className: string, descriptor: ModelRefDescriptor<O, M>): ModelRefFactory<ModelRef<any, M>> {
let superClass = descriptor.extends as ModelRefFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
if (descriptor.key === true) {
Object.defineProperty(descriptor, "key", {
value: className,
configurable: true,
});
} else if (descriptor.key === false) {
Object.defineProperty(descriptor, "key", {
value: void 0,
configurable: true,
});
}
if (superClass === void 0 || superClass === null) {
superClass = this;
}
const fastenerClass = superClass.extend(className, descriptor);
fastenerClass.construct = function (fastenerClass: {prototype: ModelRef<any, any>}, fastener: ModelRef<O, M> | null, owner: O): ModelRef<O, M> {
fastener = superClass!.construct(fastenerClass, fastener, owner);
if (affinity !== void 0) {
fastener.initAffinity(affinity);
}
if (inherits !== void 0) {
fastener.initInherits(inherits);
}
return fastener;
};
return fastenerClass;
};
return ModelRef;
})(ModelRelation); | the_stack |
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';
/**
* @class
* Operations
* __NOTE__: An instance of this class is automatically created for an
* instance of the MLTeamAccountManagementClient.
*/
export interface Operations {
/**
* Lists all of the available Azure Machine Learning Team Accounts REST API
* operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>;
/**
* Lists all of the available Azure Machine Learning Team Accounts REST API
* operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationListResult} [result] - The deserialized result object if an error did not occur.
* See {@link OperationListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>;
list(callback: ServiceCallback<models.OperationListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void;
}
/**
* @class
* Accounts
* __NOTE__: An instance of this class is automatically created for an
* instance of the MLTeamAccountManagementClient.
*/
export interface Accounts {
/**
* Gets the properties of the specified machine learning team account.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Account>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Account>>;
/**
* Gets the properties of the specified machine learning team account.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Account} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Account} [result] - The deserialized result object if an error did not occur.
* See {@link Account} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Account>;
get(resourceGroupName: string, accountName: string, callback: ServiceCallback<models.Account>): void;
get(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Account>): void;
/**
* Creates or updates a team account with the specified parameters.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {object} parameters The parameters for creating or updating a machine
* learning team account.
*
* @param {string} parameters.vsoAccountId The fully qualified arm id of the
* vso account to be used for this team account.
*
* @param {string} [parameters.description] The description of this workspace.
*
* @param {string} [parameters.friendlyName] The friendly name for this
* workspace. This will be the workspace name in the arm id when the workspace
* object gets created
*
* @param {string} parameters.keyVaultId The fully qualified arm id of the user
* key vault.
*
* @param {string} [parameters.seats] The no of users/seats who can access this
* team account. This property defines the charge on the team account.
*
* @param {object} parameters.storageAccount The properties of the storage
* account for the machine learning team account.
*
* @param {string} parameters.storageAccount.storageAccountId The fully
* qualified arm Id of the storage account.
*
* @param {string} parameters.storageAccount.accessKey The access key to the
* storage account.
*
* @param {string} parameters.location The location of the resource. This
* cannot be changed after the resource is created.
*
* @param {object} [parameters.tags] The tags of the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Account>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, accountName: string, parameters: models.Account, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Account>>;
/**
* Creates or updates a team account with the specified parameters.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {object} parameters The parameters for creating or updating a machine
* learning team account.
*
* @param {string} parameters.vsoAccountId The fully qualified arm id of the
* vso account to be used for this team account.
*
* @param {string} [parameters.description] The description of this workspace.
*
* @param {string} [parameters.friendlyName] The friendly name for this
* workspace. This will be the workspace name in the arm id when the workspace
* object gets created
*
* @param {string} parameters.keyVaultId The fully qualified arm id of the user
* key vault.
*
* @param {string} [parameters.seats] The no of users/seats who can access this
* team account. This property defines the charge on the team account.
*
* @param {object} parameters.storageAccount The properties of the storage
* account for the machine learning team account.
*
* @param {string} parameters.storageAccount.storageAccountId The fully
* qualified arm Id of the storage account.
*
* @param {string} parameters.storageAccount.accessKey The access key to the
* storage account.
*
* @param {string} parameters.location The location of the resource. This
* cannot be changed after the resource is created.
*
* @param {object} [parameters.tags] The tags of the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Account} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Account} [result] - The deserialized result object if an error did not occur.
* See {@link Account} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, accountName: string, parameters: models.Account, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Account>;
createOrUpdate(resourceGroupName: string, accountName: string, parameters: models.Account, callback: ServiceCallback<models.Account>): void;
createOrUpdate(resourceGroupName: string, accountName: string, parameters: models.Account, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Account>): void;
/**
* Deletes a machine learning team account.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes a machine learning team account.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, accountName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Updates a machine learning team account with the specified parameters.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {object} parameters The parameters for updating a machine learning
* team account.
*
* @param {object} [parameters.tags] The resource tags for the machine learning
* team account.
*
* @param {string} [parameters.description] The description of this workspace.
*
* @param {string} [parameters.friendlyName] The friendly name for this
* workspace. This will be the workspace name in the arm id when the workspace
* object gets created
*
* @param {string} [parameters.seats] The no of users/seats who can access this
* team account. This property defines the charge on the team account.
*
* @param {string} [parameters.storageAccountKey] The key for storage account
* associated with this team account
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Account>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, accountName: string, parameters: models.AccountUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Account>>;
/**
* Updates a machine learning team account with the specified parameters.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {object} parameters The parameters for updating a machine learning
* team account.
*
* @param {object} [parameters.tags] The resource tags for the machine learning
* team account.
*
* @param {string} [parameters.description] The description of this workspace.
*
* @param {string} [parameters.friendlyName] The friendly name for this
* workspace. This will be the workspace name in the arm id when the workspace
* object gets created
*
* @param {string} [parameters.seats] The no of users/seats who can access this
* team account. This property defines the charge on the team account.
*
* @param {string} [parameters.storageAccountKey] The key for storage account
* associated with this team account
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Account} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Account} [result] - The deserialized result object if an error did not occur.
* See {@link Account} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, accountName: string, parameters: models.AccountUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Account>;
update(resourceGroupName: string, accountName: string, parameters: models.AccountUpdateParameters, callback: ServiceCallback<models.Account>): void;
update(resourceGroupName: string, accountName: string, parameters: models.AccountUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Account>): void;
/**
* Lists all the available machine learning team accounts under the specified
* resource group.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AccountListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccountListResult>>;
/**
* Lists all the available machine learning team accounts under the specified
* resource group.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AccountListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AccountListResult} [result] - The deserialized result object if an error did not occur.
* See {@link AccountListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccountListResult>;
listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.AccountListResult>): void;
listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccountListResult>): void;
/**
* Lists all the available machine learning team accounts under the specified
* subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AccountListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccountListResult>>;
/**
* Lists all the available machine learning team accounts under the specified
* subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AccountListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AccountListResult} [result] - The deserialized result object if an error did not occur.
* See {@link AccountListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccountListResult>;
list(callback: ServiceCallback<models.AccountListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccountListResult>): void;
/**
* Lists all the available machine learning team accounts under the specified
* resource group.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AccountListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccountListResult>>;
/**
* Lists all the available machine learning team accounts under the specified
* resource group.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AccountListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AccountListResult} [result] - The deserialized result object if an error did not occur.
* See {@link AccountListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccountListResult>;
listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.AccountListResult>): void;
listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccountListResult>): void;
/**
* Lists all the available machine learning team accounts under the specified
* subscription.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AccountListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccountListResult>>;
/**
* Lists all the available machine learning team accounts under the specified
* subscription.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AccountListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AccountListResult} [result] - The deserialized result object if an error did not occur.
* See {@link AccountListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccountListResult>;
listNext(nextPageLink: string, callback: ServiceCallback<models.AccountListResult>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccountListResult>): void;
}
/**
* @class
* Workspaces
* __NOTE__: An instance of this class is automatically created for an
* instance of the MLTeamAccountManagementClient.
*/
export interface Workspaces {
/**
* Gets the properties of the specified machine learning workspace.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Workspace>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, accountName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workspace>>;
/**
* Gets the properties of the specified machine learning workspace.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Workspace} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Workspace} [result] - The deserialized result object if an error did not occur.
* See {@link Workspace} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, accountName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workspace>;
get(resourceGroupName: string, accountName: string, workspaceName: string, callback: ServiceCallback<models.Workspace>): void;
get(resourceGroupName: string, accountName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workspace>): void;
/**
* Creates or updates a machine learning workspace with the specified
* parameters.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {object} parameters The parameters for creating or updating a machine
* learning workspace.
*
* @param {string} [parameters.description] The description of this workspace.
*
* @param {string} parameters.friendlyName The friendly name for this
* workspace. This will be the workspace name in the arm id when the workspace
* object gets created
*
* @param {string} parameters.location The location of the resource. This
* cannot be changed after the resource is created.
*
* @param {object} [parameters.tags] The tags of the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Workspace>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, accountName: string, workspaceName: string, parameters: models.Workspace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workspace>>;
/**
* Creates or updates a machine learning workspace with the specified
* parameters.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {object} parameters The parameters for creating or updating a machine
* learning workspace.
*
* @param {string} [parameters.description] The description of this workspace.
*
* @param {string} parameters.friendlyName The friendly name for this
* workspace. This will be the workspace name in the arm id when the workspace
* object gets created
*
* @param {string} parameters.location The location of the resource. This
* cannot be changed after the resource is created.
*
* @param {object} [parameters.tags] The tags of the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Workspace} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Workspace} [result] - The deserialized result object if an error did not occur.
* See {@link Workspace} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, accountName: string, workspaceName: string, parameters: models.Workspace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workspace>;
createOrUpdate(resourceGroupName: string, accountName: string, workspaceName: string, parameters: models.Workspace, callback: ServiceCallback<models.Workspace>): void;
createOrUpdate(resourceGroupName: string, accountName: string, workspaceName: string, parameters: models.Workspace, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workspace>): void;
/**
* Deletes a machine learning workspace.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, accountName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes a machine learning workspace.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, accountName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, accountName: string, workspaceName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, accountName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Updates a machine learning workspace with the specified parameters.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {object} parameters The parameters for updating a machine learning
* workspace.
*
* @param {object} [parameters.tags] The resource tags for the machine learning
* team account workspace.
*
* @param {string} [parameters.friendlyName] Friendly name of this workspace.
*
* @param {string} [parameters.description] Description for this workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Workspace>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, accountName: string, workspaceName: string, parameters: models.WorkspaceUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workspace>>;
/**
* Updates a machine learning workspace with the specified parameters.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {object} parameters The parameters for updating a machine learning
* workspace.
*
* @param {object} [parameters.tags] The resource tags for the machine learning
* team account workspace.
*
* @param {string} [parameters.friendlyName] Friendly name of this workspace.
*
* @param {string} [parameters.description] Description for this workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Workspace} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Workspace} [result] - The deserialized result object if an error did not occur.
* See {@link Workspace} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, accountName: string, workspaceName: string, parameters: models.WorkspaceUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workspace>;
update(resourceGroupName: string, accountName: string, workspaceName: string, parameters: models.WorkspaceUpdateParameters, callback: ServiceCallback<models.Workspace>): void;
update(resourceGroupName: string, accountName: string, workspaceName: string, parameters: models.WorkspaceUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workspace>): void;
/**
* Lists all the available machine learning workspaces under the specified team
* account.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WorkspaceListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByAccountsWithHttpOperationResponse(accountName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListResult>>;
/**
* Lists all the available machine learning workspaces under the specified team
* account.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {WorkspaceListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {WorkspaceListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WorkspaceListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByAccounts(accountName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListResult>;
listByAccounts(accountName: string, resourceGroupName: string, callback: ServiceCallback<models.WorkspaceListResult>): void;
listByAccounts(accountName: string, resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListResult>): void;
/**
* Lists all the available machine learning workspaces under the specified team
* account.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WorkspaceListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByAccountsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListResult>>;
/**
* Lists all the available machine learning workspaces under the specified team
* account.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {WorkspaceListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {WorkspaceListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WorkspaceListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByAccountsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListResult>;
listByAccountsNext(nextPageLink: string, callback: ServiceCallback<models.WorkspaceListResult>): void;
listByAccountsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListResult>): void;
}
/**
* @class
* Projects
* __NOTE__: An instance of this class is automatically created for an
* instance of the MLTeamAccountManagementClient.
*/
export interface Projects {
/**
* Gets the properties of the specified machine learning project.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {string} projectName The name of the machine learning project under a
* team account workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Project>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Project>>;
/**
* Gets the properties of the specified machine learning project.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {string} projectName The name of the machine learning project under a
* team account workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Project} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Project} [result] - The deserialized result object if an error did not occur.
* See {@link Project} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Project>;
get(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, callback: ServiceCallback<models.Project>): void;
get(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Project>): void;
/**
* Creates or updates a project with the specified parameters.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {string} projectName The name of the machine learning project under a
* team account workspace.
*
* @param {object} parameters The parameters for creating or updating a
* project.
*
* @param {string} [parameters.description] The description of this project.
*
* @param {string} [parameters.gitrepo] The reference to git repo for this
* project.
*
* @param {string} parameters.friendlyName The friendly name for this project.
*
* @param {string} parameters.location The location of the resource. This
* cannot be changed after the resource is created.
*
* @param {object} [parameters.tags] The tags of the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Project>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: models.Project, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Project>>;
/**
* Creates or updates a project with the specified parameters.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {string} projectName The name of the machine learning project under a
* team account workspace.
*
* @param {object} parameters The parameters for creating or updating a
* project.
*
* @param {string} [parameters.description] The description of this project.
*
* @param {string} [parameters.gitrepo] The reference to git repo for this
* project.
*
* @param {string} parameters.friendlyName The friendly name for this project.
*
* @param {string} parameters.location The location of the resource. This
* cannot be changed after the resource is created.
*
* @param {object} [parameters.tags] The tags of the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Project} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Project} [result] - The deserialized result object if an error did not occur.
* See {@link Project} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: models.Project, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Project>;
createOrUpdate(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: models.Project, callback: ServiceCallback<models.Project>): void;
createOrUpdate(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: models.Project, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Project>): void;
/**
* Deletes a project.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {string} projectName The name of the machine learning project under a
* team account workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes a project.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {string} projectName The name of the machine learning project under a
* team account workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Updates a project with the specified parameters.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {string} projectName The name of the machine learning project under a
* team account workspace.
*
* @param {object} parameters The parameters for updating a machine learning
* team account.
*
* @param {object} [parameters.tags] The resource tags for the machine learning
* project.
*
* @param {string} [parameters.friendlyName] The friendly name for this
* project.
*
* @param {string} [parameters.description] The description of this project.
*
* @param {string} [parameters.gitrepo] The reference to git repo for this
* project.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Project>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: models.ProjectUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Project>>;
/**
* Updates a project with the specified parameters.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {string} projectName The name of the machine learning project under a
* team account workspace.
*
* @param {object} parameters The parameters for updating a machine learning
* team account.
*
* @param {object} [parameters.tags] The resource tags for the machine learning
* project.
*
* @param {string} [parameters.friendlyName] The friendly name for this
* project.
*
* @param {string} [parameters.description] The description of this project.
*
* @param {string} [parameters.gitrepo] The reference to git repo for this
* project.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Project} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Project} [result] - The deserialized result object if an error did not occur.
* See {@link Project} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: models.ProjectUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Project>;
update(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: models.ProjectUpdateParameters, callback: ServiceCallback<models.Project>): void;
update(resourceGroupName: string, accountName: string, workspaceName: string, projectName: string, parameters: models.ProjectUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Project>): void;
/**
* Lists all the available machine learning projects under the specified
* workspace.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ProjectListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByWorkspaceWithHttpOperationResponse(accountName: string, workspaceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProjectListResult>>;
/**
* Lists all the available machine learning projects under the specified
* workspace.
*
* @param {string} accountName The name of the machine learning team account.
*
* @param {string} workspaceName The name of the machine learning team account
* workspace.
*
* @param {string} resourceGroupName The name of the resource group to which
* the machine learning team account belongs.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ProjectListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ProjectListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ProjectListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByWorkspace(accountName: string, workspaceName: string, resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProjectListResult>;
listByWorkspace(accountName: string, workspaceName: string, resourceGroupName: string, callback: ServiceCallback<models.ProjectListResult>): void;
listByWorkspace(accountName: string, workspaceName: string, resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProjectListResult>): void;
/**
* Lists all the available machine learning projects under the specified
* workspace.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ProjectListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByWorkspaceNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProjectListResult>>;
/**
* Lists all the available machine learning projects under the specified
* workspace.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ProjectListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ProjectListResult} [result] - The deserialized result object if an error did not occur.
* See {@link ProjectListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByWorkspaceNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProjectListResult>;
listByWorkspaceNext(nextPageLink: string, callback: ServiceCallback<models.ProjectListResult>): void;
listByWorkspaceNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProjectListResult>): void;
} | the_stack |
import {
InputNode,
InputRelation,
NodeId,
InternalUpGradeNode,
InternalUpGradeLink,
BaseDAGConfig,
} from './types';
import LinkGenerator, { Polyline } from './Link';
import {
minBy,
find,
sumBy,
reverseArray,
maxBy,
getObjectMaxMin
} from '../../Utils/utils';
import { sortNodelevel, crossing } from './utils';
const MAX_ITERATIONS = 24;
class BaseDAG<
Node extends InputNode<Relation>,
Relation extends InputRelation
> {
// 去重节点列表,包含虚拟节点
private nodes: InternalUpGradeNode<Node, Relation>[];
// 去重边列表,不带自环
private links: InternalUpGradeLink<Node, Relation>[];
// 自环边
private selfLinks: InternalUpGradeLink<Node, Relation>[];
// 虚拟节点编号
private virtualId: number = 0;
/** 配置项 */
private config: BaseDAGConfig;
// 整个 DAG 的高度与宽度
private width: number;
private height: number;
private paddingSum: number[] = [];
private levelPaddings: number[] = [];
// 节点层级初始化排序使用
private levelMap = new Map<number, number>();
// 按节点层级划分的
private nodesByLevel: InternalUpGradeNode<Node, Relation>[][] = [];
// 节点层级中 height 最大的节点
private nodesLevelMaxHeight: number[] = [];
// dfs 节点标记
private dfsVisited: NodeId[] = [];
// link 实例
private linkInstace: any;
constructor({
nodes,
links,
selfLinks,
config
}: {
nodes: InternalUpGradeNode<Node, Relation>[];
links: InternalUpGradeLink<Node, Relation>[];
selfLinks: InternalUpGradeLink<Node, Relation>[];
config: BaseDAGConfig;
}) {
this.nodes = nodes.slice().sort((nodeA, nodeB) => {
return nodeA.id > nodeB.id ? 1 : -1;
});
this.links = links.slice().sort((linkA, linkB) => {
return `${linkA.source.id}-${linkA.target.id}` >
`${linkB.source.id}-${linkB.target.id}`
? 1
: -1;
});
this.selfLinks = selfLinks.slice();
this.config = { ...config };
}
destroy() {
this.nodes = null;
this.links = null;
this.selfLinks = null;
this.nodesByLevel = null;
this.nodesLevelMaxHeight = null;
}
getOutput(left: number, top: number) {
// 加整体偏移量
this.nodes.forEach(node => {
node.finalPos = {
x: node.pos + left,
// y: this.paddingSum[node.level] + 50 * node.level + top,
// 间隔高度 + 节点层高度 + margin.top + 在层级中高度居中
y:
this.paddingSum[node.level] +
top +
this.nodesLevelMaxHeight.reduce((pre, height, index) => {
if (index < node.level)
return pre + this.nodesLevelMaxHeight[index];
return pre;
}, 0) +
(this.nodesLevelMaxHeight[node.level] - node.nodeHeight) / 2
};
});
this.links.forEach(link => {
if (link.linkChildren && link.linkChildren.length) {
link.finalPath = link.linkChildren.reduce((path, child, index) => {
if (index === 0) {
return this.linkInstace.getFinalPath(child, this.levelPaddings, false, true);
}
return path.concat(this.linkInstace.getFinalPath(child, this.levelPaddings, index === link.linkChildren.length - 1, false));
}, []);
} else {
link.finalPath = this.linkInstace.getFinalPath(link, this.levelPaddings, true, true);
}
});
this.selfLinks.forEach(link => {
link.finalPath = this.linkInstace.getSelfFinalPath(link);
});
// 逆转边还原
this.recoverCycle();
return {
nodes: this.nodes.filter(node => node.type !== 'virtual').map(node => {
// nodes: this.nodes.map(node => {
return {
id: node.id,
view: {
x: node.finalPos.x,
y: node.finalPos.y
},
nodeWidth: node.nodeWidth,
nodeHeight: node.nodeHeight,
info: node.originInfo
};
}),
links: [
...this.links
.filter(
link =>
link.source.type !== 'virtual' && link.target.type !== 'virtual'
)
.map(link => {
return {
sourceId: link.source.id,
targetId: link.target.id,
path: link.finalPath,
info: link.originInfo
};
}),
...this.selfLinks.map(link => {
return {
sourceId: link.source.id,
targetId: link.target.id,
path: link.finalPath,
info: link.originInfo
};
})
],
pos: {
width: this.width,
height: this.height
}
};
}
run() {
// 将有向有环图转为为有向无环图
this.clearCycle();
// 计算节点层级
this.calcNodeLevels();
// 计算节点位置
this.calcNodePos();
// 计算节点坐标
this.xcordinate();
// 计算线的位置,做成插件分离出来,输入所有 node 的信息
this.calcLinkPos();
// 计算真实尺寸
this.calcRealSize();
return this;
}
getSize() {
return {
width: this.width,
height: this.height
};
}
calcLinkPos() {
const { linkType, DiyLine } = this.config;
const LinkClass = LinkGenerator(linkType, DiyLine);
this.linkInstace = new LinkClass(this.nodesByLevel, this.selfLinks, this.config);
this.levelPaddings = this.linkInstace.calcPosAndPadding();
}
calcRealSize() {
let sum = 0;
// 累计 padding
this.levelPaddings.forEach((padding, index) => {
this.paddingSum[index] = sum;
sum += padding;
});
// width 和 height 为纯的宽高
this.height =
this.paddingSum[this.paddingSum.length - 1] +
sumBy(this.nodesLevelMaxHeight, height => height);
this.width =
this.nodes.reduce((max, curNode) => {
return curNode.pos + curNode.nodeWidth > max
? curNode.pos + curNode.nodeWidth
: max;
}, 0) -
this.nodes.reduce((min, curNode) => {
return curNode.pos < min ? curNode.pos : min;
}, 0);
}
addVirtualNode() {
const virtualNodes: InternalUpGradeNode<Node, Relation>[] = [];
const virtualLinks: InternalUpGradeLink<Node, Relation>[] = [];
this.links.forEach(link => {
const source = link.source;
const target = link.target;
const sourceLevel = source.level;
const targetLevel = target.level;
link.linkChildren = [];
// 跨层级的边上才需要添加虚拟节点
if (sourceLevel + 1 < targetLevel) {
for (let i = sourceLevel + 1; i < targetLevel; i++) {
const virtualNode: InternalUpGradeNode<Node, Relation> = {
id: `virtual${this.virtualId++}`,
sourceLinks: [],
targetLinks: [],
type: 'virtual',
nodeWidth: this.config.defaultVirtualNodeWidth,
nodeHeight: this.nodesLevelMaxHeight[i],
originInfo: {} as any,
level: i
};
const sourceNode =
i === sourceLevel + 1
? source
: virtualNodes[virtualNodes.length - 1];
const virtualLink: InternalUpGradeLink<Node, Relation> = {
source: sourceNode,
target: virtualNode,
originInfo: {} as any,
isReverse: link.isReverse,
};
link.linkChildren.push(virtualLink);
virtualLinks.push(virtualLink);
sourceNode.sourceLinks.push(virtualLink);
virtualNode.targetLinks.push(virtualLink);
if (i === targetLevel - 1) {
const virtualLink: InternalUpGradeLink<Node, Relation> = {
source: virtualNode,
target,
originInfo: {} as any,
isReverse: link.isReverse,
};
link.linkChildren.push(virtualLink);
virtualLinks.push(virtualLink);
virtualNode.sourceLinks.push(virtualLink);
target.targetLinks.push(virtualLink);
}
virtualNodes.push(virtualNode);
}
}
});
this.nodes = [...this.nodes, ...virtualNodes];
this.links = [...this.links, ...virtualLinks];
}
dfsOrder(node: InternalUpGradeNode<Node, Relation>) {
if (this.dfsVisited.indexOf(node.id) > -1) return;
const pos = this.levelMap.get(node.level);
node.levelPos = pos;
node._levelPos = pos;
this.levelMap.set(node.level, pos + 1);
this.dfsVisited.push(node.id);
node.sourceLinks.forEach(link => {
const { source, target } = link;
// 只处理相邻层级
if (target.level - source.level === 1) {
this.dfsOrder(target);
}
});
}
initOrder() {
// 分割进入
this.nodes.forEach(node => {
const level = node.level;
if (this.nodesByLevel[level]) {
this.nodesByLevel[level].push(node);
} else {
this.nodesByLevel[level] = [node];
this.levelMap.set(level, 0);
}
});
// 利用 dfs 来设置 order,树可以保证初始化排序没有交叉
this.dfsVisited = [];
for (let i = 0; i < this.nodesByLevel.length; i++) {
for (let j = 0; j < this.nodesByLevel[i].length; j++) {
if (this.nodesByLevel[i][j].levelPos === undefined) {
this.dfsOrder(this.nodesByLevel[i][j]);
}
}
}
}
wmedian(index: number) {
/**
* 节点中位数
* @param nodelevel
*/
function medianNodeLevel(nodelevel: InternalUpGradeNode<Node, Relation>[]) {
nodelevel.forEach(node => {
// 筛选出非跨层级上游节点,并按照 levelPos 排序
const parentNode = node.targetLinks
.filter(link => {
return link.target.level - link.source.level === 1;
})
.map(link => link.source);
parentNode.sort((node1, node2) => {
return node1.levelPos - node2.levelPos;
});
const m = Math.floor(parentNode.length / 2);
if (parentNode.length === 0) {
node._median = -1;
} else if (parentNode.length % 2 === 1) {
node._median = parentNode[m].levelPos;
} else if (parentNode.length === 2) {
node._median = (parentNode[0].levelPos + parentNode[1].levelPos) / 2;
} else {
const left = parentNode[m - 1].levelPos - parentNode[0].levelPos;
const right = parentNode[parentNode.length - 1].levelPos - parentNode[m].levelPos;
node._median = (parentNode[m - 1].levelPos * right + parentNode[m].levelPos * left) / (left + right);
}
});
}
// index 为偶,从上到下,index 为奇,从下到上
if (index % 2 === 0) {
for (let i = 0; i < this.nodesByLevel.length; i++) {
const nodelevel = this.nodesByLevel[i];
medianNodeLevel(nodelevel);
// 根据 _median 重排序
this.nodesByLevel[i] = sortNodelevel(nodelevel);
}
return;
} else {
for (let i = this.nodesByLevel.length - 1; i >= 0; i--) {
const nodelevel = this.nodesByLevel[i];
medianNodeLevel(nodelevel);
this.nodesByLevel[i] = sortNodelevel(nodelevel);
}
}
}
// 求全图交叉数量
crossing() {
let count = 0;
for (let i = 1; i < this.nodesByLevel.length; i++) {
count += crossing<Node, Relation>(
this.nodesByLevel[i - 1],
this.nodesByLevel[i]
);
}
return count;
}
// 交换相邻节点位置
transpose() {
let bestCount = this.crossing();
// 这里 i,j 的顺序与 level、_levelPos 的顺序保持一致
for (let i = 0; i < this.nodesByLevel.length; i++) {
if (this.nodesByLevel.length === 1) continue;
for (let j = 1; j < this.nodesByLevel[i].length; j++) {
// 暂时交换位置
this.nodesByLevel[i][j]._levelPos = j - 1;
this.nodesByLevel[i][j - 1]._levelPos = j;
let currentCount = this.crossing();
if (currentCount < bestCount) {
// 能减少交叉,完成交换
const tmpNode = this.nodesByLevel[i][j];
this.nodesByLevel[i][j] = this.nodesByLevel[i][j - 1];
this.nodesByLevel[i][j - 1] = tmpNode;
bestCount = currentCount;
} else {
// 没有效果,还原
this.nodesByLevel[i][j]._levelPos = j;
this.nodesByLevel[i][j - 1]._levelPos = j - 1;
}
}
}
return bestCount;
}
/**
* 确定同层级中节点的先后排列顺序,这里需要尽可能减少边交叉
* 算法来源:A Technique for Drawing Directed Graphs.pdf 第3节
* 主要思路是根据 dfs 遍历顺序获取一个初始顺序
* 然后是启发式算法:从上到下,从下到上遍历,子节点位置由父节点们来决定,同时每次遍历完成后,尝试交换相邻节点的位置,看看是否能够减少边交叉数
* 取最小边交叉数的排序,默认为最优解
*/
ordering() {
// 按层级排布,并给予初始化排序
this.initOrder();
let bestCount = this.crossing();
if (bestCount !== 0) {
for (let i = 0; i <= MAX_ITERATIONS; i++) {
this.wmedian(i);
const currentCount = this.transpose();
if (bestCount > currentCount) {
bestCount = currentCount;
// 将所有 _levelPos 赋给 levelPos,并排序
this.nodesByLevel.forEach((nodelevel, i) => {
nodelevel.forEach(node => (node.levelPos = node._levelPos));
nodelevel.sort((node1, node2) => {
return node1.levelPos - node2.levelPos;
});
});
}
}
}
// 最终以 levelPos 为准
this.nodesByLevel.forEach((nodelevel, i) => {
nodelevel.sort((node1, node2) => {
return node1.levelPos - node2.levelPos;
});
});
}
findTypeConflicts() {
const conflicts: InternalUpGradeLink<Node, Relation>[] = [];
// 层级
for (let i = 1; i < this.nodesByLevel.length; i++) {
let k0 = 0;
let scanPos = 0;
let prevLayerLength = this.nodesByLevel[i - 1].length;
// 层级中的节点
for (let j = 0; j < this.nodesByLevel[i].length; j++) {
let node = this.nodesByLevel[i][j];
// 寻找两个虚节点连成的边,寻找当前虚拟节点的相邻上游的虚拟节点,有且仅有一个
const upVirtualLink =
node.type === 'virtual' &&
node.targetLinks.filter(link => {
return (
link.target.level - link.source.level === 1 &&
link.source.type === 'virtual'
);
});
const upVirtualNode =
upVirtualLink && upVirtualLink.length
? upVirtualLink[0].source
: undefined;
let k1 = upVirtualNode ? upVirtualNode.levelPos : prevLayerLength;
// 分段方法
// 拥有上一层级虚节点,检查当前虚节点以前的
// 当前虚节点为当前层级最后一个节点,检查最后一个虚节点以后的
if (upVirtualNode || j === this.nodesByLevel[i].length - 1) {
this.nodesByLevel[i].slice(scanPos, j + 1).forEach(curNode => {
// 当前层级的上层节点
const upCurNodes = curNode.targetLinks
.filter(node => node.target.level - node.source.level === 1)
.map(link => link.source);
upCurNodes.forEach(upCurNode => {
const pos = upCurNode.levelPos;
if (
(pos < k0 || k1 < pos) &&
!(upCurNode.type === 'virtual' && curNode.type === 'virtual')
) {
conflicts.push(
find(
curNode.targetLinks,
link =>
link.source.id === upCurNode.id &&
link.target.id === curNode.id
)
);
}
});
});
scanPos = j + 1;
k0 = k1;
}
}
}
return conflicts;
}
verticalAlignment(
vert: 'u' | 'd',
typeConflicts: InternalUpGradeLink<Node, Relation>[]
) {
const root = {} as any;
const align = {} as any;
function hasConflict(
node1: InternalUpGradeNode<Node, Relation>,
node2: InternalUpGradeNode<Node, Relation>
) {
for (let i = 0; i < typeConflicts.length; i++) {
const link = typeConflicts[i];
if (
(link.source.id === node1.id && link.target.id === node2.id) ||
(link.source.id === node2.id && link.target.id === node1.id)
) {
return true;
}
}
return false;
}
// 初始化
for (let i = 0; i < this.nodesByLevel.length; i++) {
for (let j = 0; j < this.nodesByLevel[i].length; j++) {
const { id } = this.nodesByLevel[i][j];
root[id] = id;
align[id] = id;
}
}
for (let i = 0; i < this.nodesByLevel.length; i++) {
// 因为我们是从 0 计数的,所以这里要改为 -1
let r = -1;
for (let j = 0; j < this.nodesByLevel[i].length; j++) {
const nodeV = this.nodesByLevel[i][j];
// 从上到下取上游邻居,从下到上取上游邻居
let neighbors =
vert === 'u'
? nodeV.targetLinks
.filter(link => {
return Math.abs(link.target.level - link.source.level) === 1;
})
.map(link => link.source)
: nodeV.sourceLinks
.filter(link => {
return Math.abs(link.target.level - link.source.level) === 1;
})
.map(link => link.target);
if (neighbors && neighbors.length) {
neighbors.sort((node1, node2) => {
return node1.levelPos - node2.levelPos;
});
// 取邻居中位数节点,1 or 2
const mid = (neighbors.length - 1) / 2;
for (let z = Math.floor(mid); z <= Math.ceil(mid); z++) {
const nodeW = neighbors[z];
if (
align[nodeV.id] === nodeV.id &&
r < nodeW.levelPos &&
!hasConflict(nodeV, nodeW)
) {
align[nodeW.id] = nodeV.id;
align[nodeV.id] = root[nodeV.id] = root[nodeW.id];
r = nodeW.levelPos;
}
}
}
}
}
return {
root,
align
};
}
horizontalCompaction(root: any, align: any, horiz: 'l' | 'r') {
const sink = {} as any;
const shift = {} as any;
const x = {} as any;
// 计算块与块间的最大间距,为了适配不同节点宽度
const blockSpaceMap: Map<string, number> = new Map<string, number>();
this.nodesByLevel.forEach((nodeLevel, i) => {
let uNode: InternalUpGradeNode<Node, Relation>;
nodeLevel.forEach((vnode) => {
const vRootNodeId = root[vnode.id];
if (uNode) {
const uRootNodeId = root[uNode.id];
const blockSpace = blockSpaceMap.has(`${vRootNodeId}-${uRootNodeId}`) || blockSpaceMap.has(`${uRootNodeId}-${vRootNodeId}`) ?
blockSpaceMap.get(`${vRootNodeId}-${uRootNodeId}`) || blockSpaceMap.get(`${uRootNodeId}-${vRootNodeId}`) : 0;
const curSpace = vnode.nodeWidth / 2 + this.config.nodeAndNodeSpace + uNode.nodeWidth / 2;
blockSpaceMap.set(`${vRootNodeId}-${uRootNodeId}`, Math.max(blockSpace, curSpace));
blockSpaceMap.set(`${uRootNodeId}-${vRootNodeId}`, Math.max(blockSpace, curSpace));
}
uNode = vnode;
});
});
const placeBlock = (node: InternalUpGradeNode<Node, Relation>) => {
if (x[node.id] === undefined) {
x[node.id] = 0;
let w = node.id;
do {
// 非第一个
const curNode = find(this.nodes, node => node.id === w);
if (curNode.levelPos > 0) {
// 同层级左相邻节点
const preNode = this.nodesByLevel[curNode.level][
curNode.levelPos - 1
];
// 取根节点
const rootId = root[preNode.id];
placeBlock(find(this.nodes, node => node.id === rootId));
if (sink[node.id] === node.id) {
sink[node.id] = sink[rootId];
}
if (!blockSpaceMap.has(`${rootId}-${root[node.id]}`) && !blockSpaceMap.has(`${root[node.id]}-${rootId}`)) {
throw new Error(`${rootId}, ${root[node.id]}无法获取`);
}
if (sink[node.id] !== sink[rootId]) {
shift[sink[rootId]] = Math.min(
shift[sink[rootId]],
x[node.id] - x[rootId] - (blockSpaceMap.get(`${rootId}-${root[node.id]}`) || blockSpaceMap.get(`${root[node.id]}-${rootId}`))
);
} else {
x[node.id] = Math.max(
x[node.id],
x[rootId] + (blockSpaceMap.get(`${rootId}-${root[node.id]}`) || blockSpaceMap.get(`${root[node.id]}-${rootId}`))
);
}
}
w = align[w];
// 块循环结束
} while (w !== node.id);
}
};
// 初始化
for (let i = 0; i < this.nodesByLevel.length; i++) {
for (let j = 0; j < this.nodesByLevel[i].length; j++) {
const { id } = this.nodesByLevel[i][j];
sink[id] = id;
shift[id] = Number.MAX_SAFE_INTEGER;
x[id] = undefined;
}
}
// placeBlock
for (let i = 0; i < this.nodesByLevel.length; i++) {
for (let j = 0; j < this.nodesByLevel[i].length; j++) {
const { id } = this.nodesByLevel[i][j];
if (root[id] === id) {
placeBlock(this.nodesByLevel[i][j]);
}
}
}
// 整理
for (let i = 0; i < this.nodesByLevel.length; i++) {
for (let j = 0; j < this.nodesByLevel[i].length; j++) {
const { id } = this.nodesByLevel[i][j];
x[id] = x[root[id]];
if (shift[sink[root[id]]] < Number.MAX_SAFE_INTEGER) {
x[id] = x[id] + shift[sink[root[id]]];
}
}
}
return x;
}
getDirectNodesByLevel(vert: 'u' | 'd', horiz: 'l' | 'r') {
if (vert === 'u' && horiz === 'l') {
return;
}
if ((vert === 'u' && horiz === 'r') || (vert === 'd' && horiz === 'r')) {
this.nodesByLevel = this.nodesByLevel.map((nodeLevel, i) => {
return reverseArray(nodeLevel, (node, levelPos) => {
node.levelPos = levelPos;
return node;
});
});
}
if (vert === 'd' && horiz === 'l') {
this.nodesByLevel = reverseArray(
this.nodesByLevel,
(nodeLevel, level) => {
return reverseArray(nodeLevel, (node, levelPos) => {
node.level = level;
node.levelPos = levelPos;
return node;
});
}
);
}
}
resetLevel() {
this.nodesByLevel = reverseArray(this.nodesByLevel, (nodeLevel, level) => {
return reverseArray(nodeLevel, (node, levelPos) => {
node.level = level;
node.levelPos = levelPos;
return node;
});
});
}
/**
* 节点具体位置确定,算法稳定,能保证相同节点相同边的 DAG 不发生变动
* 算法来源:Fast and Simple Horizontal Coordinate Assignment
* 将节点从 左、右、上、下 四个方向进行块划分,拉开最小距离,最终取中位值,实现原理暂时不是很了解
*/
xcordinate() {
// 寻找出与(虚拟-虚拟)边交叉的(真实-真实/真实-虚拟)边
const typeConflicts = this.findTypeConflicts();
// 四个方向
const xSet = {} as any;
['u', 'd'].forEach((vert: 'u' | 'd') => {
['l', 'r'].forEach((horiz: 'l' | 'r') => {
/** 对 nodesByLevel 进行转置 */
this.getDirectNodesByLevel(vert, horiz);
// 相当于块划分
const { root, align } = this.verticalAlignment(vert, typeConflicts);
const x = this.horizontalCompaction(root, align, horiz);
// right 方向为负
if (horiz === 'r') {
for (let key in x) {
x[key] = -x[key];
}
}
xSet[vert + horiz] = x;
});
});
this.resetLevel();
const {
minSet: smallestWidth,
minDirect
} = this.findSmallestWidthAlignment(xSet);
this.alignCoordinates(xSet, smallestWidth, minDirect);
const finalPosSet = this.balance(xSet);
let minPos = Infinity;
/** 得出节点最后位置 */
this.nodes.forEach(node => {
node.pos = finalPosSet[node.id] - node.nodeWidth / 2;
if (minPos > node.pos) {
minPos = node.pos;
}
});
this.nodes.forEach(node => {
node.pos = node.pos - minPos;
});
}
/** 从四个方向的几何中寻找一个宽度最小的 */
findSmallestWidthAlignment(xSet: any) {
let minSet;
let minDirect;
let minSetValue = Number.MAX_SAFE_INTEGER;
for (let direction in xSet) {
const xs = xSet[direction];
let minValue = Number.MAX_SAFE_INTEGER;
let maxValue = Number.MIN_SAFE_INTEGER;
for (let key in xs) {
const value = xs[key];
const node = find(this.nodes, (node) => {
// 兼容业务方id为number的情况
return String(node.id) === String(key);
});
if (value + (node.nodeWidth / 2) > maxValue) maxValue = value + (node.nodeWidth / 2);
if (value - (node.nodeWidth / 2) < minValue) minValue = value - (node.nodeWidth / 2);
}
if (maxValue - minValue < minSetValue) {
minSetValue = maxValue - minValue;
minSet = xs;
minDirect = direction;
}
}
return {
minSet,
minDirect
};
}
alignCoordinates(xSet: any, smallestWidth: any, direct: string) {
let { maxValue: maxAlign, minValue: minAlign } = getObjectMaxMin(
smallestWidth
);
['u', 'd'].forEach((vert: 'u' | 'd') => {
['l', 'r'].forEach((horiz: 'l' | 'r') => {
let alignment = vert + horiz;
if (alignment !== direct) {
const xs = xSet[alignment];
const { maxValue: maxXs, minValue: minXs } = getObjectMaxMin(xs);
let delta = horiz === 'l' ? minAlign - minXs : maxAlign - maxXs;
if (delta) {
for (let key in xs) {
xs[key] = xs[key] + delta;
}
}
}
});
});
}
balance(xSet: any) {
const posListSet = {} as any;
for (let direction in xSet) {
for (let key in xSet[direction]) {
if (posListSet[key] && posListSet[key].length) {
posListSet[key].push(xSet[direction][key]);
} else {
posListSet[key] = [xSet[direction][key]];
}
}
}
const finalPosSet = {} as any;
for (let key in posListSet) {
posListSet[key].sort((a: any, b: any) => a - b);
finalPosSet[key] = (posListSet[key][1] + posListSet[key][2]) / 2;
}
return finalPosSet;
}
calcNodePos() {
// 添加跨节点边的虚拟节点
this.addVirtualNode();
// 开始迭代变换
this.ordering();
}
recoverCycle() {
this.links.forEach((link) => {
if (link.isReverse) {
this.exchangeLink(link);
if (link.linkChildren && link.linkChildren.length) {
link.linkChildren.forEach((link) => {
if (link.isReverse) {
this.exchangeLink(link);
}
});
}
}
});
}
clearCycleDfs(node: InternalUpGradeNode<Node, Relation>, stack: (string | number)[], isFirst: boolean) {
const lastNodeId = stack[stack.length - 1];
// 当前节点已被遍历,不需要再遍历
if (lastNodeId) {
if (this.dfsVisited.indexOf(`${lastNodeId}_${node.id}`) > -1) {
return;
}
this.dfsVisited.push(`${lastNodeId}_${node.id}`);
}
// 当前节点成环,对边进行逆转标记
if (stack.indexOf(node.id) > -1) {
console.warn('当前图中存在环,已被逆转处理');
const link = find(this.links, (link) => {
return link.source.id === lastNodeId && link.target.id === node.id;
});
link.isReverse = true;
}
// 保证按真实连线进行上下关系
const LinkList = isFirst ? node.sourceLinks.filter(link => !link.isCycleRelation) : node.sourceLinks;
for (let i = 0; i < LinkList.length; i++) {
this.clearCycleDfs(LinkList[i].target, [...stack, node.id], false);
}
return;
}
exchangeLink(link: InternalUpGradeLink<Node, Relation>) {
const source = link.source;
const target = link.target;
// 从 sourceLinks 中去除
source.sourceLinks = source.sourceLinks.filter(link => {
return link.source.id !== source.id || link.target.id !== target.id || !link.isReverse;
});
// 添加到 targetLinks
source.targetLinks.push(link);
// 从 targetLinks 中去除
target.targetLinks = target.targetLinks.filter(link => {
return link.source.id !== source.id || link.target.id !== target.id || !link.isReverse;
});
target.sourceLinks.push(link);
link.source = target;
link.target = source;
}
/** 利用 dfs 去除环 */
clearCycle() {
this.dfsVisited = [];
for (let i = 0; i < this.nodes.length; i++) {
this.clearCycleDfs(this.nodes[i], [], true);
}
this.links.forEach((link) => {
if (link.isReverse) {
this.exchangeLink(link);
}
});
}
/**
* 确定节点层级
* 算法来源:A Technique for Drawing Directed Graphs,2.3 节,主要采用了生成树的做法,原理难懂且实现比较复杂
* 实现算法为简要版本,来源于 jdk137/dag,主要通过获取骨干节点后,其余节点根据自己的父子节点层级来决定层级,比较简单
*/
calcNodeLevels() {
this.nodes.forEach(node => {
node.linkNumber = node.targetLinks.length + node.sourceLinks.length;
node.levelSetted = false;
});
let shrink = true;
let boneNodes = this.nodes;
// 去除度为 1 的节点的边,获取骨干节点
while (shrink) {
shrink = false;
boneNodes.forEach(node => {
if (node.linkNumber === 1) {
shrink = true;
node.linkNumber = 0;
node.sourceLinks.forEach(link => {
link.target.linkNumber--;
});
node.targetLinks.forEach(link => {
link.source.linkNumber--;
});
}
});
boneNodes = boneNodes.filter(node => {
return node.linkNumber > 0;
});
}
boneNodes.forEach(node => {
node.isBone = true;
});
let level = 0;
let confirmNodeLevelList = boneNodes;
// boneNodes > 0 说明当前DAG图成环状,如 1—>2 2->3 1->3
// 通过不断遍历节点的下游节点,确定节点层级
if (boneNodes.length > 0) {
while (confirmNodeLevelList.length) {
const nextNodes: InternalUpGradeNode<Node, Relation>[] = [];
confirmNodeLevelList.forEach(node => {
node.level = level;
node.sourceLinks.forEach(link => {
// @Fix 2018-06-27,需要进行去重处理,不然由于图层级过深,nextNodes 数组会变得很大,导致 crash
if (!find(nextNodes, (node) => {
return node.id === link.target.id;
})) {
nextNodes.push(link.target);
}
});
});
confirmNodeLevelList = nextNodes;
level++;
}
// 收集节点的上下游骨干节点
boneNodes.forEach(node => {
const parentBoneNode: InternalUpGradeNode<Node, Relation>[] = [];
const childrenBoneNode: InternalUpGradeNode<Node, Relation>[] = [];
node.targetLinks.forEach(link => {
if (link.source.isBone) {
parentBoneNode.push(link.source);
}
});
node.sourceLinks.forEach(link => {
if (link.target.isBone) {
childrenBoneNode.push(link.target);
}
});
node.parentBoneNode = parentBoneNode;
node.childrenBoneNode = childrenBoneNode;
const minChildLevel: number = (
minBy(node.childrenBoneNode, boneNode => boneNode.level) ||
({} as InternalUpGradeNode<Node, Relation>)
).level;
// 如果没有父节点,当前节点层级就是最上层子节点的上级
if (node.parentBoneNode.length === 0) {
node.level = minChildLevel - 1;
}
if (minChildLevel && minChildLevel - node.level > 1) {
// 如果当前节点与最上层子节点相差超过一个层级,就需要进行调整,如果子节点数量少于父节点数量,则当前节点应更加靠近子节点
if (node.childrenBoneNode.length < node.parentBoneNode.length) {
node.level = minChildLevel - 1;
}
// 其余情况不需要处理
}
});
} else {
// 不成环的情况,将第一个节点设为骨干节点
this.nodes[0].level = 0;
boneNodes.push(this.nodes[0]);
}
boneNodes.forEach(node => {
node.levelSetted = true;
});
// 处理未成环状的节点,根据他上下游的依赖节点的层级来判断位置
let waitSetLevelNodes = boneNodes;
while (waitSetLevelNodes.length) {
const tmpNodeList: InternalUpGradeNode<Node, Relation>[] = [];
waitSetLevelNodes.forEach(node => {
node.sourceLinks.forEach(link => {
const targetNode = link.target;
if (!targetNode.levelSetted) {
targetNode.level = node.level + 1;
node.levelSetted = true;
tmpNodeList.push(targetNode);
}
});
node.targetLinks.forEach(link => {
const sourceNode = link.source;
if (!sourceNode.levelSetted) {
sourceNode.level = node.level - 1;
node.levelSetted = true;
tmpNodeList.push(sourceNode);
}
});
});
waitSetLevelNodes = tmpNodeList;
}
// 归 0 化处理,计算层级可能为负数
const minLevel: number = minBy(this.nodes, node => node.level).level;
this.nodes.forEach(node => {
node.level -= minLevel;
});
// 算出每个层级中最大的节点高度,以匹配节点高度不同
const maxLevel: number = maxBy(this.nodes, node => node.level).level;
this.nodesLevelMaxHeight = Array(maxLevel + 1).fill(-Infinity);
this.nodes.forEach(node => {
if (this.nodesLevelMaxHeight[node.level] < node.nodeHeight) {
this.nodesLevelMaxHeight[node.level] = node.nodeHeight;
}
});
}
}
export default BaseDAG; | the_stack |
import * as THREE from "three";
import { EdgeCalculatorCoefficients } from "./EdgeCalculatorCoefficients";
import { EdgeCalculatorDirections } from "./EdgeCalculatorDirections";
import { EdgeCalculatorSettings } from "./EdgeCalculatorSettings";
import { NavigationDirection } from "./NavigationDirection";
import { NavigationEdge } from "./interfaces/NavigationEdge";
import { PotentialEdge } from "./interfaces/PotentialEdge";
import { StepDirection } from "./interfaces/StepDirection";
import { TurnDirection } from "./interfaces/TurnDirection";
import { Image } from "../Image";
import { Sequence } from "../Sequence";
import { ArgumentMapillaryError } from "../../error/ArgumentMapillaryError";
import { Spatial } from "../../geo/Spatial";
import { isSpherical } from "../../geo/Geo";
import { geodeticToEnu } from "../../geo/GeoCoords";
/**
* @class EdgeCalculator
*
* @classdesc Represents a class for calculating node edges.
*/
export class EdgeCalculator {
private _spatial: Spatial;
private _settings: EdgeCalculatorSettings;
private _directions: EdgeCalculatorDirections;
private _coefficients: EdgeCalculatorCoefficients;
/**
* Create a new edge calculator instance.
*
* @param {EdgeCalculatorSettings} settings - Settings struct.
* @param {EdgeCalculatorDirections} directions - Directions struct.
* @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
*/
constructor(
settings?: EdgeCalculatorSettings,
directions?: EdgeCalculatorDirections,
coefficients?: EdgeCalculatorCoefficients) {
this._spatial = new Spatial();
this._settings = settings != null ? settings : new EdgeCalculatorSettings();
this._directions = directions != null ? directions : new EdgeCalculatorDirections();
this._coefficients = coefficients != null ? coefficients : new EdgeCalculatorCoefficients();
}
/**
* Returns the potential edges to destination nodes for a set
* of nodes with respect to a source node.
*
* @param {Image} node - Source node.
* @param {Array<Image>} nodes - Potential destination nodes.
* @param {Array<string>} fallbackIds - Ids for destination nodes
* that should be returned even if they do not meet the
* criteria for a potential edge.
* @throws {ArgumentMapillaryError} If node is not full.
*/
public getPotentialEdges(node: Image, potentialImages: Image[], fallbackIds: string[]): PotentialEdge[] {
if (!node.complete) {
throw new ArgumentMapillaryError("Image has to be full.");
}
if (!node.merged) {
return [];
}
let currentDirection: THREE.Vector3 =
this._spatial.viewingDirection(node.rotation);
let currentVerticalDirection: number =
this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
let potentialEdges: PotentialEdge[] = [];
for (let potential of potentialImages) {
if (!potential.merged ||
potential.id === node.id) {
continue;
}
let enu = geodeticToEnu(
potential.lngLat.lng,
potential.lngLat.lat,
potential.computedAltitude,
node.lngLat.lng,
node.lngLat.lat,
node.computedAltitude);
let motion: THREE.Vector3 = new THREE.Vector3(enu[0], enu[1], enu[2]);
let distance: number = motion.length();
if (distance > this._settings.maxDistance &&
fallbackIds.indexOf(potential.id) < 0) {
continue;
}
let motionChange: number = this._spatial.angleBetweenVector2(
currentDirection.x,
currentDirection.y,
motion.x,
motion.y);
let verticalMotion: number = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
let direction: THREE.Vector3 =
this._spatial.viewingDirection(potential.rotation);
let directionChange: number = this._spatial.angleBetweenVector2(
currentDirection.x,
currentDirection.y,
direction.x,
direction.y);
let verticalDirection: number = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
let verticalDirectionChange: number = verticalDirection - currentVerticalDirection;
let rotation: number = this._spatial.relativeRotationAngle(
node.rotation,
potential.rotation);
let worldMotionAzimuth: number =
this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
let sameSequence: boolean = potential.sequenceId != null &&
node.sequenceId != null &&
potential.sequenceId === node.sequenceId;
let sameMergeCC: boolean =
potential.mergeId === node.mergeId;
let sameUser: boolean =
potential.creatorId === node.creatorId;
let potentialEdge: PotentialEdge = {
capturedAt: potential.capturedAt,
directionChange: directionChange,
distance: distance,
spherical: isSpherical(potential.cameraType),
id: potential.id,
motionChange: motionChange,
rotation: rotation,
sameMergeCC: sameMergeCC,
sameSequence: sameSequence,
sameUser: sameUser,
sequenceId: potential.sequenceId,
verticalDirectionChange: verticalDirectionChange,
verticalMotion: verticalMotion,
worldMotionAzimuth: worldMotionAzimuth,
};
potentialEdges.push(potentialEdge);
}
return potentialEdges;
}
/**
* Computes the sequence edges for a node.
*
* @param {Image} node - Source node.
* @throws {ArgumentMapillaryError} If node is not full.
*/
public computeSequenceEdges(node: Image, sequence: Sequence): NavigationEdge[] {
if (!node.complete) {
throw new ArgumentMapillaryError("Image has to be full.");
}
if (node.sequenceId !== sequence.id) {
throw new ArgumentMapillaryError("Image and sequence does not correspond.");
}
let edges: NavigationEdge[] = [];
let nextId: string = sequence.findNext(node.id);
if (nextId != null) {
edges.push({
data: {
direction: NavigationDirection.Next,
worldMotionAzimuth: Number.NaN,
},
source: node.id,
target: nextId,
});
}
let prevId: string = sequence.findPrev(node.id);
if (prevId != null) {
edges.push({
data: {
direction: NavigationDirection.Prev,
worldMotionAzimuth: Number.NaN,
},
source: node.id,
target: prevId,
});
}
return edges;
}
/**
* Computes the similar edges for a node.
*
* @description Similar edges for perspective images
* look roughly in the same direction and are positioned closed to the node.
* Similar edges for spherical only target other spherical.
*
* @param {Image} node - Source node.
* @param {Array<PotentialEdge>} potentialEdges - Potential edges.
* @throws {ArgumentMapillaryError} If node is not full.
*/
public computeSimilarEdges(node: Image, potentialEdges: PotentialEdge[]): NavigationEdge[] {
if (!node.complete) {
throw new ArgumentMapillaryError("Image has to be full.");
}
let nodeSpherical: boolean = isSpherical(node.cameraType);
let sequenceGroups: { [key: string]: PotentialEdge[] } = {};
for (let potentialEdge of potentialEdges) {
if (potentialEdge.sequenceId == null) {
continue;
}
if (potentialEdge.sameSequence) {
continue;
}
if (nodeSpherical) {
if (!potentialEdge.spherical) {
continue;
}
} else {
if (!potentialEdge.spherical &&
Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
continue;
}
}
if (potentialEdge.distance > this._settings.similarMaxDistance) {
continue;
}
if (potentialEdge.sameUser &&
Math.abs(potentialEdge.capturedAt - node.capturedAt) <
this._settings.similarMinTimeDifference) {
continue;
}
if (sequenceGroups[potentialEdge.sequenceId] == null) {
sequenceGroups[potentialEdge.sequenceId] = [];
}
sequenceGroups[potentialEdge.sequenceId].push(potentialEdge);
}
let similarEdges: PotentialEdge[] = [];
let calculateScore =
isSpherical(node.cameraType) ?
(potentialEdge: PotentialEdge): number => {
return potentialEdge.distance;
} :
(potentialEdge: PotentialEdge): number => {
return this._coefficients.similarDistance * potentialEdge.distance +
this._coefficients.similarRotation * potentialEdge.rotation;
};
for (let sequenceId in sequenceGroups) {
if (!sequenceGroups.hasOwnProperty(sequenceId)) {
continue;
}
let lowestScore: number = Number.MAX_VALUE;
let similarEdge: PotentialEdge = null;
for (let potentialEdge of sequenceGroups[sequenceId]) {
let score: number = calculateScore(potentialEdge);
if (score < lowestScore) {
lowestScore = score;
similarEdge = potentialEdge;
}
}
if (similarEdge == null) {
continue;
}
similarEdges.push(similarEdge);
}
return similarEdges
.map<NavigationEdge>(
(potentialEdge: PotentialEdge): NavigationEdge => {
return {
data: {
direction: NavigationDirection.Similar,
worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
},
source: node.id,
target: potentialEdge.id,
};
});
}
/**
* Computes the step edges for a perspective node.
*
* @description Step edge targets can only be other perspective nodes.
* Returns an empty array for spherical.
*
* @param {Image} node - Source node.
* @param {Array<PotentialEdge>} potentialEdges - Potential edges.
* @param {string} prevId - Id of previous node in sequence.
* @param {string} nextId - Id of next node in sequence.
* @throws {ArgumentMapillaryError} If node is not full.
*/
public computeStepEdges(
node: Image,
potentialEdges: PotentialEdge[],
prevId: string,
nextId: string): NavigationEdge[] {
if (!node.complete) {
throw new ArgumentMapillaryError("Image has to be full.");
}
let edges: NavigationEdge[] = [];
if (isSpherical(node.cameraType)) {
return edges;
}
for (let k in this._directions.steps) {
if (!this._directions.steps.hasOwnProperty(k)) {
continue;
}
let step: StepDirection = this._directions.steps[k];
let lowestScore: number = Number.MAX_VALUE;
let edge: PotentialEdge = null;
let fallback: PotentialEdge = null;
for (let potential of potentialEdges) {
if (potential.spherical) {
continue;
}
if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
continue;
}
let motionDifference: number =
this._spatial.angleDifference(step.motionChange, potential.motionChange);
let directionMotionDifference: number =
this._spatial.angleDifference(potential.directionChange, motionDifference);
let drift: number =
Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
if (Math.abs(drift) > this._settings.stepMaxDrift) {
continue;
}
let potentialId: string = potential.id;
if (step.useFallback && (potentialId === prevId || potentialId === nextId)) {
fallback = potential;
}
if (potential.distance > this._settings.stepMaxDistance) {
continue;
}
motionDifference = Math.sqrt(
motionDifference * motionDifference +
potential.verticalMotion * potential.verticalMotion);
let score: number =
this._coefficients.stepPreferredDistance *
Math.abs(potential.distance - this._settings.stepPreferredDistance) /
this._settings.stepMaxDistance +
this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
if (score < lowestScore) {
lowestScore = score;
edge = potential;
}
}
edge = edge == null ? fallback : edge;
if (edge != null) {
edges.push({
data: {
direction: step.direction,
worldMotionAzimuth: edge.worldMotionAzimuth,
},
source: node.id,
target: edge.id,
});
}
}
return edges;
}
/**
* Computes the turn edges for a perspective node.
*
* @description Turn edge targets can only be other perspective images.
* Returns an empty array for spherical.
*
* @param {Image} node - Source node.
* @param {Array<PotentialEdge>} potentialEdges - Potential edges.
* @throws {ArgumentMapillaryError} If node is not full.
*/
public computeTurnEdges(node: Image, potentialEdges: PotentialEdge[]): NavigationEdge[] {
if (!node.complete) {
throw new ArgumentMapillaryError("Image has to be full.");
}
let edges: NavigationEdge[] = [];
if (isSpherical(node.cameraType)) {
return edges;
}
for (let k in this._directions.turns) {
if (!this._directions.turns.hasOwnProperty(k)) {
continue;
}
let turn: TurnDirection = this._directions.turns[k];
let lowestScore: number = Number.MAX_VALUE;
let edge: PotentialEdge = null;
for (let potential of potentialEdges) {
if (potential.spherical) {
continue;
}
if (potential.distance > this._settings.turnMaxDistance) {
continue;
}
let rig: boolean =
turn.direction !== NavigationDirection.TurnU &&
potential.distance < this._settings.turnMaxRigDistance &&
Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
let directionDifference: number = this._spatial.angleDifference(
turn.directionChange, potential.directionChange);
let score: number;
if (
rig &&
potential.directionChange * turn.directionChange > 0 &&
Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
score = -Math.PI / 2 + Math.abs(potential.directionChange);
} else {
if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
continue;
}
let motionDifference: number = turn.motionChange ?
this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
motionDifference = Math.sqrt(
motionDifference * motionDifference +
potential.verticalMotion * potential.verticalMotion);
score =
this._coefficients.turnDistance * potential.distance /
this._settings.turnMaxDistance +
this._coefficients.turnMotion * motionDifference / Math.PI +
this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
}
if (score < lowestScore) {
lowestScore = score;
edge = potential;
}
}
if (edge != null) {
edges.push({
data: {
direction: turn.direction,
worldMotionAzimuth: edge.worldMotionAzimuth,
},
source: node.id,
target: edge.id,
});
}
}
return edges;
}
/**
* Computes the spherical edges for a perspective node.
*
* @description Perspective to spherical edge targets can only be
* spherical nodes. Returns an empty array for spherical.
*
* @param {Image} node - Source node.
* @param {Array<PotentialEdge>} potentialEdges - Potential edges.
* @throws {ArgumentMapillaryError} If node is not full.
*/
public computePerspectiveToSphericalEdges(node: Image, potentialEdges: PotentialEdge[]): NavigationEdge[] {
if (!node.complete) {
throw new ArgumentMapillaryError("Image has to be full.");
}
if (isSpherical(node.cameraType)) {
return [];
}
let lowestScore: number = Number.MAX_VALUE;
let edge: PotentialEdge = null;
for (let potential of potentialEdges) {
if (!potential.spherical) {
continue;
}
let score: number =
this._coefficients.sphericalPreferredDistance *
Math.abs(potential.distance - this._settings.sphericalPreferredDistance) /
this._settings.sphericalMaxDistance +
this._coefficients.sphericalMotion * Math.abs(potential.motionChange) / Math.PI +
this._coefficients.sphericalMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
if (score < lowestScore) {
lowestScore = score;
edge = potential;
}
}
if (edge == null) {
return [];
}
return [
{
data: {
direction: NavigationDirection.Spherical,
worldMotionAzimuth: edge.worldMotionAzimuth,
},
source: node.id,
target: edge.id,
},
];
}
/**
* Computes the spherical and step edges for a spherical node.
*
* @description Spherical to spherical edge targets can only be
* spherical nodes. spherical to step edge targets can only be perspective
* nodes.
*
* @param {Image} node - Source node.
* @param {Array<PotentialEdge>} potentialEdges - Potential edges.
* @throws {ArgumentMapillaryError} If node is not full.
*/
public computeSphericalEdges(node: Image, potentialEdges: PotentialEdge[]): NavigationEdge[] {
if (!node.complete) {
throw new ArgumentMapillaryError("Image has to be full.");
}
if (!isSpherical(node.cameraType)) {
return [];
}
let sphericalEdges: NavigationEdge[] = [];
let potentialSpherical: PotentialEdge[] = [];
let potentialSteps: [NavigationDirection, PotentialEdge][] = [];
for (let potential of potentialEdges) {
if (potential.distance > this._settings.sphericalMaxDistance) {
continue;
}
if (potential.spherical) {
if (potential.distance < this._settings.sphericalMinDistance) {
continue;
}
potentialSpherical.push(potential);
} else {
for (let k in this._directions.spherical) {
if (!this._directions.spherical.hasOwnProperty(k)) {
continue;
}
let spherical = this._directions.spherical[k];
let turn: number = this._spatial.angleDifference(
potential.directionChange,
potential.motionChange);
let turnChange: number = this._spatial.angleDifference(spherical.directionChange, turn);
if (Math.abs(turnChange) > this._settings.sphericalMaxStepTurnChange) {
continue;
}
potentialSteps.push([spherical.direction, potential]);
// break if step direction found
break;
}
}
}
let maxRotationDifference: number = Math.PI / this._settings.sphericalMaxItems;
let occupiedAngles: number[] = [];
let stepAngles: number[] = [];
for (let index: number = 0; index < this._settings.sphericalMaxItems; index++) {
let rotation: number = index / this._settings.sphericalMaxItems * 2 * Math.PI;
let lowestScore: number = Number.MAX_VALUE;
let edge: PotentialEdge = null;
for (let potential of potentialSpherical) {
let motionDifference: number = this._spatial.angleDifference(rotation, potential.motionChange);
if (Math.abs(motionDifference) > maxRotationDifference) {
continue;
}
let occupiedDifference: number = Number.MAX_VALUE;
for (let occupiedAngle of occupiedAngles) {
let difference: number = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
if (difference < occupiedDifference) {
occupiedDifference = difference;
}
}
if (occupiedDifference <= maxRotationDifference) {
continue;
}
let score: number =
this._coefficients.sphericalPreferredDistance *
Math.abs(potential.distance - this._settings.sphericalPreferredDistance) /
this._settings.sphericalMaxDistance +
this._coefficients.sphericalMotion * Math.abs(motionDifference) / maxRotationDifference +
this._coefficients.sphericalSequencePenalty * (potential.sameSequence ? 0 : 1) +
this._coefficients.sphericalMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
if (score < lowestScore) {
lowestScore = score;
edge = potential;
}
}
if (edge != null) {
occupiedAngles.push(edge.motionChange);
sphericalEdges.push({
data: {
direction: NavigationDirection.Spherical,
worldMotionAzimuth: edge.worldMotionAzimuth,
},
source: node.id,
target: edge.id,
});
} else {
stepAngles.push(rotation);
}
}
let occupiedStepAngles: { [direction: string]: number[] } = {};
occupiedStepAngles[NavigationDirection.Spherical] = occupiedAngles;
occupiedStepAngles[NavigationDirection.StepForward] = [];
occupiedStepAngles[NavigationDirection.StepLeft] = [];
occupiedStepAngles[NavigationDirection.StepBackward] = [];
occupiedStepAngles[NavigationDirection.StepRight] = [];
for (let stepAngle of stepAngles) {
let occupations: [NavigationDirection, PotentialEdge][] = [];
for (let k in this._directions.spherical) {
if (!this._directions.spherical.hasOwnProperty(k)) {
continue;
}
let spherical = this._directions.spherical[k];
let allOccupiedAngles: number[] = occupiedStepAngles[NavigationDirection.Spherical]
.concat(occupiedStepAngles[spherical.direction])
.concat(occupiedStepAngles[spherical.prev])
.concat(occupiedStepAngles[spherical.next]);
let lowestScore: number = Number.MAX_VALUE;
let edge: [NavigationDirection, PotentialEdge] = null;
for (let potential of potentialSteps) {
if (potential[0] !== spherical.direction) {
continue;
}
let motionChange: number = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
if (Math.abs(motionChange) > maxRotationDifference) {
continue;
}
let minOccupiedDifference: number = Number.MAX_VALUE;
for (let occupiedAngle of allOccupiedAngles) {
let occupiedDifference: number =
Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
if (occupiedDifference < minOccupiedDifference) {
minOccupiedDifference = occupiedDifference;
}
}
if (minOccupiedDifference <= maxRotationDifference) {
continue;
}
let score: number = this._coefficients.sphericalPreferredDistance *
Math.abs(potential[1].distance - this._settings.sphericalPreferredDistance) /
this._settings.sphericalMaxDistance +
this._coefficients.sphericalMotion * Math.abs(motionChange) / maxRotationDifference +
this._coefficients.sphericalMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
if (score < lowestScore) {
lowestScore = score;
edge = potential;
}
}
if (edge != null) {
occupations.push(edge);
sphericalEdges.push({
data: {
direction: edge[0],
worldMotionAzimuth: edge[1].worldMotionAzimuth,
},
source: node.id,
target: edge[1].id,
});
}
}
for (let occupation of occupations) {
occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
}
}
return sphericalEdges;
}
} | the_stack |
import { Linter, Rule } from 'template-lint';
import { BindingRule } from '../source/rules/binding';
import { Reflection } from '../source/reflection';
import { AureliaReflection } from '../source/aurelia-reflection';
import { ASTNode } from '../source/ast';
describe("Static-Type Binding Tests", () => {
describe("repeat.for bindings", () => {
it("will fail bad repeat.for syntax", (done) => {
var linter: Linter = new Linter([
new BindingRule(new Reflection(), new AureliaReflection())
]);
linter.lint('<div repeat.for="item of"></div>')
.then((issues) => {
expect(issues.length).toBe(1);
expect(issues[0].message).toContain('Incorrect syntax for "for"');
done();
});
});
it("will reject bad interpolation binding after repeat.for attribute", (done) => {
let viewmodel = `
export class Foo {
existing = true;
items = [];
}`;
let view = `
<template>
\${existing}
\${missing1}
<a repeat.for="item of items">
\${missing2}
\${item}
</a>
\${missing3}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(3);
expect(issues[0].message).toBe("cannot find 'missing1' in type 'Foo'");
expect(issues[1].message).toBe("cannot find 'missing2' in type 'Foo'");
expect(issues[2].message).toBe("cannot find 'missing3' in type 'Foo'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
it("accepts good repeat.for attribute value", (done) => {
let item = `
export class Item{
info:string;
}`;
let viewmodel = `
import {Item} from './path/item
export class Foo{
items:Item[]
}`;
let view = `
<template repeat.for="item of items">
\${item}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./path/item.ts", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(0);
}
catch (error) { expect(error).toBeUndefined(); }
finally { done(); }
});
});
it("accepts good repeat.for attribute valid of imported interface", (done) => {
let item = `
export interface Item{
info:string;
}`;
let viewmodel = `
import {Item} from './path/item
export class Foo{
items:Item[]
}`;
let view = `
<template repeat.for="item of items">
\${item}
\${item.info}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./path/item.ts", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(0);
}
catch (error) { expect(error).toBeUndefined(); }
finally { done(); }
});
});
it("supports repeat.for when iterating an unknown", (done) => {
let viewmodel = `
import {Router} from 'not-defined'
export class Foo{
@bindable router: Router;
}`;
let view = `
<template>
<li repeat.for="row of router.navigation">
<a href.bind="row.href">\${row.title}</a>
</li>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(0);
}
catch (error) {
fail(error);
}
finally {
done();
}
});
});
});
it("will fail bad interpolation syntax in text node", (done) => {
var linter: Linter = new Linter([
new BindingRule(new Reflection(), new AureliaReflection())
]);
linter.lint('<div>${..}</div>')
.then((issues) => {
expect(issues.length).toBe(1);
expect(issues[0].message).toContain('Parser Error');
done();
});
});
it("accepts good interpolation binding", (done) => {
let viewmodel = `
export class Foo{
name:string
}`;
let view = `
<template>
\${name}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(0);
}
catch (error) { expect(error).toBeUndefined(); }
finally { done(); }
});
});
it("accepts good interpolation within attribute value", (done) => {
let viewmodel = `
export class Foo{
width:number;
height:number;
}`;
let view = `
<template>
<div css="width: \${width}px; height: \${height}px;"></div>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(0);
done();
});
});
it("rejects bad interpolation within attribute value", (done) => {
let viewmodel = `
export class Foo{
width:number;
height:number;
}`;
let view = `
<template>
<div css="width: \${widt}px; height: \${hight}px;"></div>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(2);
expect(issues[0].message).toBe("cannot find 'widt' in type 'Foo'");
expect(issues[1].message).toBe("cannot find 'hight' in type 'Foo'");
done();
});
});
it("rejects bad interpolation binding", (done) => {
let viewmodel = `
export class Foo{
name:string
}`;
let view = `
<template>
\${nam}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'nam' in type 'Foo'");
}
catch (error) { expect(error).toBeUndefined(); }
finally { done(); }
});
});
it("accepts good if.bind", (done) => {
let viewmodel = `
export class Foo{
condition:boolean
}`;
let view = `
<template>
<div if.bind="condition"></div>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(0);
done();
});
});
it("accepts good negated if.bind", (done) => {
let viewmodel = `
export class Foo{
condition:boolean
}`;
let view = `
<template>
<div if.bind="!condition"></div>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(0);
done();
});
});
it("accepts good attribute binding", (done) => {
let viewmodel = `
export class Foo{
name:string
}`;
let view = `
<template>
<input type="text" value.bind="name">
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(0);
}
catch (error) { expect(error).toBeUndefined(); }
finally { done(); }
});
});
it("accepts good attribute binding to imported type", (done) => {
let item = `
export class Item{
info:string;
}`;
let viewmodel = `
import {Item} from './path/item
export class Foo{
item:Item
}`;
let view = `
<template>
\${item.info}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./path/item.ts", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(0);
}
catch (error) { expect(error).toBeUndefined(); }
finally { done(); }
});
});
it("rejects bad attribute binding to imported type", (done) => {
let item = `
export class Item{
info:string;
}`;
let viewmodel = `
import {Item} from './path/item
export class Foo{
item:Item
}`;
let view = `
<template>
\${item.infooo}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./path/item.ts", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'infooo' in type 'Item'");
}
catch (error) { expect(error).toBeUndefined(); }
finally { done(); }
});
});
it("accepts good with.bind attribute value", (done) => {
let item = `
export class Item{
info:string;
}`;
let viewmodel = `
import {Item} from './path/item
export class Foo{
item:Item
}`;
let view = `
<template with.bind="item"></template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./path/item.ts", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(0);
}
catch (error) { expect(error).toBeUndefined(); }
finally { done(); }
});
});
it("rejects bad with.bind attribute value", (done) => {
let item = `
export class Item{
info:string;
}`;
let viewmodel = `
import {Item} from './path/item
export class Foo{
item:Item
}`;
let view = `
<template with.bind="itm"></template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./path/item.ts", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'itm' in type 'Foo'");
}
catch (error) { expect(error).toBeUndefined(); }
finally { done(); }
});
});
it("rejects bad with.bind attribute value", (done) => {
let item = `
export class Item{
info:string;
}`;
let viewmodel = `
import {Item} from './path/item
export class Foo{
items:Item[]
}`;
let view = `
<template repeat.for="item of itms"></template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./path/item.ts", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'itms' in type 'Foo'");
}
catch (error) { expect(error).toBeUndefined(); }
finally { done(); }
});
});
it("correctly find view-model regardless of class name", (done) => {
let viewmodel = `
export class ChooChoo{
name:string
}`;
let view = `
<template>
<input type="text" value.bind="name">
\${nam}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo-camel.ts", viewmodel);
linter.lint(view, "./foo-camel.html")
.then((issues) => {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'nam' in type 'ChooChoo'");
done();
});
});
it("supports chain traversal via method return type", (done) => {
let role = `
export class Role{
isAdmin:boolean;
}
`;
let person = `
import {Role} from './role';
export class Person{
getRole():Role{}
}`;
let viewmodel = `
import {Person} from './nested/person';
export class Foo{
getPerson():Person{}
}`;
let view = `
<template>
\${getPerson().getRole().isAdmin}
\${getPerson().getRole().isAdmi}
\${getPerson().rol}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./nested/person.ts", person);
reflection.add("./nested/role.ts", role);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(2);
try {
expect(issues[0].message).toBe("cannot find 'isAdmi' in type 'Role'");
expect(issues[1].message).toBe("cannot find 'rol' in type 'Person'");
} finally { done(); }
});
});
it("supports $parent access scope", (done) => {
let role = `
export class Role{
isAdmin:boolean;
}
`;
let person = `
import {Role} from './role';
export class Person{
role:Role;
}`;
let viewmodel = `
import {Person} from './person';
export class Foo{
person:Person;
}`;
let view = `
<template with.bind="person">
<template with.bind="role">
\${$parent.$parent.person.role.isAdmn}
\${$parent.$parent.person.role.isAdmin}
\${$parent.role.isAdmin}
</template>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./person.ts", person);
reflection.add("./role.ts", role);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'isAdmn' in type 'Role'");
done();
});
});
it("will accept use of local created in same element", (done) => {
let person = `
export class Person{
id:number;
fullName:string;
}`;
let viewmodel = `
import {Person} from './person';
export class Foo{
employees:Person[];
}`;
let view = `
<template>
<option repeat.for="employee of employees" model.bind = "employee.id" >
\${employee.fullName }
</option>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./person.ts", person);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(0);
done();
});
});
it("will accept use of local created in same element, before it is created", (done) => {
let person = `
export class Person{
id:number;
fullName:string;
}`;
let viewmodel = `
import {Person} from './person';
export class Foo{
employees:Person[];
}`;
let view = `
<template>
<option model.bind = "employee.id" repeat.for="employee of employees" >
\${employee.fullName }
</option>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./person.ts", person);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(0);
done();
});
});
it("will reject access of private member", (done) => {
let viewmodel = `
export class Foo{
private name:string;
}`;
let view = `
<template>
<input type="text" value.bind="name">
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("field 'name' in type 'Foo' has private access modifier");
done();
});
});
it("will reject access of protected member (with default settings)", (done) => {
let viewmodel = `
export class Foo{
protected name:string;
}`;
let view = `
<template>
<input type="text" value.bind="name">
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("field 'name' in type 'Foo' has protected access modifier");
done();
});
});
it("will not reject access of protected member if only private access modifier is restricted", (done) => {
let viewmodel = `
export class Foo{
private privateMember:string;
protected protectedMember:string;
}`;
let view = `
<template>
<input type="text" value.bind="privateMember">
<input type="text" value.bind="protectedMember">
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection(), { restrictedAccess: ["private"] });
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("field 'privateMember' in type 'Foo' has private access modifier");
done();
});
});
it("supports custom typings", (done) => {
let lib = `
declare module 'my-lib' {
export interface Person{
name:string;
}
}`;
let viewmodel = `
import {Person} from 'my-lib';
export class Foo{
person:Person;
}`;
let view = `
<template>
\${person.name}
\${person.nme}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./path/foo.ts", viewmodel);
reflection.addTypings(lib);
linter.lint(view, "./path/foo.html")
.then((issues) => {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'nme' in type 'Person'");
done();
});
});
it("supports importing module", (done) => {
let lib = `
declare module 'module-name' {
// dummy module that in reality should have some exports imported bellow
}`;
let viewmodel = `
import defaultMember from "module-name";
import * as name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import defaultMember2, * as name2 from "module-name";
import "module-name";
export class Foo{
existing:string;
}`;
let view = `
<template>
\${existing}
\${missing}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection(), { reportExceptions: true });
let linter = new Linter([rule]);
reflection.add("./path/foo.ts", viewmodel);
reflection.addTypings(lib);
linter.lint(view, "./path/foo.html")
.then((issues) => {
expect(issues.length).toBe(1);
const issue1 = issues[0];
expect(issue1.message).toContain("cannot find 'missing' in type 'Foo'");
done();
});
});
// #112
it("supports importing from file that re-exports all", (done) => {
let item = `
export class Item{
prop: string;
}`;
let common = `
export * from './item';
`;
let viewmodel = `
import {Item} from './common';
export class Foo{
items: Item[]
}`;
let view = `
<template>
<div repeat.for="item of items">
\${item.prop}
\${item.pro}
</div>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection(), { reportExceptions: true });
let linter = new Linter([rule]);
reflection.add("./path/item.ts", item);
reflection.add("./path/common.ts", common);
reflection.add("./path/foo.ts", viewmodel);
linter.lint(view, "./path/foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'pro' in type 'Item'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
// #112
it("supports importing from file that exports specific item", (done) => {
let item = `
export class Item{
prop: string;
}`;
let common = `
export { Item } from './item';
`;
let viewmodel = `
import {Item} from './common';
export class Foo{
items: Item[]
}`;
let view = `
<template>
<div repeat.for="item of items">
\${item.prop}
\${item.pro}
</div>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection(), { reportExceptions: true });
let linter = new Linter([rule]);
reflection.add("./path/item.ts", item);
reflection.add("./path/common.ts", common);
reflection.add("./path/foo.ts", viewmodel);
linter.lint(view, "./path/foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'pro' in type 'Item'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
it("supports bindable field", (done) => {
let item = `
export class Item{
name:string;
}`;
let viewmodel = `
import {bindable} from "aurelia-framework";
import {Item} from './item'
export class ItemCustomElement {
@bindable value: Item;
}`;
let view = `
<template>
\${value}
\${valu}
\${value.name}
\${value.nae}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./item.ts", item);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(2);
expect(issues[0].message).toBe("cannot find 'valu' in type 'ItemCustomElement'");
expect(issues[1].message).toBe("cannot find 'nae' in type 'Item'");
done();
});
});
it("supports public property from constructor argument", (done) => {
let viewmodel = `
export class ConstructorFieldCustomElement {
constructor(public constructorPublicField:string, justAConstructorArgument: string, private constructorPrivateField: string){}
}`;
let view = `
<template>
\${constructorPublicField}
\${justAConstructorArgument}
\${constructorPrivateField}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(2);
expect(issues[0].message).toBe("cannot find 'justAConstructorArgument' in type 'ConstructorFieldCustomElement'");
expect(issues[1].message).toBe("field 'constructorPrivateField' in type 'ConstructorFieldCustomElement' has private access modifier");
done();
});
});
it("supports keyed-access (expression)", (done) => {
let item = `
export class Item{
info:string;
}`;
let viewmodel = `
import {Item} from './path/item
export class Foo{
items:Item[]
index:number;
}`;
let view = `
<template>
\${items[index].info}
\${items[indx].inf}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./path/item.ts", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(2);
expect(issues[0].message).toBe("cannot find 'indx' in type 'Foo'");
expect(issues[1].message).toBe("cannot find 'inf' in type 'Item'");
} finally { done(); }
});
});
// #90
it("supports dynamic properties from index signature", (done) => {
let viewmodel = `
export class Foo{
i: I;
c: C;
}
export interface I {
existing: string;
[x: string]: any; // dynamic properties can be used with index signature
}
export class C {
existing: string;
[x: string]: any; // dynamic properties can be used with index signature
}
`;
let view = `
<template>
\${i.existing}
\${i.dynamic1}
\${i.dynamic2}
\${c.existing}
\${c.dynamic3}
\${c.dynamic4}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection(), { reportExceptions: true });
let linter = new Linter([rule]);
reflection.add("./path/foo.ts", viewmodel);
linter.lint(view, "./path/foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(0);
}
catch (err) { fail(err); }
finally { done(); }
});
});
//#59
it("supports getters", (done) => {
let item = `
export class Item{
value:string;
}`;
let viewmodel = `
import {Item} from './path/item
export class Foo{
get item(): Item {}
}`;
let view = `
<template>
\${item}
\${item.value}
\${item.vale}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./path/item", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'vale' in type 'Item'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
it("support javascript (untyped) source", (done) => {
let viewmodel = `
export class Foo{
items;
index;
}`;
let view = `
<template>
\${items};
\${index};
\${item};
\${indx};
\${items[index]}
\${items[index].info}
\${index.will.never.know.how.wrong.this.is}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.js", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(2);
expect(issues[0].message).toBe("cannot find 'item' in type 'Foo'");
expect(issues[1].message).toBe("cannot find 'indx' in type 'Foo'");
} finally { done(); }
});
});
//#58
it("supports access to typed Array-object members", (done) => {
let item = `
export interface Item{
value:string;
}`;
let viewmodel = `
import {Item} from './item
export class Foo{
items: Item[];
}`;
let view = `
<template>
\${items.length}
\${items.lengh}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./item", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'lengh' in object 'Array'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
//#111
it("supports access to generic Array type members", (done) => {
let item = `
export interface Item{
value:string;
}`;
let viewmodel = `
import {Item} from './item
export class Foo{
items: Array<Item>;
}`;
let view = `
<template>
\${items.length}
\${items.lengh}
\${items[0].value}
\${items[0].vale}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./item", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(2);
expect(issues[0].message).toBe("cannot find 'lengh' in object 'Array'");
expect(issues[1].message).toBe("cannot find 'vale' in type 'Item'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
//#68
it("supports inheritence of classes", (done) => {
let base = `
export class Base{
value:string;
}`;
let viewmodel = `
import {Base} from './base
export class Foo extends Base{
}`;
let view = `
<template>
\${value}
\${valu}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./base.ts", base);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'valu' in type 'Foo'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
//#68
it("supports inheritence of interfaces", (done) => {
let item = `
export interface BaseItem {
name: string;
}
export interface Item extends BaseItem {
value: string;
}`;
let viewmodel = `
import {Item} from './item
export class Foo{
item: Item;
}`;
let view = `
<template>
\${item.name}
\${item.value}
\${item.valu}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./item.ts", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'valu' in type 'Item'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
//#66
it("supports classes declared in same-file", (done) => {
let item = `
export class Price{
value:string;
}
export class Item{
name:string;
price:Price
}`;
let viewmodel = `
import {Item} from './item
export class Foo {
item:Item;
}`;
let view = `
<template>
\${item.name}
\${item.price.value}
\${item.price.valu}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./item.ts", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'valu' in type 'Price'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
//#66
it("supports interfaces declared in same-file", (done) => {
let item = `
export interface Price{
value:string;
}
export interface Item{
name:string;
price:Price
}`;
let viewmodel = `
import {Item} from './item
export class Foo {
item:Item;
}`;
let view = `
<template>
\${item.name}
\${item.price.value}
\${item.price.valu}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./item.ts", item);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'valu' in type 'Price'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
it("supports delegate binding", (done) => {
let pageViewModel = `
export class Page {
value:number;
public submit() {
}
}`;
let pageView = `
<template>
\${value}
<form role="form" submit.delegate="submit()"></form>
<form role="form" submit.delegate="submt()"></form>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection(), { reportExceptions: true });
let linter = new Linter([rule]);
reflection.add("./page.ts", pageViewModel);
linter.lint(pageView, "./page.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'submt' in type 'Page'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
//87
it("Support named element binding", (done) => {
let viewmodel = `
export class Foo{
existingElement: HTMLSelectElement;
existing: string;
}`;
let view = `
<template>
<select ref="existingElement"></select>
<select ref="missingElement"></select>
\${missing}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection(), { reportExceptions: true });
let linter = new Linter([rule]);
reflection.add("./path/foo.ts", viewmodel);
linter.lint(view, "./path/foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toContain("cannot find 'missing' in type 'Foo'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
// #92
it("supports (svg) attributes with namespace", (done) => {
let viewmodel = `
export class Foo{
existing: string;
}`;
let view = `
<template>
<svg class="icon">
<use xlink:href="icons.svg#some_selector_\${existing}_\${missing}"></use>
</svg>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection(), { reportExceptions: true });
let linter = new Linter([rule]);
reflection.add("./path/foo.ts", viewmodel);
linter.lint(view, "./path/foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toContain("cannot find 'missing' in type 'Foo'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
// #117
it("supports svg element namespace", async (done) => {
var view = `
<svg if.bind="!userContext.imageUri" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" style="width:20px;height:20px;">
<circle cx="20" cy="20" r="18" stroke="grey" stroke-width="1" fill="#FFFFFF" />
<text x="50%" y="50%" text-anchor="middle" stroke="#51c5cf" stroke-width="2px" dy=".3em" letter-spacing="2">
\${userContext.caps}</text>
</svg>
`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection(), { reportExceptions: true });
let linter = new Linter([rule]);
try {
await linter.lint(view, "./path/foo.html")
.then((issues) => {
expect(issues.length).toBe(0);
});
}
catch (err) {
fail(err);
}
finally { done(); }
});
//#119
it("accept binding to ref variables", (done) => {
let viewmodel = `
export class Foo{
someMethod(value){}
}`;
let view = `
<template>
<button click.delegate="someMethod(someName.attributes['expanded'].value)" ref="someName">
</button>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(0);
}
catch (err) { fail(err); }
finally { done(); }
});
});
// #125
it("accept binding to ref variables (not a child)", (done) => {
let viewmodel = `
export class Foo{
someMethod(value){}
}`;
let view = `
<template>
<button ref="someName"></button>
<div>
\${someName.attributes['expanded'].value}
</div>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(0);
}
catch (err) { fail(err); }
finally { done(); }
});
});
//#120
it("Support resolving method args for delegate bindings", (done) => {
let viewmodel = `
export class Foo{
}`;
let view = `
<template>
<button ref="someName" click.delegate="missing(someName.attributes['expanded'].value)">
</button>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'missing' in type 'Foo'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
//#120
it("Support resolving $event method arg for delegate bindings", (done) => {
let viewmodel = `
export class Foo{
method(event){}
}`;
let view = `
<template>
<button ref="someName" keyup.delegate="method($event)"></button>
<button ref="someName" keyup.trigger="method($event)"></button>
<button ref="someName" keyup.delegate="method($evnt)"></button>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find '$evnt' in type 'Foo'");
}
catch (err) { fail(err); }
finally { done(); }
});
});
//#128
xdescribe("@computedFrom decorator usages", () => {
xit("should detect invalid references", (done) => {
const viewmodel = `
export class Foo{
field1: number;
field2: number;
@computedFrom("field1", "missingField1", "field2", "missingField2")
get computedField(){
return this.field1 + this.field2;
}
}`;
const view = `
<template>
\${computedField}
</template>`;
const reflection = new Reflection();
const rule = new BindingRule(reflection, new AureliaReflection());
const linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(2);
expect(issues[0].message).toBe("cannot find 'missingField1' in type 'Foo'");
expect(issues[1].message).toBe("cannot find 'missingField2' in type 'Foo'");
}
catch (err) {
fail(err);
}
finally {
done();
}
});
});
xit("should detect invalid references to nested objects", (done) => {
let price = `
export interface Price{
value:string;
}`;
let item = `
import {Price} from './price';
export interface Item{
name:string;
price:Price;
}`;
const viewmodel = `
import {Item} from './item';
export class Foo{
field1: Item;
field2: Item;
@computedFrom("field1.name", "field1.missingField1", "field2.price.value", "field2.price.missingField2")
get computedField(){
return this.field1 + this.field2;
}
}`;
const view = `
<template>
\${computedField}
</template>`;
const reflection = new Reflection();
const rule = new BindingRule(reflection, new AureliaReflection());
const linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./item", item);
reflection.add("./price.ts", price);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(2);
expect(issues[0].message).toBe("cannot find 'missingField1' in type 'Item'");
expect(issues[1].message).toBe("cannot find 'missingField2' in type 'Price'");
}
catch (err) {
fail(err);
}
finally {
done();
}
});
});
});
// #148
it("Support inherited constructor properties", (done) => {
let base = `
export class Base {
constructor(public sharedValue:number, booboo:string) {
}
}`;
let viewmodel = `
import {Base} from './base'
export class ExtendedItem extends Base {
constructor(sharedValue:number, public extendedValue:number, booboo:string) {
super(sharedValue, booboo);
}
}`;
let view = `
<template>
<span>\${sharedValue}</span>
<span>\${extendedValue}</span>
<span>\${booboo}</span>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./path/base.ts", base);
reflection.add("./path/foo.ts", viewmodel);
linter.lint(view, "./path/foo.html")
.then((issues) => {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'booboo' in type 'ExtendedItem'");
done();
});
});
// #159
it("Choose instance members over static members", (done) => {
let viewmodel = `
export class Foo {
private static bar:number;
bar: number;
}`;
let view = `
<template>
\${bar}
<input text=\"\${bar}\"></input>
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection(), {
});
let linter = new Linter([rule]);
reflection.add("./path/foo.ts", viewmodel);
linter.lint(view, "./path/foo.html")
.then((issues) => {
expect(issues.length).toBe(0);
done();
});
});
// #167
it("Support inheritence (different files)", (done) => {
let viewmodel = `
import {Bar} from './bar';
export class Foo extends Bar {
myProp = "Lorem Ipsum";
}`;
let base = `
export class Bar {
toggled = false;
toggle() {
this.toggled = !this.toggled;
}
}`;
let view = `
<template>
<button click.trigger="toggle()">Toggle me</button>
<p if.bind="toggled">\${myProp}</p>
\${invalid}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection(), {
});
let linter = new Linter([rule]);
reflection.add("./path/foo.ts", viewmodel);
reflection.add("./path/bar.ts", base);
linter.lint(view, "./path/foo.html")
.then((issues) => {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'invalid' in type 'Foo'");
done();
});
});
// #167
it("Support inheritence (same file)", (done) => {
let viewmodel = `
export class Foo extends Bar {
myProp = "Lorem Ipsum";
}
export class Bar {
toggled = false;
toggle() {
this.toggled = !this.toggled;
}
}`;
let view = `
<template>
<button click.trigger="toggle()">Toggle me</button>
<p if.bind="toggled">\${myProp}</p>
\${invalid}
</template>`;
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection(), {
});
let linter = new Linter([rule]);
reflection.add("./path/foo.ts", viewmodel);
linter.lint(view, "./path/foo.html")
.then((issues) => {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'invalid' in type 'Foo'");
done();
});
});
/*it("rejects more than one class in view-model file", (done) => {
let viewmodel = `
export class ChooChoo{
name:string
}
export class Moo{}`
let view = `
<template>
</template>`
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
linter.lint(view, "./foo.html")
.then((issues) => {
expect(issues.length).toBe(1);
if (issues.length === 1) {
expect(issues[0].message).toBe("view-model file should only have one class");
}
done();
})
});*/
/*it("supports generics", (done) => {
let cat = `
export class Cat{
color:string;
}`;
let person = `
export class Person<T>{
name:string;
pet:T;
}`;
let viewmodel = `
import {Person} from './path/person'
import {Cat} from './path/cat'
export class Foo{
person:Person<Cat>
}`
let view = `
<template>
\${person}
\${person.pet}
\${person.pet.color}
\${person.pet.colr}
</template>`
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./foo.ts", viewmodel);
reflection.add("./path/person.ts", person);
reflection.add("./path/cat.ts", cat);
linter.lint(view, "./foo.html")
.then((issues) => {
try {
expect(issues.length).toBe(2);
expect(issues[0].message).toBe("cannot find 'colr' in type 'Cat'")
expect(issues[1].message).toBe("cannot find 'corl' in type 'Cat'")
}
catch(error){expect(error).toBeUndefined()}
finally { done(); }
})
});*/
/*it("supports custom elements", (done) => {
let itemCustomElement = `
import {bindable} from "aurelia-templating";
export class ItemCustomElement {
@bindable value: string;
}`;
let pageViewModel = `
export class Foo {
fooValue:number;
}`
let pageView = `
<template>
<require from="./item"></require>
<item bad.bind="fooValue" value.bind="fooValue"></item>
</template>`
let reflection = new Reflection();
let rule = new BindingRule(reflection, new AureliaReflection());
let linter = new Linter([rule]);
reflection.add("./item.ts", itemCustomElement);
reflection.add("./page.ts", pageViewModel);
linter.lint(pageView, "./page.html")
.then((issues) => {
try {
expect(issues.length).toBe(1);
expect(issues[0].message).toBe("cannot find 'bad' in type 'ItemCustomElement'")
}
catch (err) { fail(err); }
finally { done(); }
})
});*/
}); | the_stack |
import { ethers, network, upgrades, waffle } from "hardhat";
import { Signer, BigNumberish, utils, Wallet } from "ethers";
import chai from "chai";
import { solidity } from "ethereum-waffle";
import "@openzeppelin/test-helpers";
import * as TestHelpers from "../../../../helpers/assert";
import {
MockERC20,
MockERC20__factory,
PancakeFactory,
PancakeFactory__factory,
PancakePair,
PancakePair__factory,
PancakeRouter,
PancakeRouter__factory,
StrategyWithdrawMinimizeTrading,
StrategyWithdrawMinimizeTrading__factory,
WETH,
WETH__factory,
WNativeRelayer__factory,
} from "../../../../../typechain";
chai.use(solidity);
const { expect } = chai;
describe("Pancakeswap - StrategyWithdrawMinimizeTrading", () => {
const FOREVER = "2000000000";
/// Pancake-related instance(s)
let factory: PancakeFactory;
let router: PancakeRouter;
let lp: PancakePair;
let baseTokenWbnbLp: PancakePair;
/// Token-related instance(s)
let wbnb: WETH;
let baseToken: MockERC20;
let farmingToken: MockERC20;
/// Strategy-ralted instance(s)
let strat: StrategyWithdrawMinimizeTrading;
// Accounts
let deployer: Signer;
let alice: Signer;
let bob: Signer;
// Contract Signer
let baseTokenAsAlice: MockERC20;
let baseTokenAsBob: MockERC20;
let baseTokenWbnbLpAsBob: PancakePair;
let lpAsAlice: PancakePair;
let lpAsBob: PancakePair;
let farmingTokenAsAlice: MockERC20;
let farmingTokenAsBob: MockERC20;
let routerAsAlice: PancakeRouter;
let routerAsBob: PancakeRouter;
let stratAsAlice: StrategyWithdrawMinimizeTrading;
let stratAsBob: StrategyWithdrawMinimizeTrading;
let wbnbAsAlice: WETH;
let wbnbAsBob: WETH;
async function fixture() {
[deployer, alice, bob] = await ethers.getSigners();
// Setup Pancake
const PancakeFactory = (await ethers.getContractFactory("PancakeFactory", deployer)) as PancakeFactory__factory;
factory = await PancakeFactory.deploy(await deployer.getAddress());
await factory.deployed();
const WETH = (await ethers.getContractFactory("WETH", deployer)) as WETH__factory;
wbnb = await WETH.deploy();
await factory.deployed();
const PancakeRouter = (await ethers.getContractFactory("PancakeRouter", deployer)) as PancakeRouter__factory;
router = await PancakeRouter.deploy(factory.address, wbnb.address);
await router.deployed();
/// Setup token stuffs
const MockERC20 = (await ethers.getContractFactory("MockERC20", deployer)) as MockERC20__factory;
baseToken = (await upgrades.deployProxy(MockERC20, ["BTOKEN", "BTOKEN", 18])) as MockERC20;
await baseToken.deployed();
await baseToken.mint(await alice.getAddress(), ethers.utils.parseEther("100"));
await baseToken.mint(await bob.getAddress(), ethers.utils.parseEther("100"));
farmingToken = (await upgrades.deployProxy(MockERC20, ["FTOKEN", "FTOKEN", 18])) as MockERC20;
await farmingToken.deployed();
await farmingToken.mint(await alice.getAddress(), ethers.utils.parseEther("1"));
await farmingToken.mint(await bob.getAddress(), ethers.utils.parseEther("1"));
await factory.createPair(baseToken.address, farmingToken.address);
await factory.createPair(baseToken.address, wbnb.address);
lp = PancakePair__factory.connect(await factory.getPair(farmingToken.address, baseToken.address), deployer);
baseTokenWbnbLp = PancakePair__factory.connect(await factory.getPair(wbnb.address, baseToken.address), deployer);
/// Setup WNativeRelayer
const WNativeRelayer = (await ethers.getContractFactory("WNativeRelayer", deployer)) as WNativeRelayer__factory;
const wNativeRelayer = await WNativeRelayer.deploy(wbnb.address);
await wNativeRelayer.deployed();
/// Setup StrategyWithdrawMinimizeTrading
const StrategyWithdrawMinimizeTrading = (await ethers.getContractFactory(
"StrategyWithdrawMinimizeTrading",
deployer
)) as StrategyWithdrawMinimizeTrading__factory;
strat = (await upgrades.deployProxy(StrategyWithdrawMinimizeTrading, [
router.address,
wbnb.address,
wNativeRelayer.address,
])) as StrategyWithdrawMinimizeTrading;
await strat.deployed();
await wNativeRelayer.setCallerOk([strat.address], true);
// Assign contract signer
baseTokenAsAlice = MockERC20__factory.connect(baseToken.address, alice);
baseTokenAsBob = MockERC20__factory.connect(baseToken.address, bob);
baseTokenWbnbLpAsBob = PancakePair__factory.connect(baseTokenWbnbLp.address, bob);
farmingTokenAsAlice = MockERC20__factory.connect(farmingToken.address, alice);
farmingTokenAsBob = MockERC20__factory.connect(farmingToken.address, bob);
routerAsAlice = PancakeRouter__factory.connect(router.address, alice);
routerAsBob = PancakeRouter__factory.connect(router.address, bob);
lpAsAlice = PancakePair__factory.connect(lp.address, alice);
lpAsBob = PancakePair__factory.connect(lp.address, bob);
stratAsAlice = StrategyWithdrawMinimizeTrading__factory.connect(strat.address, alice);
stratAsBob = StrategyWithdrawMinimizeTrading__factory.connect(strat.address, bob);
wbnbAsAlice = WETH__factory.connect(wbnb.address, alice);
wbnbAsBob = WETH__factory.connect(wbnb.address, bob);
// Set block base fee per gas to 0
await network.provider.send("hardhat_setNextBlockBaseFeePerGas", ["0x0"]);
}
beforeEach(async () => {
await waffle.loadFixture(fixture);
});
context("It should convert LP tokens and farming token", () => {
beforeEach(async () => {
// Alice adds 0.1 FTOKEN + 1 BaseToken
await baseTokenAsAlice.approve(router.address, ethers.utils.parseEther("1"));
await farmingTokenAsAlice.approve(router.address, ethers.utils.parseEther("0.1"));
await routerAsAlice.addLiquidity(
baseToken.address,
farmingToken.address,
ethers.utils.parseEther("1"),
ethers.utils.parseEther("0.1"),
"0",
"0",
await alice.getAddress(),
FOREVER
);
// Bob tries to add 1 FTOKEN + 1 BaseToken (but obviously can only add 0.1 FTOKEN)
await baseTokenAsBob.approve(router.address, ethers.utils.parseEther("1"));
await farmingTokenAsBob.approve(router.address, ethers.utils.parseEther("1"));
await routerAsBob.addLiquidity(
baseToken.address,
farmingToken.address,
ethers.utils.parseEther("1"),
ethers.utils.parseEther("1"),
"0",
"0",
await bob.getAddress(),
FOREVER
);
expect(await farmingToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0.9"));
expect(await lp.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0.316227766016837933"));
await lpAsBob.transfer(strat.address, ethers.utils.parseEther("0.316227766016837933"));
});
it("should revert, Bob uses withdraw minimize trading strategy to turn LPs back to farming with an unreasonable expectation", async () => {
// Bob uses withdraw minimize trading strategy to turn LPs back to farming with an unreasonable expectation
await expect(
stratAsBob.execute(
await bob.getAddress(),
ethers.utils.parseEther("1"),
ethers.utils.defaultAbiCoder.encode(
["address", "address", "uint256"],
[baseToken.address, farmingToken.address, ethers.utils.parseEther("2")]
)
)
).to.be.revertedWith("StrategyWithdrawMinimizeTrading::execute:: insufficient farming tokens received");
});
it("should convert all LP tokens back to BaseToken and FTOKEN, while debt == received BaseToken", async () => {
const bobBaseTokenBefore = await baseToken.balanceOf(await bob.getAddress());
const bobFTOKENBefore = await farmingToken.balanceOf(await bob.getAddress());
// Bob uses minimize trading strategy to turn LPs back to BaseToken and FTOKEN
await stratAsBob.execute(
await bob.getAddress(),
ethers.utils.parseEther("1"), // debt 1 BaseToken
ethers.utils.defaultAbiCoder.encode(
["address", "address", "uint256"],
[baseToken.address, farmingToken.address, ethers.utils.parseEther("0.001")]
)
);
const bobBaseTokenAfter = await baseToken.balanceOf(await bob.getAddress());
const bobFTOKENAfter = await farmingToken.balanceOf(await bob.getAddress());
expect(await lp.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await lp.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(bobBaseTokenAfter.sub(bobBaseTokenBefore)).to.be.eq(ethers.utils.parseEther("1"));
expect(bobFTOKENAfter.sub(bobFTOKENBefore)).to.be.eq(ethers.utils.parseEther("0.1"));
});
it("should convert all LP tokens back to BaseToken and FTOKEN when debt < received BaseToken", async () => {
const bobBtokenBefore = await baseToken.balanceOf(await bob.getAddress());
const bobFtokenBefore = await farmingToken.balanceOf(await bob.getAddress());
// Bob uses liquidate strategy to turn LPs back to ETH and farming token
await stratAsBob.execute(
await bob.getAddress(),
ethers.utils.parseEther("0.5"), // debt 0.5 ETH
ethers.utils.defaultAbiCoder.encode(
["address", "address", "uint256"],
[baseToken.address, farmingToken.address, ethers.utils.parseEther("0.001")]
)
);
const bobBtokenAfter = await baseToken.balanceOf(await bob.getAddress());
const bobFtokenAfter = await farmingToken.balanceOf(await bob.getAddress());
expect(await lp.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await lp.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(bobBtokenAfter.sub(bobBtokenBefore)).to.be.eq(ethers.utils.parseEther("1"));
expect(bobFtokenAfter.sub(bobFtokenBefore)).to.be.eq(ethers.utils.parseEther("0.1"));
});
it("should convert all LP tokens back to BaseToken and farming token (debt > received BaseToken, farming token is enough to cover debt)", async () => {
const bobBtokenBefore = await baseToken.balanceOf(await bob.getAddress());
const bobFtokenBefore = await farmingToken.balanceOf(await bob.getAddress());
// Bob uses withdraw minimize trading strategy to turn LPs back to BaseToken and farming token
await stratAsBob.execute(
await bob.getAddress(),
ethers.utils.parseEther("1.2"), // debt 1.2 BaseToken
ethers.utils.defaultAbiCoder.encode(
["address", "address", "uint256"],
[baseToken.address, farmingToken.address, ethers.utils.parseEther("0.001")]
)
);
const bobBtokenAfter = await baseToken.balanceOf(await bob.getAddress());
const bobFtokenAfter = await farmingToken.balanceOf(await bob.getAddress());
expect(await lp.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await lp.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(bobBtokenAfter.sub(bobBtokenBefore)).to.be.eq(ethers.utils.parseEther("1.2"));
expect(bobFtokenAfter.sub(bobFtokenBefore)).to.be.eq(ethers.utils.parseEther("0.074949899799599198")); // 0.1 - 0.025 = 0.075 farming token
});
it("should revert when debt > received BaseToken, farming token is not enough to cover the debt", async () => {
await expect(
stratAsBob.execute(
await bob.getAddress(),
ethers.utils.parseEther("3"), // debt 2 BaseToken
ethers.utils.defaultAbiCoder.encode(
["address", "address", "uint256"],
[baseToken.address, farmingToken.address, ethers.utils.parseEther("0.001")]
)
)
).to.be.revertedWith("subtraction overflow");
});
});
context("It should handle properly when the farming token is WBNB", () => {
beforeEach(async () => {
// Alice wrap BNB
await wbnbAsAlice.deposit({ value: ethers.utils.parseEther("0.1") });
// Alice adds 0.1 WBNB + 1 BaseToken
await baseTokenAsAlice.approve(router.address, ethers.utils.parseEther("1"));
await wbnbAsAlice.approve(router.address, ethers.utils.parseEther("0.1"));
await routerAsAlice.addLiquidity(
baseToken.address,
wbnb.address,
ethers.utils.parseEther("1"),
ethers.utils.parseEther("0.1"),
"0",
"0",
await alice.getAddress(),
FOREVER
);
// Bob wrap BNB
await wbnbAsBob.deposit({ value: ethers.utils.parseEther("1") });
// Bob tries to add 1 WBNB + 1 BaseToken (but obviously can only add 0.1 WBNB)
await baseTokenAsBob.approve(router.address, ethers.utils.parseEther("1"));
await wbnbAsBob.approve(router.address, ethers.utils.parseEther("1"));
await routerAsBob.addLiquidity(
baseToken.address,
wbnb.address,
ethers.utils.parseEther("1"),
ethers.utils.parseEther("1"),
"0",
"0",
await bob.getAddress(),
FOREVER
);
expect(await wbnb.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0.9"));
expect(await baseTokenWbnbLp.balanceOf(await bob.getAddress())).to.be.eq(
ethers.utils.parseEther("0.316227766016837933")
);
await baseTokenWbnbLpAsBob.transfer(strat.address, ethers.utils.parseEther("0.316227766016837933"));
});
it("should revert, Bob uses withdraw minimize trading strategy to turn LPs back to farming with an unreasonable expectation", async () => {
// Bob uses withdraw minimize trading strategy to turn LPs back to farming with an unreasonable expectation
await expect(
stratAsBob.execute(
await bob.getAddress(),
ethers.utils.parseEther("1"),
ethers.utils.defaultAbiCoder.encode(
["address", "address", "uint256"],
[baseToken.address, wbnb.address, ethers.utils.parseEther("2")]
)
)
).to.be.revertedWith("StrategyWithdrawMinimizeTrading::execute:: insufficient farming tokens received");
});
it("should convert all LP tokens back to BaseToken and BNB, while debt == received BaseToken", async () => {
const bobBaseTokenBefore = await baseToken.balanceOf(await bob.getAddress());
const bobBnbBefore = await ethers.provider.getBalance(await bob.getAddress());
// Bob uses minimize trading strategy to turn LPs back to BaseToken and BNB
// set gasPrice = 0 in order to assert native balance movement easier
await stratAsBob.execute(
await bob.getAddress(),
ethers.utils.parseEther("1"), // debt 1 BaseToken
ethers.utils.defaultAbiCoder.encode(
["address", "address", "uint256"],
[baseToken.address, wbnb.address, ethers.utils.parseEther("0.001")]
),
{ gasPrice: 0 }
);
const bobBaseTokenAfter = await baseToken.balanceOf(await bob.getAddress());
const bobBnbAfter = await ethers.provider.getBalance(await bob.getAddress());
expect(await baseTokenWbnbLp.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await baseTokenWbnbLp.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
// Bob still get 1 BTOKEN back due to Bob is a msg.sender
expect(bobBaseTokenAfter.sub(bobBaseTokenBefore)).to.be.eq(ethers.utils.parseEther("1"));
TestHelpers.assertAlmostEqual(
ethers.utils.parseEther("0.1").toString(),
bobBnbAfter.sub(bobBnbBefore).toString()
);
});
it("should convert all LP tokens back to BaseToken and FTOKEN when debt < received BaseToken", async () => {
const bobBtokenBefore = await baseToken.balanceOf(await bob.getAddress());
const bobBnbBefore = await ethers.provider.getBalance(await bob.getAddress());
// Bob uses liquidate strategy to turn LPs back to ETH and farming token
// set gasPrice = 0 in order to assert native balance movement easier
await stratAsBob.execute(
await bob.getAddress(),
ethers.utils.parseEther("0.5"), // debt 0.5 ETH
ethers.utils.defaultAbiCoder.encode(
["address", "address", "uint256"],
[baseToken.address, wbnb.address, ethers.utils.parseEther("0.001")]
),
{ gasPrice: 0 }
);
const bobBtokenAfter = await baseToken.balanceOf(await bob.getAddress());
const bobBnbAfter = await ethers.provider.getBalance(await bob.getAddress());
expect(await lp.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await lp.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
// Bob still get 1 BTOKEN back due to Bob is a msg.sender which get .5 debt
// and StrategyWithdrawMinimizeTrading returns another .5 BTOKEN
expect(bobBtokenAfter.sub(bobBtokenBefore)).to.be.eq(ethers.utils.parseEther("1"));
TestHelpers.assertAlmostEqual(
ethers.utils.parseEther("0.1").toString(),
bobBnbAfter.sub(bobBnbBefore).toString()
);
});
it("should convert all LP tokens back to BaseToken and BNB (debt > received BaseToken, BNB is enough to cover debt)", async () => {
const bobBtokenBefore = await baseToken.balanceOf(await bob.getAddress());
const bobBnbBefore = await ethers.provider.getBalance(await bob.getAddress());
// Bob uses withdraw minimize trading strategy to turn LPs back to BaseToken and BNB
// set gasPrice = 0 in order to assert native balance movement easier
await stratAsBob.execute(
await bob.getAddress(),
ethers.utils.parseEther("1.2"), // debt 1.2 BaseToken
ethers.utils.defaultAbiCoder.encode(
["address", "address", "uint256"],
[baseToken.address, wbnb.address, ethers.utils.parseEther("0.001")]
),
{ gasPrice: 0 }
);
const bobBtokenAfter = await baseToken.balanceOf(await bob.getAddress());
const bobBnbAfter = await ethers.provider.getBalance(await bob.getAddress());
expect(await lp.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await lp.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
// Bob still get 1.2 BTOKEN back due to Bob is a msg.sender which get 1 BTOKEN from LP
// and 0.2 BTOKEN from swap BNB to BTOKEN
expect(bobBtokenAfter.sub(bobBtokenBefore)).to.be.eq(ethers.utils.parseEther("1.2"));
TestHelpers.assertAlmostEqual(
ethers.utils.parseEther("0.074949899799599198").toString(),
bobBnbAfter.sub(bobBnbBefore).toString()
);
});
it("should revert when debt > received BaseToken, BNB is not enough to cover the debt", async () => {
await expect(
stratAsBob.execute(
await bob.getAddress(),
ethers.utils.parseEther("3"), // debt 3 BTOKEN
ethers.utils.defaultAbiCoder.encode(
["address", "address", "uint256"],
[baseToken.address, wbnb.address, ethers.utils.parseEther("0.001")]
)
)
).to.be.revertedWith("subtraction overflow");
});
});
}); | the_stack |
* 此组件为基础组件,用于数据开发画布节点基类,所有节点详情可基于此类扩展
* 谨慎修改,所有修改需要进行 merge request 评审
*/
import Bus from '@/common/js/bus.js';
import { exitFullscreen, fullScreen, isFullScreen } from '@/common/js/util.js';
import { deduplicate } from '@/common/js/util.js';
import { bkButton } from 'bk-magic-vue';
import styled from '@tencent/vue-styled-components';
import { CreateElement } from 'vue';
import { Component, Emit, Model, Prop, PropSync, ProvideReactive, Vue, Watch } from 'vue-property-decorator';
import { mapGetters } from 'vuex';
import { INodeParams } from '../../interface/INodeParams';
import GraphNodeLayout from './GraphNode.Layout';
import StyledVue from './StyledVue';
const bkbuttonProps = {};
/** 节点详情组件 */
const StyledRoot = {
/** 节点头部组件 */
Header: styled('section', {})`
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
padding: 15px 20px;
position: relative;
line-height: normal;
`,
/** 节点标题(名称) */
Title: styled('div', {})`
font-size: 18px;
margin-bottom: 10px;
color: #333;
display: flex;
align-items: center;
font-weight: 400;
position: relative;
width: 100%;
`,
/** 节点子标题(描述) */
SubTitle: styled('div', {})`
display: flex;
font-size: 14px;
font-weight: 400;
color: #888;
width: 100%;
`,
/** 节点Icon */
TitleIcon: styled('i', {})`
margin-right: 5px;
`,
/** 工具区域组件 */
TitleTool: styled('div')`
position: absolute;
top: 0;
right: 0;
bottom: 0;
`,
/** 工具条目 */
ToolItem: styled('span')`
font-size: 14px;
line-height: 19px;
margin-right: 20px;
cursor: pointer;
color: #979ba5;
`,
/** 工具Icon */
ToolIcon: styled('i')`
margin-right: 5px;
color: #c4c6cc;
`,
FooterButton: styled('button', bkbuttonProps, { clsName: 'bkdata-button' })`
width: 120px;
margin-right: 10px;
`.withComponent(bkButton),
};
@Component({
components: {
GraphNodeLayout,
},
computed: {
...mapGetters({
allBizList: 'global/getAllBizList',
}),
},
})
export default class GraphNodeBase extends StyledVue {
@ProvideReactive() public parentResultTables = [];
/** 节点类型 */
@Prop({ default: 'Node Type' }) nodeType!: string;
/** 描述 */
@Prop({ default: 'Description' }) description!: string;
/** 显示Icon */
@Prop({ default: 'icon-nodata' }) IconName!: string;
/** 帮助文档 */
@Prop({ default: undefined }) helpUrl!: string;
/** 保存按钮loading */
@Prop({ default: false }) public isSaving: boolean = false;
/** 是否为全屏 */
public isFullScreen: boolean = false;
public selfConfig: object = {};
public parentConfig: object = {};
public bizList: object[] = [];
public loading: boolean = false;
public params: INodeParams = {
config: {
name: 'string',
bk_biz_id: '',
dedicated_config: {},
node_type: '',
},
};
/**
* 提交表单信息
* 不同节点的表单信息略有差异
* 根据继承的节点自动扩展
*/
public formData: any = {
params: {},
};
/**
* 提交表单数据校验设置
* 根据不同节点类型设置
*/
public validateForm: any = {};
get fullScreenIcon() {
return this.isFullScreen ? 'icon-un-full-screen' : 'icon-full-screen';
}
public mounted() {
this.$emit('nodeDetailMounted', this);
}
public getBizNameByBizId(id: string | number) {
id = String(id);
const result = (this.allBizList || []).find(biz => biz.bk_biz_id === id) || {};
return result.bk_biz_name || '';
}
public initOutput() { }
public customValidateForm() { } // 自定义校验,由子组件实现
public customSetConfigBack() { } // 自定义回填,由子组件实现,且必须返回一个Promise
public validateFormData() {
this.params.config.bk_biz_id = this.params.config.outputs[0].bk_biz_id; // 没有什么意义,之后考虑去掉
/** 更新节点时需要flowid */
if (this.selfConfig.hasOwnProperty('node_id')) {
this.params.flow_id = this.$route.params.fid;
}
return this.customValidateForm();
}
public async setConfigBack(self, source, fl, option = {}) {
this.loading = true;
/** 画布缓存数据处理 */
let tempConfig = this.$store.state.ide.tempNodeConfig.find(item => {
return item.node_key === self.id;
});
const cacheConfig = await this.bkRequest.httpRequest('dataFlow/getCatchData', {
query: { key: 'node_' + self.id },
});
if (cacheConfig.result) {
tempConfig = Object.assign({ config: {} }, tempConfig, { config: cacheConfig.data });
}
if (tempConfig && !self.hasOwnProperty('node_id')) {
self.node_config = tempConfig.config;
}
/** 节点数据回填 */
this.activeTab = option.elType === 'referTask' ? 'referTasks' : 'config';
this.selfConfig = self;
this.parentConfig = deduplicate(JSON.parse(JSON.stringify(source)), 'id');
this.params.frontend_info = self.frontend_info;
this.params.from_links = fl;
const parentList = this.parentConfig.reduce((output, config) => [...output, ...config.result_table_ids], []);
await this.getResultList(parentList);
if (self.hasOwnProperty('node_id') || self.isCopy || tempConfig) {
for (const key in self.node_config) {
// 去掉 null、undefined, [], '', fals
if (key === 'inputs') {
continue;
}
if (self.node_config[key] !== null) {
this.params.config[key] = self.node_config[key];
if (key === 'outputs') {
this.params.config[key].forEach(output => {
this.$set(output, 'validate', {
table_name: {
// 输出编辑框 数据输出
status: false,
errorMsg: '',
},
output_name: {
// 输出编辑框 中文名称
status: false,
errorMsg: '',
},
field_config: {
status: false,
errorMsg: this.$t('必填项不可为空'),
},
});
});
}
}
}
}
this.parentConfig.forEach(parent => {
// 在离线节点的父节点是离线节点时,传来的父节点对象里result_table_id为null,需要赋值
if (!parent.result_table_id) {
parent.result_table_id = parent.result_table_ids[0];
}
const parentRts = parent.result_table_ids;
/** 数据输入相关 */
this.params.config.inputs.push({
id: parent.node_id,
from_result_table_ids: parentRts,
});
const selectInputList = {
id: parent.node_id,
name: parent.node_name,
children: [],
};
parentRts.forEach(item => {
const listItem = {
id: `${item}(${parent.node_id})`,
name: `${item}(${parent.node_id})`,
disabled: parentRts.length === 1,
// name: `${item}(${parent.output_description})`
};
selectInputList.children.push(listItem);
});
// this.dataInputList.push(selectInputList)
/** 根据parent配置biz_list */
const bizId = parent.bk_biz_id;
if (!this.bizList.some(item => item.biz_id === bizId)) {
this.bizList.push({
name: this.getBizNameByBizId(bizId),
biz_id: bizId,
});
}
});
this.$nextTick(() => {
this.initOutput();
});
this.customSetConfigBack().then(resolve => {
this.loading = false;
Bus.$emit('nodeConfigBack');
});
}
public async getResultList(resultTableIds = []) {
return this.getAllResultList(resultTableIds)
.then(res => {
this.$set(this, 'parentResultTables', res);
})
['catch'](err => {
this.getMethodWarning(err.message, 'error');
});
}
public getAllResultList(resultTableIds = []) {
const resultList = {};
return Promise.all(resultTableIds.map(id => this.getResultListByResultTableId(id)))
.then(res => {
return Promise.resolve(
res.reduce(
(pre, current) => Object.assign(pre, {
[current.resultTableId]: {
fields: current.fields,
resultTable: {
id: current.result_table_id,
name: current.result_table_name,
alias: current.result_table_name_alias,
},
},
}),
resultList
)
);
})
['catch'](err => {
this.getMethodWarning(err.message, 'error');
return Promise.reject(err);
});
}
/*
获取结果字段表
*/
public getResultListByResultTableId(id) {
return this.bkRequest.httpRequest('meta/getResultTablesWithFields', { params: { rtid: id } }).then(res => {
if (res.result) {
return Promise.resolve({
fields: res.data.fields
.filter(item => item.field_name !== '_startTime_' && item.field_name !== '_endTime_')
.map(field => ({
name: field.field_name,
type: field.field_type,
alias: field.field_alias,
des: field.description,
})),
resultTableId: id,
});
} else {
return Promise.reject(res);
}
});
}
public getCode() {
const Inputs = this.parentResultTables;
const rtId = Object.keys(Inputs)[0];
const parentResult = Inputs[rtId];
let sql = '';
for (let i = 0; i < parentResult.fields.length; i++) {
sql += parentResult.fields[i].name + ', ';
if (i % 3 === 0 && i !== 0) {
sql += '\n ';
}
}
const index = sql.lastIndexOf(',');
sql = sql.slice(0, index);
if (!sql) {
sql = '*';
}
return 'select ' + sql + '\nfrom ' + rtId;
}
/** 全屏操作 */
public handleFullscreenClick() {
this.isFullScreen = !isFullScreen();
!this.isFullScreen ? exitFullscreen() : fullScreen(this.$el);
}
/** 提交表单 */
public handleSubmitClick() {
if (this.beforeSubmit()) {
this.$emit('submit', this.params);
}
}
/** 取消逻辑 */
public handleCancelClick() {
this.$emit('cancel', this.formData);
}
/**
* 表单提交之前钩子
* 子组件可以重写此函数,用于单独的校验逻辑
*/
public beforeSubmit(): Boolean {
return true;
}
/** 渲染Header适配器 */
public getHeaderAdapter(h: CreateElement) {
return (
<StyledRoot.Header>
<StyledRoot.Title>
<StyledRoot.TitleIcon class={`bk-icon ${this.IconName}`}></StyledRoot.TitleIcon>
{this.nodeType}
<StyledRoot.TitleTool>
<StyledRoot.ToolItem onClick={this.handleFullscreenClick}>
<StyledRoot.ToolIcon class={`bkdata-icon ${this.fullScreenIcon}`}></StyledRoot.ToolIcon>
{this.$t('全屏')}
</StyledRoot.ToolItem>
{this.helpUrl && (
<StyledRoot.ToolItem>
<StyledRoot.ToolIcon class="bkdata-icon icon-help-fill"></StyledRoot.ToolIcon>
<a href={this.helpUrl} target="_blank">
{this.$t('帮助文档')}
</a>
</StyledRoot.ToolItem>
)}
</StyledRoot.TitleTool>
</StyledRoot.Title>
<StyledRoot.SubTitle>{this.description}</StyledRoot.SubTitle>
</StyledRoot.Header>
);
}
/**
* 渲染body适配器
* @param h
*/
public getBodyAdapter(h: CreateElement) {
return this.$slots['default'];
}
/** 渲染Footer适配器 */
public getFooterAdapter(h: CreateElement) {
return (
<div>
<StyledRoot.FooterButton theme="primary" loading={this.isSaving} onClick={this.handleSubmitClick}>
{this.$t('保存')}
</StyledRoot.FooterButton>
<StyledRoot.FooterButton onClick={this.handleCancelClick}>{this.$t('取消')}</StyledRoot.FooterButton>
</div>
);
}
public render(h: CreateElement) {
return (
<GraphNodeLayout>
<template slot="header">{this.getHeaderAdapter(h)}</template>
<template slot="default">
<div className="node-content-wrapper"
style="height: 100%"
v-bkloading={{ isLoading: this.loading }}>
{this.getBodyAdapter(h)}
</div>
</template>
<template slot="footer">{this.getFooterAdapter(h)}</template>
</GraphNodeLayout>
);
}
} | the_stack |
import { Inject, Injectable, HttpService } from '@nestjs/common'
import { InjectModel } from '@nestjs/sequelize'
import format from 'date-fns/format'
import {
RecyclingRequestModel,
RecyclingRequestUnion,
RequestErrors,
RequestStatus,
} from './model/recycling.request.model'
import type { Logger } from '@island.is/logging'
import { LOGGER_PROVIDER } from '@island.is/logging'
import { FjarsyslaService } from '../fjarsysla/models/fjarsysla.service'
import { RecyclingPartnerService } from '../recycling.partner/recycling.partner.service'
import { VehicleService } from '../vehicle/vehicle.service'
import { environment } from '../../../environments'
import { VehicleModel } from '../vehicle/model/vehicle.model'
@Injectable()
export class RecyclingRequestService {
constructor(
@InjectModel(RecyclingRequestModel)
private recyclingRequestModel: typeof RecyclingRequestModel,
@Inject(LOGGER_PROVIDER) private logger: Logger,
private httpService: HttpService,
@Inject(FjarsyslaService)
private fjarsyslaService: FjarsyslaService,
@Inject(RecyclingPartnerService)
private recycllingPartnerService: RecyclingPartnerService,
@Inject(VehicleService)
private vehicleService: VehicleService,
) {}
async deRegisterVehicle(vehiclePermno: string, disposalStation: string) {
try {
this.logger.info(
`---- Starting deRegisterVehicle call on ${vehiclePermno} ----`,
)
const {
restAuthUrl,
restDeRegUrl,
restUsername,
restPassword,
} = environment.samgongustofa
const jsonObj = {
username: restUsername,
password: restPassword,
}
const jsonAuthBody = JSON.stringify(jsonObj)
const headerAuthRequest = {
'Content-Type': 'application/json',
}
// TODO: saved jToken and use it in next 7 days ( until it expires )
const authRes = await this.httpService
.post(restAuthUrl, jsonAuthBody, { headers: headerAuthRequest })
.toPromise()
if (authRes.status > 299 || authRes.status < 200) {
this.logger.error(authRes.statusText)
throw new Error(authRes.statusText)
}
// DeRegisterd vehicle
const jToken = authRes.data['jwtToken']
this.logger.info(
'Finished Authentication request and starting deRegister request',
)
const jsonDeRegBody = JSON.stringify({
permno: vehiclePermno,
deRegisterDate: format(new Date(), "yyyy-MM-dd'T'HH:mm:ss"),
disposalstation: disposalStation,
explanation: 'Rafrænt afskráning',
})
const headerDeRegRequest = {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + jToken,
}
this.logger.info(`RestUrl: ${restDeRegUrl}`)
this.logger.info(`RestHeader: ${headerDeRegRequest}`)
this.logger.info(`RestBody: ${jsonDeRegBody}`)
const deRegRes = await this.httpService
.post(restDeRegUrl, jsonDeRegBody, { headers: headerDeRegRequest })
.toPromise()
if (deRegRes.status < 300 && deRegRes.status >= 200) {
this.logger.info(
`---- Finished deRegisterVehicle call on ${vehiclePermno} ----`,
)
return true
} else {
this.logger.info(deRegRes.statusText)
throw new Error(deRegRes.statusText)
}
} catch (err) {
this.logger.error(
`Failed on deregistered vehicle ${vehiclePermno} with: ${err}`,
)
throw new Error(
`Failed on deregistered vehicle ${vehiclePermno} because: ${err}`,
)
}
}
async findAll(): Promise<RecyclingRequestModel[]> {
this.logger.info('---- Starting findAll Recycling request ----')
const res = await this.recyclingRequestModel.findAll()
return res
}
// Find all a vehicle's requests
async findAllWithPermno(permno: string): Promise<RecyclingRequestModel[]> {
this.logger.info(
`---- Starting findAllWithPermno Recycling request for ${permno} ----`,
)
try {
const res = await this.recyclingRequestModel.findAll({
where: { vehicleId: permno },
order: [['createdAt', 'DESC']],
})
this.logger.info(
`---- Finished findAllWithPermno Recycling request for ${permno} ----`,
)
return res
} catch (err) {
this.logger.error(
`Getting error when trying to findAllWithPermno: ${permno}`,
)
throw new Error(err)
}
}
// Find all a vehicle's requests
async getVehicleInfoToDeregistered(permno: string): Promise<VehicleModel> {
this.logger.info(
`---- Starting getVehicleInfoToDeregistered request for ${permno} ----`,
)
try {
// Check 'pendingRecycle' status
this.logger.info(`Getting lastest requestType on vehicle: ${permno}`)
const resRequestType = await this.findAllWithPermno(permno)
if (resRequestType.length > 0) {
if (
resRequestType[0]['dataValues']['requestType'] != 'pendingRecycle'
) {
this.logger.error(
`Lastest requestType of vehicle's number ${permno} is not 'pendingRecycle' but is: ${resRequestType[0]['dataValues']['requestType']}`,
)
throw new Error(
`Lastest requestType of vehicle's number ${permno} is not 'pendingRecycle' but is: ${resRequestType[0]['dataValues']['requestType']}`,
)
}
} else {
this.logger.error(
`Could not find any requestType for vehicle's number: ${permno} in database`,
)
throw new Error(
`Could not find any requestType for vehicle's number: ${permno} in database`,
)
}
// Get vehicle's information
this.logger.info(`Getting vehicle's information for vehicle: ${permno}`)
const res = await this.vehicleService.findByVehicleId(permno)
if (!res) {
this.logger.error(
`Could not find any vehicle's information for vehicle's number: ${permno} in database`,
)
throw new Error(
`Could not find any vehicle's information for vehicle's number: ${permno} in database`,
)
}
this.logger.info(
`---- Finished getVehicleInfoToDeregistered request for ${permno} ----`,
)
return res
} catch (err) {
this.logger.error(
`Getting error when trying to getVehicleInfoToDeregistered: ${permno}`,
)
throw new Error(err)
}
}
// Create new RecyclingRequest for citizen and recycling partner.
// partnerId could be null, when it's the request is for citizen
async createRecyclingRequest(
requestType: string,
permno: string,
nameOfRequestor: string,
partnerId: string,
): Promise<typeof RecyclingRequestUnion> {
const errors = new RequestErrors()
try {
this.logger.info(
`---- Starting update requestType for ${permno} to requestType: ${requestType} ----`,
)
// nameOfRequestor and partnerId are not required arguments
// But partnerId and partnerId could not both be null at the same time
if (!nameOfRequestor && !partnerId) {
this.logger.error(
`partnerId and nameOfRequestor could not be null at the same time.`,
)
errors.operation = 'Checking arguments'
errors.message = `Not all required fields are filled. Please contact admin.`
return errors
}
// If requestType is 'deregistered'
// partnerId could not be null when create requestType for recycling partner.
if (requestType == 'deregistered' && !partnerId) {
this.logger.error(
`partnerId could not be null when create requestType 'deregistered' for recylcing partner`,
)
errors.operation = 'Checking partnerId'
errors.message = `Not all required fields are filled. Please contact admin.`
return errors
}
// If requestType is not 'pendingRecycle', 'cancelled' or 'deregistered'
if (
!(
requestType == 'pendingRecycle' ||
requestType == 'cancelled' ||
requestType == 'deregistered'
)
) {
this.logger.error(
`requestType have to be 'pendingRecycle', 'cancelled' or 'deregistered'`,
)
errors.operation = 'Checking requestType'
errors.message = `RequestType is incorrect. Please contact admin.`
return errors
}
// Initalise new RecyclingRequest
const newRecyclingRequest = new RecyclingRequestModel()
newRecyclingRequest.vehicleId = permno
newRecyclingRequest.requestType = requestType
if (nameOfRequestor) {
newRecyclingRequest.nameOfRequestor = nameOfRequestor
}
// is partnerId null?
if (partnerId) {
newRecyclingRequest.recyclingPartnerId = partnerId
const partner = await this.recycllingPartnerService.findByPartnerId(
partnerId,
)
if (!partner) {
this.logger.error(
`Could not find Partner from partnerId: ${partnerId}`,
)
errors.operation = 'Checking partner'
errors.message = `Your station is not in the recycling station list. Please contact admin.`
return errors
}
newRecyclingRequest.nameOfRequestor = partner['companyName']
}
// Checking if 'permno' is already in the database
const isVehicle = await this.vehicleService.findByVehicleId(permno)
if (!isVehicle) {
this.logger.error(`Vehicle ${permno} has not been saved in database`)
errors.operation = 'Checking vehicle'
errors.message = `Citizen has not accepted to recycle the vehicle.`
return errors
}
// Here is a bit tricky
// 1. Check if lastest vehicle's requestType is 'pendingRecycle'
// 2. Set requestType to 'handOver'
// 3. Then deregistered the vehicle from Samgongustofa
// 4. Set requestType to 'deregistered'
// 5. Then call fjarsysla for payment
// 6. Set requestType to 'paymentInitiated'
// If we encounter error then update requestType to 'paymentFailed'
// If we encounter error with 'partnerId' then there is no request saved
if (requestType == 'deregistered') {
// 1. Check 'pendingRecycle' requestType
this.logger.info(`Check "pendingRecycle" status on vehicle: ${permno}`)
const resRequestType = await this.findAllWithPermno(permno)
if (!requestType || resRequestType.length == 0) {
this.logger.error(
`Could not find any requestType for vehicle's number: ${permno} in database`,
)
errors.operation = 'Checking vehicle status'
errors.message = `Citizen has not accepted to recycle the vehicle.`
return errors
} else {
if (
!['pendingRecycle', 'handOver'].includes(
resRequestType[0]['dataValues']['requestType'],
)
) {
this.logger.error(
`Lastest requestType of vehicle's number ${permno} is not 'pendingRecycle' but is: ${resRequestType[0]['dataValues']['requestType']}`,
)
errors.operation = 'Checking vehicle status'
errors.message = `Citizen has not accepted to recycle the vehicle.`
return errors
}
}
// 2. Update requestType to 'handOver'
try {
this.logger.info(
`create requestType: handOver for ${permno} for partnerId: ${partnerId}`,
)
const req = new RecyclingRequestModel()
req.vehicleId = newRecyclingRequest.vehicleId
req.nameOfRequestor = newRecyclingRequest.nameOfRequestor
req.requestType = 'handOver'
req.recyclingPartnerId = newRecyclingRequest.recyclingPartnerId
await req.save()
} catch (err) {
this.logger.error(
`Getting error while inserting requestType 'handOver' for vehicle's number: ${permno} in database with error: ${err}`,
)
errors.operation = 'handOver'
errors.message = `Could not start deregistered process. Please try again later.`
return errors
}
// 3. deregistered vehicle from Samgongustofa
try {
this.logger.info(
`start deregistered vehicle ${permno} for partnerId: ${partnerId}`,
)
// partnerId 000 is Rafræn afskráning in Samgongustofa's system
// Samgongustofa wants to use it ('000') instead of Recycling partnerId for testing
await this.deRegisterVehicle(permno, partnerId)
} catch (err) {
this.logger.error(
`Getting error while deregistered vehicle: ${permno} on Samgongustofa with error: ${err}`,
)
// Saved requestType back to 'pendingRecycle'
const req = new RecyclingRequestModel()
req.vehicleId = newRecyclingRequest.vehicleId
req.nameOfRequestor = newRecyclingRequest.nameOfRequestor
req.requestType = 'pendingRecycle'
req.recyclingPartnerId = newRecyclingRequest.recyclingPartnerId
await req.save()
errors.operation = 'deregistered'
errors.message = `deregistered process failed. Please try again later.`
return errors
}
// 4. Update requestType to 'deregistered'
let getGuId = new RecyclingRequestModel()
try {
this.logger.info(
`create requestType: deregistered for ${permno} for partnerId: ${partnerId}`,
)
const req = new RecyclingRequestModel()
req.vehicleId = newRecyclingRequest.vehicleId
req.nameOfRequestor = newRecyclingRequest.nameOfRequestor
req.requestType = 'deregistered'
req.recyclingPartnerId = newRecyclingRequest.recyclingPartnerId
getGuId = await req.save()
} catch (err) {
// Log error and continue to payment
this.logger.error(
`Getting error while inserting requestType 'deregistered' for vehicle's number: ${permno} in database with error: ${err}`,
)
}
// 5. Call Fjarsysla for payment
try {
this.logger.info(
`start payment on vehicle ${permno} for partnerId: ${partnerId}`,
)
// Need to send vehicleOwner's nationalId on fjarsysla API
const vehicle = await this.vehicleService.findByVehicleId(permno)
if (!vehicle) {
this.logger.error(
`Could not find vehicleOwner's nationalId for vehicle's number: ${permno}`,
)
const req = new RecyclingRequestModel()
req.vehicleId = newRecyclingRequest.vehicleId
req.nameOfRequestor = newRecyclingRequest.nameOfRequestor
req.requestType = 'paymentFailed'
req.recyclingPartnerId = newRecyclingRequest.recyclingPartnerId
await req.save()
errors.operation = 'paymentFailed'
errors.message = `Vehicle has been successful deregistered but payment process failed. Please contact admin.`
return errors
}
let guid = `Skilagjald ökutækis: ${permno}`
if (getGuId?.id) {
guid = getGuId.id
}
await this.fjarsyslaService.getFjarsysluRest(
vehicle.ownerNationalId,
permno,
guid,
)
} catch (err) {
this.logger.error(
`Getting error while calling payment process for vehicle's number: ${permno} in database with error: ${err}`,
)
const req = new RecyclingRequestModel()
req.vehicleId = newRecyclingRequest.vehicleId
req.nameOfRequestor = newRecyclingRequest.nameOfRequestor
req.requestType = 'paymentFailed'
req.recyclingPartnerId = newRecyclingRequest.recyclingPartnerId
await req.save()
errors.operation = 'paymentFailed'
errors.message = `Vehicle has been successful deregistered but payment process failed. Please contact admin.`
return errors
}
// 6. Update requestType to 'paymentInitiated'
try {
this.logger.info(
`create requestType: paymentInitiated for ${permno} for partnerId: ${partnerId}`,
)
const req = new RecyclingRequestModel()
req.vehicleId = newRecyclingRequest.vehicleId
req.nameOfRequestor = newRecyclingRequest.nameOfRequestor
req.requestType = 'paymentInitiated'
req.recyclingPartnerId = newRecyclingRequest.recyclingPartnerId
await req.save()
} catch (err) {
this.logger.error(
`Getting error while inserting requestType 'paymentInitiated' for vehicle's number: ${permno} in database with error: ${err}`,
)
}
}
// requestType: 'pendingRecycle' or 'cancelled'
else {
this.logger.info(`create requestType: ${requestType} for ${permno}`)
await newRecyclingRequest.save()
}
const status = new RequestStatus()
status.status = true
this.logger.info(
`---- Finsihed update requestType for ${permno} to requestType: ${requestType} ----`,
)
return status
} catch (err) {
this.logger.error(
`Getting error while creating createRecyclingRquest for requestType: ${requestType}, permno: ${permno}, nameOfRequestor: ${nameOfRequestor}, partnerId: ${partnerId} with: ${err}`,
)
errors.operation = 'general'
errors.message = `Something went wrong. Please try again later.`
return errors
}
}
} | the_stack |
import 'chrome://resources/cr_elements/hidden_style_css.m.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js';
import '../appearance_page/appearance_page.js';
import '../privacy_page/privacy_page.js';
import '../privacy_page/privacy_review_promo.js';
import '../safety_check_page/safety_check_page.js';
import '../autofill_page/autofill_page.js';
import '../controls/settings_idle_load.js';
import '../on_startup_page/on_startup_page.js';
import '../people_page/people_page.js';
import '../reset_page/reset_profile_banner.js';
import '../search_page/search_page.js';
import '../settings_page/settings_section.js';
import '../settings_page_css.js';
// <if expr="chromeos_ash or chromeos_lacros">
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
// </if>
// <if expr="not chromeos and not lacros">
import '../default_browser_page/default_browser_page.js';
// </if>
import {assert} from 'chrome://resources/js/assert.m.js';
import {beforeNextRender, html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {SettingsIdleLoadElement} from '../controls/settings_idle_load.js';
import {loadTimeData} from '../i18n_setup.js';
import {PageVisibility} from '../page_visibility.js';
// <if expr="chromeos_ash or chromeos_lacros">
import {PrefsMixin, PrefsMixinInterface} from '../prefs/prefs_mixin.js';
// </if>
import {routes} from '../route.js';
import {Route, RouteObserverMixin, RouteObserverMixinInterface, Router} from '../router.js';
import {getSearchManager, SearchResult} from '../search_settings.js';
import {MainPageMixin, MainPageMixinInterface} from '../settings_page/main_page_mixin.js';
// <if expr="chromeos_ash or chromeos_lacros">
const OS_BANNER_INTERACTION_METRIC_NAME =
'ChromeOS.Settings.OsBannerInteraction';
/**
* These values are persisted to logs and should not be renumbered or re-used.
* See tools/metrics/histograms/enums.xml.
* @enum {number}
*/
const CrosSettingsOsBannerInteraction = {
NotShown: 0,
Shown: 1,
Clicked: 2,
Closed: 3,
};
// </if>
// TODO(crbug.com/1234307): Remove when RouteObserverMixin is converted to
// TypeScript.
type Constructor<T> = new (...args: any[]) => T;
// <if expr="chromeos_ash or chromeos_lacros">
const SettingsBasicPageElementBase =
PrefsMixin(MainPageMixin(
RouteObserverMixin(PolymerElement) as unknown as
Constructor<PolymerElement>)) as unknown as {
new (): PolymerElement & PrefsMixinInterface &
RouteObserverMixinInterface & MainPageMixinInterface
};
// </if>
// <if expr="not chromeos and not lacros">
const SettingsBasicPageElementBase = MainPageMixin(
RouteObserverMixin(PolymerElement) as
unknown as
Constructor<PolymerElement>) as {
new (): PolymerElement & RouteObserverMixinInterface & MainPageMixinInterface
};
// </if>
export class SettingsBasicPageElement extends SettingsBasicPageElementBase {
static get is() {
return 'settings-basic-page';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/** Preferences state. */
prefs: {
type: Object,
notify: true,
},
/**
* Dictionary defining page visibility.
*/
pageVisibility: {
type: Object,
value() {
return {};
},
},
/**
* Whether a search operation is in progress or previous search
* results are being displayed.
*/
inSearchMode: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
advancedToggleExpanded: {
type: Boolean,
value: false,
notify: true,
observer: 'advancedToggleExpandedChanged_',
},
/**
* True if a section is fully expanded to hide other sections beneath it.
* False otherwise (even while animating a section open/closed).
*/
hasExpandedSection_: {
type: Boolean,
value: false,
},
/**
* True if the basic page should currently display the reset profile
* banner.
*/
showResetProfileBanner_: {
type: Boolean,
value() {
return loadTimeData.getBoolean('showResetProfileBanner');
},
},
// <if expr="chromeos_ash or chromeos_lacros">
showOSSettingsBanner_: {
type: Boolean,
computed: 'computeShowOSSettingsBanner_(' +
'prefs.settings.cros.show_os_banner.value, currentRoute_)',
},
// </if>
currentRoute_: Object,
/**
* Used to avoid handling a new toggle while currently toggling.
*/
advancedTogglingInProgress_: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
};
}
pageVisibility: PageVisibility;
inSearchMode: boolean;
advancedToggleExpanded: boolean;
private hasExpandedSection_: boolean;
private showResetProfileBanner_: boolean;
// <if expr="chromeos_ash or chromeos_lacros">
private showOSSettingsBanner_: boolean;
private osBannerShowMetricRecorded_: boolean = false;
// </if>
private currentRoute_: Route;
private advancedTogglingInProgress_: boolean;
ready() {
super.ready();
this.setAttribute('role', 'main');
this.addEventListener('subpage-expand', this.onSubpageExpanded_);
}
connectedCallback() {
super.connectedCallback();
this.currentRoute_ = Router.getInstance().getCurrentRoute();
}
currentRouteChanged(newRoute: Route, oldRoute?: Route) {
this.currentRoute_ = newRoute;
if (routes.ADVANCED && routes.ADVANCED.contains(newRoute)) {
this.advancedToggleExpanded = true;
}
if (oldRoute && oldRoute.isSubpage()) {
// If the new route isn't the same expanded section, reset
// hasExpandedSection_ for the next transition.
if (!newRoute.isSubpage() || newRoute.section !== oldRoute.section) {
this.hasExpandedSection_ = false;
}
} else {
assert(!this.hasExpandedSection_);
}
super.currentRouteChanged(newRoute, oldRoute);
}
/**
* Override MainPageMixin method.
*/
containsRoute(route: Route|null): boolean {
return !route || routes.BASIC.contains(route) ||
routes.ADVANCED.contains(route);
}
private showPage_(visibility?: boolean): boolean {
return visibility !== false;
}
private getIdleLoad_(): Promise<Element> {
return (this.shadowRoot!.querySelector('#advancedPageTemplate') as
SettingsIdleLoadElement)
.get();
}
private showPrivacyReviewPromo_(visibility: boolean|undefined): boolean {
// TODO(crbug/1215630): Only show on the first look at the privacy page.
return this.showPage_(visibility) &&
loadTimeData.getBoolean('privacyReviewEnabled');
}
/**
* Queues a task to search the basic sections, then another for the advanced
* sections.
* @param query The text to search for.
* @return A signal indicating that searching finished.
*/
searchContents(query: string): Promise<SearchResult> {
const whenSearchDone = [
getSearchManager().search(
query,
assert(this.shadowRoot!.querySelector('#basicPage') as HTMLElement)),
];
if (this.pageVisibility.advancedSettings !== false) {
whenSearchDone.push(this.getIdleLoad_().then(function(advancedPage) {
return getSearchManager().search(query, advancedPage);
}));
}
return Promise.all(whenSearchDone).then(function(requests) {
// Combine the SearchRequests results to a single SearchResult object.
return {
canceled: requests.some(function(r) {
return r.canceled;
}),
didFindMatches: requests.some(function(r) {
return r.didFindMatches();
}),
// All requests correspond to the same user query, so only need to check
// one of them.
wasClearSearch: requests[0].isSame(''),
};
});
}
// <if expr="chromeos_ash or chromeos_lacros">
private computeShowOSSettingsBanner_(): boolean|undefined {
// this.prefs is implicitly used by this.getPref() below.
if (!this.prefs || !this.currentRoute_) {
return;
}
const showPref = this.getPref('settings.cros.show_os_banner').value;
// Banner only shows on the main page because direct navigations to a
// sub-page are unlikely to be due to a user looking for an OS setting.
const show = showPref && !this.currentRoute_.isSubpage();
// Record the show metric once. We can't record the metric in attached()
// because prefs might not be ready yet.
if (!this.osBannerShowMetricRecorded_) {
chrome.metricsPrivate.recordEnumerationValue(
OS_BANNER_INTERACTION_METRIC_NAME,
show ? CrosSettingsOsBannerInteraction.Shown :
CrosSettingsOsBannerInteraction.NotShown,
Object.keys(CrosSettingsOsBannerInteraction).length);
this.osBannerShowMetricRecorded_ = true;
}
return show;
}
private onOSSettingsBannerClick_() {
// The label has a link that opens the page, so just record the metric.
chrome.metricsPrivate.recordEnumerationValue(
OS_BANNER_INTERACTION_METRIC_NAME,
CrosSettingsOsBannerInteraction.Clicked,
Object.keys(CrosSettingsOsBannerInteraction).length);
}
private onOSSettingsBannerClosed_() {
this.setPrefValue('settings.cros.show_os_banner', false);
chrome.metricsPrivate.recordEnumerationValue(
OS_BANNER_INTERACTION_METRIC_NAME,
CrosSettingsOsBannerInteraction.Closed,
Object.keys(CrosSettingsOsBannerInteraction).length);
}
// </if>
// <if expr="chromeos">
private onOpenChromeOSLanguagesSettingsClick_() {
const chromeOSLanguagesSettingsPath =
loadTimeData.getString('chromeOSLanguagesSettingsPath');
window.location.href =
`chrome://os-settings/${chromeOSLanguagesSettingsPath}`;
}
// </if>
private onResetProfileBannerClosed_() {
this.showResetProfileBanner_ = false;
}
/**
* Hides everything but the newly expanded subpage.
*/
private onSubpageExpanded_() {
this.hasExpandedSection_ = true;
}
/**
* Render the advanced page now (don't wait for idle).
*/
private advancedToggleExpandedChanged_() {
if (!this.advancedToggleExpanded) {
return;
}
// In Polymer2, async() does not wait long enough for layout to complete.
// beforeNextRender() must be used instead.
beforeNextRender(this, () => {
this.getIdleLoad_();
});
}
private fire_(eventName: string, detail: any) {
this.dispatchEvent(
new CustomEvent(eventName, {bubbles: true, composed: true, detail}));
}
/**
* @return Whether to show the basic page, taking into account both routing
* and search state.
*/
private showBasicPage_(
currentRoute: Route, _inSearchMode: boolean,
hasExpandedSection: boolean): boolean {
return !hasExpandedSection || routes.BASIC.contains(currentRoute);
}
/**
* @return Whether to show the advanced page, taking into account both routing
* and search state.
*/
private showAdvancedPage_(
currentRoute: Route, inSearchMode: boolean, hasExpandedSection: boolean,
advancedToggleExpanded: boolean): boolean {
return hasExpandedSection ?
(routes.ADVANCED && routes.ADVANCED.contains(currentRoute)) :
advancedToggleExpanded || inSearchMode;
}
private showAdvancedSettings_(visibility?: boolean): boolean {
return visibility !== false;
}
}
declare global {
interface HTMLElementTagNameMap {
'settings-basic-page': SettingsBasicPageElement;
}
}
customElements.define(SettingsBasicPageElement.is, SettingsBasicPageElement); | the_stack |
import * as React from "react";
import { PBRMaterial } from "babylonjs";
import { Inspector, IObjectInspectorProps } from "../../components/inspector";
import { InspectorList } from "../../gui/inspector/fields/list";
import { InspectorColor } from "../../gui/inspector/fields/color";
import { InspectorNumber } from "../../gui/inspector/fields/number";
import { InspectorBoolean } from "../../gui/inspector/fields/boolean";
import { InspectorSection } from "../../gui/inspector/fields/section";
import { InspectorVector2 } from "../../gui/inspector/fields/vector2";
import { InspectorColorPicker } from "../../gui/inspector/fields/color-picker";
import { MaterialInspector } from "./material-inspector";
export interface IPBRMaterialInspectorState {
/**
* Defines wether or not the material is using the metallic workflow.
*/
useMetallic: boolean;
/**
* Defines wether or not the material is using the roughness workflow.
*/
useRoughness: boolean;
/**
* Defines wether or not clear coat is enabled.
*/
clearCoatEnabled: boolean;
/**
* Defines wether or not anisotropy is enabled.
*/
anisotropyEnabled: boolean;
/**
* Defines wether or not sheen is enabled.
*/
sheenEnabled: boolean;
/**
* Defines wether or not roughness is used by sheen.
*/
useSheenRoughness: boolean;
/**
* Defines wether or not sub surface translucency is enabled.
*/
subSurfaceTranslucencyEnabled: boolean;
/**
* Defines wether or not sub surface refaction is enabled.
*/
subSurfaceRefractionEnabled: boolean;
}
export class PBRMaterialInspector extends MaterialInspector<PBRMaterial, IPBRMaterialInspectorState> {
/**
* Constructor.
* @param props defines the component's props.
*/
public constructor(props: IObjectInspectorProps) {
super(props);
this.state = {
useMetallic: (this.material.metallic ?? null) !== null,
useRoughness: (this.material.roughness ?? null) !== null,
clearCoatEnabled: this.material.clearCoat.isEnabled,
anisotropyEnabled: this.material.anisotropy.isEnabled,
sheenEnabled: this.material.sheen.isEnabled,
useSheenRoughness: (this.material.sheen.roughness ?? null) !== null,
subSurfaceTranslucencyEnabled: this.material.subSurface.isTranslucencyEnabled,
subSurfaceRefractionEnabled: this.material.subSurface.isRefractionEnabled,
};
}
/**
* Renders the content of the inspector.
*/
public renderContent(): React.ReactNode {
return (
<>
{super.renderContent()}
{this.getMaterialFlagsInspector()}
{this.getAdvancedOptionsInspector()}
{this.getMapsInspector()}
<InspectorSection title="Options">
<InspectorBoolean object={this.material} property="usePhysicalLightFalloff" label= "Use Physical Light Falloff" />
<InspectorBoolean object={this.material} property="forceIrradianceInFragment" label= "Force Irradiance In Fragment" />
</InspectorSection>
<InspectorSection title="Albedo">
<InspectorBoolean object={this.material} property="useAlphaFromAlbedoTexture" label= "Use Alpha From Albedo Texture" />
<InspectorColor object={this.material} property="albedoColor" label="Color" step={0.01} />
<InspectorColorPicker object={this.material} property="albedoColor" label="Hex Color" />
</InspectorSection>
<InspectorSection title="Bump">
{this._getBumpTextureLevelInspector()}
<InspectorBoolean object={this.material} property="invertNormalMapX" label= "Invert Normal Map X" />
<InspectorBoolean object={this.material} property="invertNormalMapY" label= "Invert Normal Map Y" />
<InspectorBoolean object={this.material} property="useParallax" label= "Use Parallax" />
<InspectorBoolean object={this.material} property="useParallaxOcclusion" label= "Use Parallax Occlusion" />
<InspectorNumber object={this.material} property="parallaxScaleBias" label="Parallax Scale Bias" step={0.001} />
</InspectorSection>
<InspectorSection title="Reflectivity">
<InspectorBoolean object={this.material} property="enableSpecularAntiAliasing" label= "Enable Specular Anti-Aliasing" />
<InspectorBoolean object={this.material} property="useSpecularOverAlpha" label= "Use Specular Over Alpha" />
<InspectorColor object={this.material} property="reflectivityColor" label="Color" step={0.01} />
<InspectorColorPicker object={this.material} property="reflectivityColor" label="Hex Color" />
</InspectorSection>
<InspectorSection title="Reflection">
<InspectorNumber object={this.material} property="environmentIntensity" label="Environment Intensity" step={0.01} />
<InspectorColor object={this.material} property="reflectionColor" label="Color" step={0.01} />
<InspectorColorPicker object={this.material} property="reflectionColor" label="Hex Color" />
</InspectorSection>
<InspectorSection title="Ambient">
<InspectorBoolean object={this.material} property="useAmbientInGrayScale" label= "Use Ambient In Gray Scale" />
<InspectorBoolean object={this.material} property="useAmbientOcclusionFromMetallicTextureRed" label= "Use Ambient Occlusion From Metallic Texture Red" />
<InspectorNumber object={this.material} property="ambientTextureStrength" label="Strength" step={0.01} />
<InspectorColor object={this.material} property="ambientColor" label="Color" step={0.01} />
<InspectorColorPicker object={this.material} property="ambientColor" label="Hex Color" />
</InspectorSection>
<InspectorSection title="Micro Surface (Glossiness)">
<InspectorNumber object={this.material} property="microSurface" label="Micro Surface" min={0} max={1} step={0.01} />
<InspectorBoolean object={this.material} property="useAutoMicroSurfaceFromReflectivityMap" label= "Use Auto Micro Surface From Reflectivity Map" />
<InspectorBoolean object={this.material} property="useMicroSurfaceFromReflectivityMapAlpha" label= "Use Micro Surface From Reflectivity Map Alpha" />
</InspectorSection>
<InspectorSection title="Metallic / Roughness">
<InspectorBoolean object={this.material} property="useMetallnessFromMetallicTextureBlue" label= "Use Metallness From Metallic Texture Blue" />
<InspectorBoolean object={this.material} property="useRoughnessFromMetallicTextureAlpha" label= "Use Roughness From Metallic Texture Alpha" />
<InspectorBoolean object={this.material} property="useRoughnessFromMetallicTextureGreen" label= "Use Roughness From Metallic Texture Green" />
<InspectorNumber object={this.material} property="indexOfRefraction" label= "Index Of Refraction" min={1} max={3} step={0.01} />
<InspectorNumber object={this.material} property="metallicF0Factor" label= "Metallic F0 Factor" min={0} max={1} step={0.01} />
{this._getMetallicWorkflowInspector()}
{this._getRoughnessWorkflowInspector()}
</InspectorSection>
<InspectorSection title="Emissive">
<InspectorColor object={this.material} property="emissiveColor" label="Color" step={0.01} />
<InspectorColorPicker object={this.material} property="emissiveColor" label="Hex Color" />
</InspectorSection>
<InspectorSection title="BRDF">
<InspectorBoolean object={this.material.brdf} property="useEnergyConservation" label="Use Energy Conservation" />
<InspectorBoolean object={this.material.brdf} property="useSpecularGlossinessInputEnergyConservation" label="Use Specular Glossiness Input Energy Conservation" />
</InspectorSection>
{this._getClearCoatInspector()}
{this._getAnisotropyInspector()}
{this._getSheenInspector()}
{this._getSubSurfaceInspector()}
</>
);
}
/**
* Returns the inspector used to set the textures of the standard material.
*/
protected getMapsInspector(): React.ReactNode {
return (
<InspectorSection title="Maps">
<InspectorList object={this.material} property="albedoTexture" label="Albedo Texture" items={() => this.getTexturesList()} />
<InspectorList object={this.material} property="bumpTexture" label="Bump Texture" items={() => this.getTexturesList()} />
<InspectorList object={this.material} property="reflectivityTexture" label="Reflectivity Texture" items={() => this.getTexturesList()} />
<InspectorList object={this.material} property="reflectionTexture" label="Reflection Texture" items={() => this.getTexturesList()} />
<InspectorList object={this.material} property="ambientTexture" label="Ambient Texture" items={() => this.getTexturesList()} />
<InspectorList object={this.material} property="microSurfaceTexture" label="Micro Surface Texture" items={() => this.getTexturesList()} />
<InspectorList object={this.material} property="metallicTexture" label="Metallic Texture" items={() => this.getTexturesList()} />
<InspectorList object={this.material} property="opacityTexture" label="Opacity Texture" items={() => this.getTexturesList()} />
<InspectorList object={this.material} property="emissiveTexture" label="Emissive Texture" items={() => this.getTexturesList()} />
<InspectorList object={this.material} property="lightmapTexture" label="Lightmap Texture" items={() => this.getTexturesList()} />
</InspectorSection>
);
}
/**
* Returns the inspector used to control the bump texture strength/level.
*/
private _getBumpTextureLevelInspector(): React.ReactNode {
return this.material.bumpTexture ? (
<InspectorNumber object={this.material.bumpTexture} property="level" label="Strength" step={0.01} />
) : undefined;
}
/**
* Returns the metallic workflow inspector used to configure the metallic properties of the
* PBR material.
*/
private _getMetallicWorkflowInspector(): React.ReactNode {
if (!this.state.useMetallic) {
return (
<InspectorSection title="Metallic">
<InspectorBoolean object={this.state} property="useMetallic" label="Use Metallic" onChange={(v) => {
this.material.metallic = 0;
this.setState({ useMetallic: v });
}} />
</InspectorSection>
);
}
return (
<InspectorSection title="Metallic">
<InspectorBoolean object={this.state} property="useMetallic" label="Use Metallic" onChange={(v) => {
this.material.metallic = null;
this.setState({ useMetallic: v });
}} />
<InspectorNumber object={this.material} property="metallic" label="Metallic" min={0} max={1} step={0.01} />
</InspectorSection>
);
}
/**
* Returns the roughness workflow inspector used to configure the roughness properties of the
* PBR material.
*/
private _getRoughnessWorkflowInspector(): React.ReactNode {
if (!this.state.useRoughness) {
return (
<InspectorSection title="Roughness">
<InspectorBoolean object={this.state} property="useRoughness" label="Use Roughness" onChange={(v) => {
this.material.roughness = 0;
this.setState({ useRoughness: v });
}} />
</InspectorSection>
);
}
return (
<InspectorSection title="Roughness">
<InspectorBoolean object={this.state} property="useRoughness" label="Use Roughness" onChange={(v) => {
this.material.roughness = null;
this.setState({ useRoughness: v });
}} />
<InspectorNumber object={this.material} property="roughness" label="Roughness" min={0} max={1} step={0.01} />
</InspectorSection>
);
}
/**
* Returns the clear coat inspector used to configure the clear coat values
* of the PBR material.
*/
private _getClearCoatInspector(): React.ReactNode {
if (!this.state.clearCoatEnabled) {
return (
<InspectorSection title="Clear Coat">
<InspectorBoolean object={this.material.clearCoat} property="isEnabled" label= "Enabled" onChange={(v) => this.setState({ clearCoatEnabled: v })} />
</InspectorSection>
);
}
return (
<InspectorSection title="Clear Coat">
<InspectorBoolean object={this.material.clearCoat} property="isEnabled" label="Enabled" onChange={(v) => this.setState({ clearCoatEnabled: v })} />
<InspectorNumber object={this.material.clearCoat} property="intensity" label="Intensity" step={0.01} />
<InspectorNumber object={this.material.clearCoat} property="roughness" label="Roughness" step={0.01} />
<InspectorNumber object={this.material.clearCoat} property="indexOfRefraction" label="Index Of Refraction" step={0.01} />
<InspectorSection title="Textures">
<InspectorList object={this.material.clearCoat} property="texture" label="Texture" items={() => this.getTexturesList()} />
<InspectorList object={this.material.clearCoat} property="bumpTexture" label="Bump Texture" items={() => this.getTexturesList()} />
</InspectorSection>
<InspectorSection title="Tint">
<InspectorBoolean object={this.material.clearCoat} property="isTintEnabled" label="Enabled" />
<InspectorNumber object={this.material.clearCoat} property="tintColorAtDistance" label="Color At Distance" step={0.01} />
<InspectorNumber object={this.material.clearCoat} property="tintThickness" label="Thickness" step={0.01} />
</InspectorSection>
</InspectorSection>
);
}
/**
* Returns the anisotropy inspector used to configure the anisotropy values
* of the PBR material.
*/
private _getAnisotropyInspector(): React.ReactNode {
if (!this.state.anisotropyEnabled) {
return (
<InspectorSection title="Anisotropy">
<InspectorBoolean object={this.material.anisotropy} property="isEnabled" label= "Enabled" onChange={(v) => this.setState({ anisotropyEnabled: v })} />
</InspectorSection>
);
}
return (
<InspectorSection title="Anisotropy">
<InspectorBoolean object={this.material.anisotropy} property="isEnabled" label= "Enabled" onChange={(v) => this.setState({ anisotropyEnabled: v })} />
<InspectorList object={this.material.anisotropy} property="texture" label="Texture" items={() => this.getTexturesList()} />
<InspectorNumber object={this.material.anisotropy} property="intensity" label="Intensity" step={0.01} />
<InspectorVector2 object={this.material.anisotropy} property="direction" label="Direction" step={0.01} />
</InspectorSection>
);
}
/**
* Returns the sheen inspector used to configure the sheen values
* of the PBR material.
*/
private _getSheenInspector(): React.ReactNode {
if (!this.state.sheenEnabled) {
return (
<InspectorSection title="Sheen">
<InspectorBoolean object={this.material.sheen} property="isEnabled" label= "Enabled" onChange={(v) => this.setState({ sheenEnabled: v })} />
</InspectorSection>
);
}
return (
<InspectorSection title="Sheen">
<InspectorBoolean object={this.material.sheen} property="isEnabled" label= "Enabled" onChange={(v) => this.setState({ sheenEnabled: v })} />
<InspectorList object={this.material.sheen} property="texture" label="Texture" items={() => this.getTexturesList()} />
<InspectorBoolean object={this.material.sheen} property="linkSheenWithAlbedo" label= "Link Sheen With Albedo" />
<InspectorBoolean object={this.material.sheen} property="albedoScaling" label= "Albedo Scaling" />
<InspectorBoolean object={this.material.sheen} property="useRoughnessFromMainTexture" label= "Use Roughness From Main Texture" />
{this._getSheenRoughnessInspector()}
<InspectorNumber object={this.material.sheen} property="intensity" label="Intensity" step={0.01} />
<InspectorColor object={this.material.sheen} property="color" label="Color" step={0.01} />
</InspectorSection>
);
}
/**
* Returns the roughness inspector to edit the roughness values of the sheen
* PBR material.
*/
private _getSheenRoughnessInspector(): React.ReactNode {
if (!this.state.useSheenRoughness) {
return (
<InspectorSection title="Roughness">
<InspectorBoolean object={this.state} property="useSheenRoughness" label="Enabled" onChange={(v) => {
this.material.sheen.roughness = 0;
this.setState({ useSheenRoughness: v });
}} />
</InspectorSection>
);
}
return (
<InspectorSection title="Roughness">
<InspectorBoolean object={this.state} property="useSheenRoughness" label="Enabled" onChange={(v) => {
this.material.sheen.roughness = null;
this.setState({ useSheenRoughness: v });
}} />
<InspectorList object={this.material.sheen} property="textureRoughness" label="Roughness" items={() => this.getTexturesList()} />
<InspectorNumber object={this.material.sheen} property="roughness" label="Roughness" step={0.01} />
</InspectorSection>
);
}
/**
* Returns the inspector used to
*/
private _getSubSurfaceInspector(): React.ReactNode {
const translucencyInspector = this._getSubSurfaceTranslucencyInspector();
const refractionInspector = this._getSubSurfaceRefractionInspector();
if (this.state.subSurfaceTranslucencyEnabled || this.state.subSurfaceRefractionEnabled) {
return (
<InspectorSection title="Sub Surface">
<InspectorList object={this.material.subSurface} property="thicknessTexture" label="Thickness Texture" items={() => this.getTexturesList()} />
<InspectorList object={this.material.subSurface} property="refractionTexture" label="Refraction Texture" items={() => this.getTexturesList()} />
<InspectorColor object={this.material.subSurface} property="tintColor" label="Tint Color" step={0.01} />
<InspectorColorPicker object={this.material.subSurface} property="tintColor" label="Hex Color" />
<InspectorBoolean object={this.material.subSurface} property="useMaskFromThicknessTexture" label="Use Mask From Thickness Texture" />
{translucencyInspector}
{refractionInspector}
</InspectorSection>
);
}
return (
<InspectorSection title="Sub Surface">
{translucencyInspector}
{refractionInspector}
</InspectorSection>
);
}
/**
* Returns the inspector used to configure the sub surface translucency propeties
* of the PBR material.
*/
private _getSubSurfaceTranslucencyInspector(): React.ReactNode {
if (!this.state.subSurfaceTranslucencyEnabled) {
return (
<InspectorSection title="Translucency">
<InspectorBoolean object={this.state} property="subSurfaceTranslucencyEnabled" label="Enabled" onChange={(v) => {
this.material.subSurface.isTranslucencyEnabled = true;
this.setState({ subSurfaceTranslucencyEnabled: v });
}} />
</InspectorSection>
);
}
return (
<InspectorSection title="Translucency">
<InspectorBoolean object={this.state} property="subSurfaceTranslucencyEnabled" label="Enabled" onChange={(v) => {
this.material.subSurface.isTranslucencyEnabled = false;
this.setState({ subSurfaceTranslucencyEnabled: v });
}} />
<InspectorNumber object={this.material.subSurface} property="translucencyIntensity" label="Intensity" step={0.01} />
</InspectorSection>
);
}
/**
* Returns the inspector used to configure the sub surface refraction properties
* of the PBR material.
*/
private _getSubSurfaceRefractionInspector(): React.ReactNode {
if (!this.state.subSurfaceRefractionEnabled) {
return (
<InspectorSection title="Refraction">
<InspectorBoolean object={this.state} property="subSurfaceRefractionEnabled" label="Enabled" onChange={(v) => {
this.material.subSurface.isRefractionEnabled = true;
this.setState({ subSurfaceRefractionEnabled: v });
}} />
</InspectorSection>
);
}
return (
<InspectorSection title="Refraction">
<InspectorBoolean object={this.state} property="subSurfaceRefractionEnabled" label="Enabled" onChange={(v) => {
this.material.subSurface.isRefractionEnabled = false;
this.setState({ subSurfaceRefractionEnabled: v });
}} />
<InspectorNumber object={this.material.subSurface} property="indexOfRefraction" label="Index Of Refraction" step={0.01} />
</InspectorSection>
);
}
}
Inspector.RegisterObjectInspector({
ctor: PBRMaterialInspector,
ctorNames: ["PBRMaterial"],
title: "PBR",
isSupported: (o) => MaterialInspector.IsObjectSupported(o, PBRMaterial),
}); | the_stack |
import React, { KeyboardEvent } from 'react'
import { DEFAULT_EXTERNAL_DATE_FORMAT, INTERNAL_DATE_FORMAT } from './constants'
/**
* This file contains the USWDS DatePicker date manipulation functions converted to TypeScript
*/
/**
* Keep date within month. Month would only be over by 1 to 3 days
*
* @param {Date} dateToCheck the date object to check
* @param {number} month the correct month
* @returns {Date} the date, corrected if needed
*/
export const keepDateWithinMonth = (dateToCheck: Date, month: number): Date => {
if (month !== dateToCheck.getMonth()) {
dateToCheck.setDate(0)
}
return dateToCheck
}
/**
* Set date from month day year
*
* @param {number} year the year to set
* @param {number} month the month to set (zero-indexed)
* @param {number} date the date to set
* @returns {Date} the set date
*/
export const setDate = (year: number, month: number, date: number): Date => {
const newDate = new Date(0)
newDate.setFullYear(year, month, date)
return newDate
}
/**
* todays date
*
* @returns {Date} todays date
*/
export const today = (): Date => {
const newDate = new Date()
const day = newDate.getDate()
const month = newDate.getMonth()
const year = newDate.getFullYear()
return setDate(year, month, day)
}
/**
* Set date to first day of the month
*
* @param {Date} date the date to adjust
* @returns {Date} the adjusted date
*/
export const startOfMonth = (date: Date): Date => {
const newDate = new Date(0)
newDate.setFullYear(date.getFullYear(), date.getMonth(), 1)
return newDate
}
/**
* Set date to last day of the month
*
* @param {number} date the date to adjust
* @returns {Date} the adjusted date
*/
export const lastDayOfMonth = (date: Date): Date => {
const newDate = new Date(0)
newDate.setFullYear(date.getFullYear(), date.getMonth() + 1, 0)
return newDate
}
/**
* Add days to date
*
* @param {Date} _date the date to adjust
* @param {number} numDays the difference in days
* @returns {Date} the adjusted date
*/
export const addDays = (date: Date, numDays: number): Date => {
const newDate = new Date(date.getTime())
newDate.setDate(newDate.getDate() + numDays)
return newDate
}
/**
* Subtract days from date
*
* @param {Date} _date the date to adjust
* @param {number} numDays the difference in days
* @returns {Date} the adjusted date
*/
export const subDays = (date: Date, numDays: number): Date =>
addDays(date, -numDays)
/**
* Add weeks to date
*
* @param {Date} _date the date to adjust
* @param {number} numWeeks the difference in weeks
* @returns {Date} the adjusted date
*/
export const addWeeks = (date: Date, numWeeks: number): Date =>
addDays(date, numWeeks * 7)
/**
* Subtract weeks from date
*
* @param {Date} _date the date to adjust
* @param {number} numWeeks the difference in weeks
* @returns {Date} the adjusted date
*/
export const subWeeks = (date: Date, numWeeks: number): Date =>
addWeeks(date, -numWeeks)
/**
* Set date to the start of the week (Sunday)
*
* @param {Date} _date the date to adjust
* @returns {Date} the adjusted date
*/
export const startOfWeek = (date: Date): Date => {
const dayOfWeek = date.getDay()
return subDays(date, dayOfWeek)
}
/**
* Set date to the end of the week (Saturday)
*
* @param {Date} _date the date to adjust
* @param {number} numWeeks the difference in weeks
* @returns {Date} the adjusted date
*/
export const endOfWeek = (date: Date): Date => {
const dayOfWeek = date.getDay()
return addDays(date, 6 - dayOfWeek)
}
/**
* Add months to date and keep date within month
*
* @param {Date} _date the date to adjust
* @param {number} numMonths the difference in months
* @returns {Date} the adjusted date
*/
export const addMonths = (date: Date, numMonths: number): Date => {
const newDate = new Date(date.getTime())
const dateMonth = (newDate.getMonth() + 12 + numMonths) % 12
newDate.setMonth(newDate.getMonth() + numMonths)
keepDateWithinMonth(newDate, dateMonth)
return newDate
}
/**
* Subtract months from date
*
* @param {Date} _date the date to adjust
* @param {number} numMonths the difference in months
* @returns {Date} the adjusted date
*/
export const subMonths = (date: Date, numMonths: number): Date =>
addMonths(date, -numMonths)
/**
* Add years to date and keep date within month
*
* @param {Date} _date the date to adjust
* @param {number} numYears the difference in years
* @returns {Date} the adjusted date
*/
export const addYears = (date: Date, numYears: number): Date =>
addMonths(date, numYears * 12)
/**
* Subtract years from date
*
* @param {Date} _date the date to adjust
* @param {number} numYears the difference in years
* @returns {Date} the adjusted date
*/
export const subYears = (date: Date, numYears: number): Date =>
addYears(date, -numYears)
/**
* Set months of date
*
* @param {Date} _date the date to adjust
* @param {number} month zero-indexed month to set
* @returns {Date} the adjusted date
*/
export const setMonth = (date: Date, month: number): Date => {
const newDate = new Date(date.getTime())
newDate.setMonth(month)
keepDateWithinMonth(newDate, month)
return newDate
}
/**
* Set year of date
*
* @param {Date} _date the date to adjust
* @param {number} year the year to set
* @returns {Date} the adjusted date
*/
export const setYear = (date: Date, year: number): Date => {
const newDate = new Date(date.getTime())
const month = newDate.getMonth()
newDate.setFullYear(year)
keepDateWithinMonth(newDate, month)
return newDate
}
/**
* Return the earliest date
*
* @param {Date} dateA date to compare
* @param {Date} dateB date to compare
* @returns {Date} the earliest date
*/
export const min = (dateA: Date, dateB: Date): Date => {
let newDate = dateA
if (dateB < dateA) {
newDate = dateB
}
return new Date(newDate.getTime())
}
/**
* Return the latest date
*
* @param {Date} dateA date to compare
* @param {Date} dateB date to compare
* @returns {Date} the latest date
*/
export const max = (dateA: Date, dateB: Date): Date => {
let newDate = dateA
if (dateB > dateA) {
newDate = dateB
}
return new Date(newDate.getTime())
}
/**
* Check if dates are the in the same year
*
* @param {Date} dateA date to compare
* @param {Date} dateB date to compare
* @returns {boolean} are dates in the same year
*/
export const isSameYear = (dateA: Date, dateB: Date): boolean => {
return dateA && dateB && dateA.getFullYear() === dateB.getFullYear()
}
/**
* Check if dates are the in the same month
*
* @param {Date} dateA date to compare
* @param {Date} dateB date to compare
* @returns {boolean} are dates in the same month
*/
export const isSameMonth = (dateA: Date, dateB: Date): boolean => {
return isSameYear(dateA, dateB) && dateA.getMonth() === dateB.getMonth()
}
/**
* Check if dates are the same date
*
* @param {Date} dateA the date to compare
* @param {Date} dateA the date to compare
* @returns {boolean} are dates the same date
*/
export const isSameDay = (dateA: Date, dateB: Date): boolean => {
return isSameMonth(dateA, dateB) && dateA.getDate() === dateB.getDate()
}
/**
* return a new date within minimum and maximum date
*
* @param {Date} date date to check
* @param {Date} minDate minimum date to allow
* @param {Date} maxDate maximum date to allow
* @returns {Date} the date between min and max
*/
export const keepDateBetweenMinAndMax = (
date: Date,
minDate: Date,
maxDate?: Date
): Date => {
let newDate = date
if (date < minDate) {
newDate = minDate
} else if (maxDate && date > maxDate) {
newDate = maxDate
}
return new Date(newDate.getTime())
}
/**
* Check if dates is valid.
*
* @param {Date} date date to check
* @param {Date} minDate minimum date to allow
* @param {Date} maxDate maximum date to allow
* @return {boolean} is there a day within the month within min and max dates
*/
export const isDateWithinMinAndMax = (
date: Date,
minDate: Date,
maxDate?: Date
): boolean => date >= minDate && (!maxDate || date <= maxDate)
/**
* Check if dates month is invalid.
*
* @param {Date} date date to check
* @param {Date} minDate minimum date to allow
* @param {Date} maxDate maximum date to allow
* @return {boolean} is the month outside min or max dates
*/
export const isDatesMonthOutsideMinOrMax = (
date: Date,
minDate: Date,
maxDate?: Date
): boolean => {
return (
lastDayOfMonth(date) < minDate ||
(!!maxDate && startOfMonth(date) > maxDate)
)
}
/**
* Check if dates year is invalid.
*
* @param {Date} date date to check
* @param {Date} minDate minimum date to allow
* @param {Date} maxDate maximum date to allow
* @return {boolean} is the month outside min or max dates
*/
export const isDatesYearOutsideMinOrMax = (
date: Date,
minDate: Date,
maxDate?: Date
): boolean => {
return (
lastDayOfMonth(setMonth(date, 11)) < minDate ||
(!!maxDate && startOfMonth(setMonth(date, 0)) > maxDate)
)
}
/**
* Parse a date with format M-D-YY
*
* @param {string} dateString the date string to parse
* @param {string} dateFormat the format of the date string
* @param {boolean} adjustDate should the date be adjusted
* @returns {Date} the parsed date
*/
export const parseDateString = (
dateString: string,
dateFormat: string = INTERNAL_DATE_FORMAT,
adjustDate = false
): Date | undefined => {
let date
let month
let day
let year
let parsed
if (dateString) {
let monthStr, dayStr, yearStr
if (dateFormat === DEFAULT_EXTERNAL_DATE_FORMAT) {
;[monthStr, dayStr, yearStr] = dateString.split('/')
} else {
;[yearStr, monthStr, dayStr] = dateString.split('-')
}
if (yearStr) {
parsed = parseInt(yearStr, 10)
if (!Number.isNaN(parsed)) {
year = parsed
if (adjustDate) {
year = Math.max(0, year)
if (yearStr.length < 3) {
const currentYear = today().getFullYear()
const currentYearStub =
currentYear - (currentYear % 10 ** yearStr.length)
year = currentYearStub + parsed
}
}
}
}
if (monthStr) {
parsed = parseInt(monthStr, 10)
if (!Number.isNaN(parsed)) {
month = parsed
if (adjustDate) {
month = Math.max(1, month)
month = Math.min(12, month)
}
}
}
if (month && dayStr && year != null) {
parsed = parseInt(dayStr, 10)
if (!Number.isNaN(parsed)) {
day = parsed
if (adjustDate) {
const lastDayOfMonth = setDate(year, month, 0).getDate()
day = Math.max(1, day)
day = Math.min(lastDayOfMonth, day)
}
}
}
if (month && day && year != null) {
date = setDate(year, month - 1, day)
}
}
return date
}
/**
* Format a date to format YYYY-MM-DD
*
* @param {Date} date the date to format
* @param {string} dateFormat the format of the date string
* @returns {string} the formatted date string
*/
export const formatDate = (
date: Date,
dateFormat: string = INTERNAL_DATE_FORMAT
): string => {
const padZeros = (value: number, length: number): string => {
return `0000${value}`.slice(-length)
}
const month = date.getMonth() + 1
const day = date.getDate()
const year = date.getFullYear()
if (dateFormat === DEFAULT_EXTERNAL_DATE_FORMAT) {
return [padZeros(month, 2), padZeros(day, 2), padZeros(year, 4)].join('/')
}
return [padZeros(year, 4), padZeros(month, 2), padZeros(day, 2)].join('-')
}
// VALIDATION
export const isDateInvalid = (
dateString: string,
minDate: Date,
maxDate?: Date
): boolean => {
let isInvalid = false
if (dateString) {
isInvalid = true
const dateStringParts = dateString.split('/')
const [month, day, year] = dateStringParts.map((str) => {
let value
const parsed = parseInt(str, 10)
if (!Number.isNaN(parsed)) value = parsed
return value
})
if (month && day && year != null) {
const checkDate = setDate(year, month - 1, day)
if (
checkDate.getMonth() === month - 1 &&
checkDate.getDate() === day &&
checkDate.getFullYear() === year &&
dateStringParts[2].length === 4 &&
isDateWithinMinAndMax(checkDate, minDate, maxDate)
) {
isInvalid = false
}
}
}
return isInvalid
}
// RENDERING TABLES
export const listToTable = (
list: React.ReactNode[],
rowSize: number
): React.ReactFragment => {
const rows = []
let i = 0
while (i < list.length) {
const row = []
while (i < list.length && row.length < rowSize) {
row.push(list[parseInt(`${i}`)])
i += 1
}
rows.push(row)
}
return (
<>
{rows.map((r, rIndex) => (
<tr key={`row_${rIndex}`}>
{r.map((cell, cIndex) => (
<td key={`row_${rIndex}_cell_${cIndex}`}>{cell}</td>
))}
</tr>
))}
</>
)
}
export const handleTabKey = (
event: KeyboardEvent,
focusableEl: Array<HTMLButtonElement | null>
): void => {
if (event.key === 'Tab') {
const focusable = focusableEl.filter((el) => el && !el.disabled)
const activeElement = document?.activeElement
const firstTabIndex = 0
const lastTabIndex = focusable.length - 1
const firstTabStop = focusable[parseInt(`${firstTabIndex}`)]
const lastTabStop = focusable[parseInt(`${lastTabIndex}`)]
const focusIndex =
activeElement instanceof HTMLButtonElement
? focusable.indexOf(activeElement)
: -1
const isLastTab = focusIndex === lastTabIndex
const isFirstTab = focusIndex === firstTabIndex
const isNotFound = focusIndex === -1
if (event.shiftKey) {
// Tab backwards
if (isFirstTab || isNotFound) {
event.preventDefault()
lastTabStop?.focus()
}
} else {
// Tab forwards
if (isLastTab || isNotFound) {
event.preventDefault()
firstTabStop?.focus()
}
}
}
}
// iOS detection from: http://stackoverflow.com/a/9039885/177710
export const isIosDevice = (): boolean =>
typeof navigator !== 'undefined' &&
(navigator.userAgent.match(/(iPod|iPhone|iPad)/g) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&
!window.MSStream | the_stack |
declare const WhereSymbol: unique symbol;
declare const UpdateDataSymbol: unique symbol;
interface ReadOnlyAttribute {
readonly readOnly: true;
}
interface RequiredAttribute {
readonly required: true;
}
interface HiddenAttribute {
readonly hidden: true;
}
interface DefaultedAttribute {
readonly default: any;
}
type NestedBooleanAttribute = {
readonly type: "boolean";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: boolean, item: any) => boolean | undefined | void;
readonly set?: (val?: boolean, item?: any) => boolean | undefined | void;
readonly default?: boolean | (() => boolean);
readonly validate?: ((val: boolean) => boolean) | ((val: boolean) => void) | ((val: boolean) => string | void);
readonly field?: string;
}
type BooleanAttribute = {
readonly type: "boolean";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: boolean, item: any) => boolean | undefined | void;
readonly set?: (val?: boolean, item?: any) => boolean | undefined | void;
readonly default?: boolean | (() => boolean);
readonly validate?: ((val: boolean) => boolean) | ((val: boolean) => void) | ((val: boolean) => string | void);
readonly field?: string;
readonly label?: string;
readonly watch?: ReadonlyArray<string> | "*";
}
type NestedNumberAttribute = {
readonly type: "number";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: number, item: any) => number | undefined | void;
readonly set?: (val?: number, item?: any) => number | undefined | void;
readonly default?: number | (() => number);
readonly validate?: ((val: number) => boolean) | ((val: number) => void) | ((val: number) => string | void);
readonly field?: string;
}
type NumberAttribute = {
readonly type: "number";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: number, item: any) => number | undefined | void;
readonly set?: (val?: number, item?: any) => number | undefined | void;
readonly default?: number | (() => number);
readonly validate?: ((val: number) => boolean) | ((val: number) => void) | ((val: number) => string | void);
readonly field?: string;
readonly label?: string;
readonly watch?: ReadonlyArray<string> | "*";
}
type NestedStringAttribute = {
readonly type: "string";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: string, item: any) => string | undefined | void;
readonly set?: (val?: string, item?: any) => string | undefined | void;
readonly default?: string | (() => string);
readonly validate?: ((val: string) => boolean) | ((val: string) => void) | ((val: string) => string | void) | RegExp;
readonly field?: string;
}
type StringAttribute = {
readonly type: "string";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: string, item: any) => string | undefined | void;
readonly set?: (val?: string, item?: any) => string | undefined | void;
readonly default?: string | (() => string);
readonly validate?: ((val: string) => boolean) | ((val: string) => void) | ((val: string) => string | void) | RegExp;
readonly field?: string;
readonly label?: string;
readonly watch?: ReadonlyArray<string> | "*";
}
type NestedEnumAttribute = {
readonly type: ReadonlyArray<string>;
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: any, item: any) => any | undefined | void;
readonly set?: (val?: any, item?: any) => any | undefined | void;
readonly default?: string | (() => string);
readonly validate?: ((val: any) => boolean) | ((val: any) => void) | ((val: any) => string | void);
readonly field?: string;
readonly label?: string;
}
type EnumAttribute = {
readonly type: ReadonlyArray<string>;
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: any, item: any) => any | undefined | void;
readonly set?: (val?: any, item?: any) => any | undefined | void;
readonly default?: string | (() => string);
readonly validate?: ((val: any) => boolean) | ((val: any) => void) | ((val: any) => string | void);
readonly field?: string;
readonly label?: string;
readonly watch?: ReadonlyArray<string> | "*";
}
type NestedAnyAttribute = {
readonly type: "any";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: any, item: any) => any | undefined | void;
readonly set?: (val?: any, item?: any) => any | undefined | void;
readonly default?: any | (() => any);
readonly validate?: ((val: any) => boolean) | ((val: any) => void) | ((val: any) => string | void);
readonly field?: string;
}
type AnyAttribute = {
readonly type: "any";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: any, item: any) => any | undefined | void;
readonly set?: (val?: any, item?: any) => any | undefined | void;
readonly default?: any | (() => any);
readonly validate?: ((val: any) => boolean) | ((val: any) => void) | ((val: any) => string | void);
readonly field?: string;
readonly label?: string;
readonly watch?: ReadonlyArray<string> | "*";
}
type NestedMapAttribute = {
readonly type: "map";
readonly properties: {
readonly [name: string]: NestedAttributes;
};
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: Record<string, any>, item: any) => Record<string, any> | undefined | void;
readonly set?: (val?: Record<string, any>, item?: any) => Record<string, any> | undefined | void;
readonly default?: Record<string, any> | (() => Record<string, any>);
readonly validate?: ((val: Record<string, any>) => boolean) | ((val: Record<string, any>) => void) | ((val: Record<string, any>) => string | void);
readonly field?: string;
}
type MapAttribute = {
readonly type: "map";
readonly properties: {
readonly [name: string]: NestedAttributes;
};
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: Record<string, any>, item: any) => Record<string, any> | undefined | void;
readonly set?: (val?: Record<string, any>, item?: any) => Record<string, any> | undefined | void;
readonly default?: Record<string, any> | (() => Record<string, any>);
readonly validate?: ((val: Record<string, any>) => boolean) | ((val: Record<string, any>) => void) | ((val: Record<string, any>) => string | void);
readonly field?: string;
readonly watch?: ReadonlyArray<string> | "*";
}
type NestedStringListAttribute = {
readonly type: "list";
readonly items: {
readonly type: "string";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: string, item: any) => string | undefined | void;
readonly set?: (val?: string, item?: any) => string | undefined | void;
readonly default?: string | (() => string);
readonly validate?: ((val: string) => boolean) | ((val: string) => void) | ((val: string) => string | void) | RegExp;
readonly field?: string;
};
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: Array<string>, item: any) => Array<string> | undefined | void;
readonly set?: (val?: Array<string>, item?: any) => Array<string> | undefined | void;
readonly default?: Array<string> | (() => Array<string>);
readonly validate?: ((val: Array<string>) => boolean) | ((val: Array<string>) => void) | ((val: Array<string>) => string | void);
}
type StringListAttribute = {
readonly type: "list";
readonly items: {
readonly type: "string";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: string, item: any) => string | undefined | void;
readonly set?: (val?: string, item?: any) => string | undefined | void;
readonly default?: string | (() => string);
readonly validate?: ((val: string) => boolean) | ((val: string) => void) | ((val: string) => string | void) | RegExp;
readonly field?: string;
}
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: Array<string>, item: any) => Array<string> | undefined | void;
readonly set?: (val?: Array<string>, item?: any) => Array<string> | undefined | void;
readonly default?: Array<string> | (() => Array<string>);
readonly validate?: ((val: Array<string>) => boolean) | ((val: Array<string>) => void) | ((val: Array<string>) => string | void);
readonly watch?: ReadonlyArray<string> | "*";
}
type NestedNumberListAttribute = {
readonly type: "list";
readonly items: NestedNumberAttribute;
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: Array<number>, item: any) => Array<number> | undefined | void;
readonly set?: (val?: Array<number>, item?: any) => Array<number> | undefined | void;
readonly default?: Array<number> | (() => Array<number>);
readonly validate?: ((val: Array<number>) => boolean) | ((val: Array<number>) => void) | ((val: Array<number>) => string | void);
readonly field?: string;
}
type NumberListAttribute = {
readonly type: "list";
readonly items: NestedNumberAttribute;
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: Array<number>, item: any) => Array<number> | undefined | void;
readonly set?: (val?: Array<number>, item?: any) => Array<number> | undefined | void;
readonly default?: Array<number> | (() => Array<number>);
readonly validate?: ((val: Array<number>) => boolean) | ((val: Array<number>) => void) | ((val: Array<number>) => string | void);
readonly field?: string;
readonly watch?: ReadonlyArray<string> | "*";
}
type NestedMapListAttribute = {
readonly type: "list";
readonly items: NestedMapAttribute;
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: Record<string, any>[], item: any) => Record<string, any>[] | undefined | void;
readonly set?: (val?: Record<string, any>[], item?: any) => Record<string, any>[] | undefined | void;
readonly default?: Record<string, any>[] | (() => Record<string, any>[]);
readonly validate?: ((val: Record<string, any>[]) => boolean) | ((val: Record<string, any>[]) => void) | ((val: Record<string, any>[]) => string | void);
readonly field?: string;
}
type MapListAttribute = {
readonly type: "list";
readonly items: NestedMapAttribute;
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: Record<string, any>[], item: any) => Record<string, any>[] | undefined | void;
readonly set?: (val?: Record<string, any>[], item?: any) => Record<string, any>[] | undefined | void;
readonly default?: Record<string, any>[] | (() => Record<string, any>[]);
readonly validate?: ((val: Record<string, any>[]) => boolean) | ((val: Record<string, any>[]) => void) | ((val: Record<string, any>[]) => string | void);
readonly field?: string;
readonly watch?: ReadonlyArray<string> | "*";
}
type NestedStringSetAttribute = {
readonly type: "set";
readonly items: "string";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: Array<string>, item: any) => Array<string> | undefined | void;
readonly set?: (val?: Array<string>, item?: any) => Array<string> | undefined | void;
readonly default?: Array<string> | (() => Array<string>);
readonly validate?: ((val: Array<string>) => boolean) | ((val: Array<string>) => void) | ((val: Array<string>) => string | void) | RegExp;
readonly field?: string;
}
type StringSetAttribute = {
readonly type: "set";
readonly items: "string";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: Array<string>, item: any) => Array<string> | undefined | void;
readonly set?: (val?: Array<string>, item?: any) => Array<string> | undefined | void;
readonly default?: Array<string> | (() => Array<string>);
readonly validate?: ((val: Array<string>) => boolean) | ((val: Array<string>) => void) | ((val: Array<string>) => string | void) | RegExp;
readonly field?: string;
readonly watch?: ReadonlyArray<string> | "*";
}
type NestedNumberSetAttribute = {
readonly type: "set";
readonly items: "number";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: Array<number>, item: any) => Array<number> | undefined | void;
readonly set?: (val?: Array<number>, item?: any) => Array<number> | undefined | void;
readonly default?: Array<number> | (() => Array<number>);
readonly validate?: ((val: Array<number>) => boolean) | ((val: Array<number>) => void) | ((val: Array<number>) => string | void);
readonly field?: string;
}
type NumberSetAttribute = {
readonly type: "set";
readonly items: "number";
readonly required?: boolean;
readonly hidden?: boolean;
readonly readOnly?: boolean;
readonly get?: (val: Array<number>, item: any) => Array<number> | undefined | void;
readonly set?: (val?: Array<number>, item?: any) => Array<number> | undefined | void;
readonly default?: Array<number> | (() => Array<number>);
readonly validate?: ((val: Array<number>) => boolean) | ((val: Array<number>) => void) | ((val: Array<number>) => string | void);
readonly field?: string;
readonly watch?: ReadonlyArray<string> | "*";
}
type Attribute =
BooleanAttribute
| NumberAttribute
| StringAttribute
| EnumAttribute
| AnyAttribute
| MapAttribute
| StringSetAttribute
| NumberSetAttribute
| StringListAttribute
| NumberListAttribute
| MapListAttribute;
type NestedAttributes =
NestedBooleanAttribute
| NestedNumberAttribute
| NestedStringAttribute
| NestedAnyAttribute
| NestedMapAttribute
| NestedStringListAttribute
| NestedNumberListAttribute
| NestedMapListAttribute
| NestedStringSetAttribute
| NestedNumberSetAttribute
| NestedEnumAttribute
type Attributes<A extends string> = {
readonly [a in A]: Attribute
}
type SecondaryIndex = {
readonly index: string;
readonly pk: {
readonly field: string;
readonly composite: ReadonlyArray<string>;
readonly template?: string;
}
readonly sk?: {
readonly field: string;
readonly composite: ReadonlyArray<string>;
readonly template?: string;
}
}
type IndexWithSortKey = {
readonly sk: {
readonly field: string;
readonly composite: ReadonlyArray<string>;
readonly template?: string;
}
}
type AccessPatternCollection<C extends string> = C | ReadonlyArray<C>;
type Schema<A extends string, F extends A, C extends string> = {
readonly model: {
readonly entity: string;
readonly service: string;
readonly version: string;
}
readonly attributes: {
readonly [a in A]: Attribute
};
readonly indexes: {
[accessPattern: string]: {
readonly index?: string;
readonly collection?: C | ReadonlyArray<C>;
readonly pk: {
readonly casing?: "upper" | "lower" | "none" | "default";
readonly field: string;
readonly composite: ReadonlyArray<F>;
readonly template?: string;
}
readonly sk?: {
readonly casing?: "upper" | "lower" | "none" | "default";
readonly field: string;
readonly composite: ReadonlyArray<F>;
readonly template?: string;
}
}
}
};
type IndexCollections<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = {
[i in keyof S["indexes"]]: S["indexes"][i]["collection"] extends
AccessPatternCollection<infer Name>
? Name
: never
}[keyof S["indexes"]];
type EntityCollections<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = {
[N in IndexCollections<A,F,C,S>]: {
[i in keyof S["indexes"]]: S["indexes"][i]["collection"] extends AccessPatternCollection<infer Name>
? Name extends N
? i
: never
: never
}[keyof S["indexes"]];
}
type ItemAttribute<A extends Attribute> =
A["type"] extends infer R
? R extends "string" ? string
: R extends "number" ? number
: R extends "boolean" ? boolean
: R extends ReadonlyArray<infer E> ? E
: R extends "map"
? "properties" extends keyof A
? {
[P in keyof A["properties"]]:
A["properties"][P] extends infer M
? M extends Attribute
? ItemAttribute<M>
: never
: never
}
: never
: R extends "list"
? "items" extends keyof A
? A["items"] extends infer I
? I extends Attribute
? Array<ItemAttribute<I>>
: never
: never
: never
: R extends "set"
? "items" extends keyof A
? A["items"] extends infer I
? I extends "string" ? string[]
: I extends "number" ? number[]
: never
: never
: never
: R extends "any" ? any
: never
: never
type ReturnedAttribute<A extends Attribute> =
A extends HiddenAttribute ? never
: A["type"] extends infer R
? R extends "string" ? string
: R extends "number" ? number
: R extends "boolean" ? boolean
: R extends ReadonlyArray<infer E> ? E
: R extends "map"
? "properties" extends keyof A
?
TrimmedAttributes<{
[P in keyof A["properties"]]: A["properties"][P] extends infer M
? M extends Attribute
? M extends RequiredAttribute | DefaultedAttribute
? ReturnedAttribute<M>
: ReturnedAttribute<M> | undefined
: never
: never
}>
: never
: R extends "list"
? "items" extends keyof A
? A["items"] extends infer I
? I extends Attribute
? ReturnedAttribute<I>[]
: never
: never
: never
: R extends "set"
? "items" extends keyof A
? A["items"] extends infer I
? I extends "string" ? string[]
: I extends "number" ? number[]
: never
: never
: never
: R extends "any" ? any
: never
: never
type UndefinedKeys<T> = {
[P in keyof T]: undefined extends T[P] ? P: never
}[keyof T]
type TrimmedAttributes<A extends Attributes<any>> =
Partial<Pick<A, UndefinedKeys<A>>> & Omit<A, UndefinedKeys<A>>
type CreatedAttribute<A extends Attribute> =
A["type"] extends infer R
? R extends "string" ? string
: R extends "number" ? number
: R extends "boolean" ? boolean
: R extends ReadonlyArray<infer E> ? E
: R extends "map"
? "properties" extends keyof A
? TrimmedAttributes<{
[P in keyof A["properties"]]: A["properties"][P] extends infer M
? M extends Attribute
? M extends DefaultedAttribute
? CreatedAttribute<M> | undefined
: M extends RequiredAttribute
? CreatedAttribute<M>
: CreatedAttribute<M> | undefined
: never
: never
}>
: never
: R extends "list"
? "items" extends keyof A
? A["items"] extends infer I
? I extends Attribute
? CreatedAttribute<I>[]
: never
: never
: never
: R extends "set"
? "items" extends keyof A
? A["items"] extends infer I
? I extends "string" ? string[]
: I extends "number" ? number[]
: never
: never
: never
: R extends "any" ? any
: never
: never
type ReturnedItem<A extends string, F extends A, C extends string, S extends Schema<A,F,C>,Attr extends S["attributes"]> = {
[a in keyof Attr]: ReturnedAttribute<Attr[a]>
}
type CreatedItem<A extends string, F extends A, C extends string, S extends Schema<A,F,C>,Attr extends S["attributes"]> = {
[a in keyof Attr]: CreatedAttribute<Attr[a]>
}
type EditableItemAttribute<A extends Attribute> =
A extends ReadOnlyAttribute
? never
: A["type"] extends infer R
? R extends "string" ? string
: R extends "number" ? number
: R extends "boolean" ? boolean
: R extends ReadonlyArray<infer E> ? E
: R extends "map"
? "properties" extends keyof A
? TrimmedAttributes<{
[P in keyof A["properties"]]:
A["properties"][P] extends infer M
? M extends Attribute
? EditableItemAttribute<M>
: never
: never
}>
: never
: R extends "list"
? "items" extends keyof A
? A["items"] extends infer I
? I extends Attribute
? Array<EditableItemAttribute<I>>
: never
: never
: never
: R extends "set"
? "items" extends keyof A
? A["items"] extends infer I
? I extends "string" ? string[]
: I extends "number" ? number[]
: never
: never
: never
: R extends "any" ? any
: never
: never
type UpdatableItemAttribute<A extends Attribute> =
A extends ReadOnlyAttribute
? never
: A["type"] extends infer R
? R extends "string" ? string
: R extends "number" ? number
: R extends "boolean" ? boolean
: R extends ReadonlyArray<infer E> ? E
: R extends "map"
? "properties" extends keyof A
? {
[P in keyof A["properties"]]?:
A["properties"][P] extends infer M
? M extends Attribute
? UpdatableItemAttribute<M>
: never
: never
}
: never
: R extends "list"
? "items" extends keyof A
? A["items"] extends infer I
? I extends Attribute
? Array<UpdatableItemAttribute<I>>
: never
: never
: never
: R extends "set"
? "items" extends keyof A
? A["items"] extends infer I
? I extends "string" ? string[]
: I extends "number" ? number[]
: never
: never
: never
: R extends "any" ? any
: never
: never
type RemovableItemAttribute<A extends Attribute> =
A extends ReadOnlyAttribute | RequiredAttribute
? never
: A["type"] extends infer R
? R extends "string" ? string
: R extends "number" ? number
: R extends "boolean" ? boolean
: R extends ReadonlyArray<infer E> ? E
: R extends "map"
? "properties" extends keyof A
? {
[P in keyof A["properties"]]?:
A["properties"][P] extends infer M
? M extends Attribute
? UpdatableItemAttribute<M>
: never
: never
}
: never
: R extends "list"
? "items" extends keyof A
? A["items"] extends infer I
? I extends Attribute
? Array<UpdatableItemAttribute<I>>
: never
: never
: never
: R extends "set"
? "items" extends keyof A
? A["items"] extends infer I
? I extends "string" ? string[]
: I extends "number" ? number[]
: never
: never
: never
: R extends "any" ? any
: never
: never
type Item<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, Attr extends Attributes<A>> = {
[a in keyof Attr]: ItemAttribute<Attr[a]>
}
type ItemTypeDescription<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = {
[a in keyof S["attributes"]]: S["attributes"][a]["type"] extends infer R
? R
: never
}
type RequiredAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = ExtractKeysOfValueType<{
[a in keyof S["attributes"]]: S["attributes"][a]["required"] extends infer R
? R extends true ? true
: false
: never;
}, true>
type HiddenAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = ExtractKeysOfValueType<{
[a in keyof S["attributes"]]: S["attributes"][a]["hidden"] extends infer R
? R extends true
? true
: false
: never;
}, true>
type ReadOnlyAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = ExtractKeysOfValueType<{
[a in keyof S["attributes"]]: S["attributes"][a]["readOnly"] extends infer R
? R extends true
? true
: false
: never;
}, true>
type ExtractKeysOfValueType<T, K> = {
[I in keyof T]: T[I] extends K ? I : never
}[keyof T];
type TableIndexes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = {
[i in keyof S["indexes"]]: S["indexes"][i] extends infer I
? I extends SecondaryIndex
? "secondary"
: "table"
: never;
};
type TableIndexName<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = ExtractKeysOfValueType<TableIndexes<A,F,C,S>, "table">;
type PKCompositeAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = {
[i in keyof S["indexes"]]: S["indexes"][i]["pk"]["composite"][number];
}
type SKCompositeAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = {
[i in keyof S["indexes"]]: S["indexes"][i] extends IndexWithSortKey
? S["indexes"][i]["sk"]["composite"][number]
: never;
}
type TableIndexPKCompositeAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = Pick<PKCompositeAttributes<A,F,C,S>, TableIndexName<A,F,C,S>>;
type TableIndexSKCompositeAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = Pick<SKCompositeAttributes<A,F,C,S>, TableIndexName<A,F,C,S>>;
type IndexPKCompositeAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends keyof S["indexes"]> = Pick<PKCompositeAttributes<A,F,C,S>,I>;
type IndexSKCompositeAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends keyof S["indexes"]> = Pick<SKCompositeAttributes<A,F,C,S>,I>;
type TableIndexPKAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = Pick<Item<A,F,C,S,S["attributes"]>, TableIndexPKCompositeAttributes<A,F,C,S>[TableIndexName<A,F,C,S>]>;
type TableIndexSKAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = TableIndexSKCompositeAttributes<A,F,C,S>[TableIndexName<A,F,C,S>] extends keyof S["attributes"]
? Pick<Item<A,F,C,S,S["attributes"]>, TableIndexSKCompositeAttributes<A,F,C,S>[TableIndexName<A,F,C,S>]>
: Item<A,F,C,S,S["attributes"]>;
type IndexPKAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends keyof S["indexes"]> = Pick<Item<A,F,C,S,S["attributes"]>, IndexPKCompositeAttributes<A,F,C,S,I>[I]>;
type IndexSKAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends keyof S["indexes"]> = IndexSKCompositeAttributes<A,F,C,S,I>[I] extends keyof S["attributes"]
? Pick<Item<A,F,C,S,S["attributes"]>, IndexSKCompositeAttributes<A,F,C,S,I>[I]>
: Item<A,F,C,S,S["attributes"]>;
type TableIndexCompositeAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = TableIndexPKAttributes<A,F,C,S> & Partial<TableIndexSKAttributes<A,F,C,S>>;
type AllTableIndexCompositeAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = TableIndexPKAttributes<A,F,C,S> & TableIndexSKAttributes<A,F,C,S>;
type IndexCompositeAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends keyof S["indexes"]> = IndexPKAttributes<A,F,C,S,I> & Partial<IndexSKAttributes<A,F,C,S,I>>;
type TableItem<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> =
AllTableIndexCompositeAttributes<A,F,C,S> &
Pick<ReturnedItem<A,F,C,S,S["attributes"]>, RequiredAttributes<A,F,C,S>> &
Partial<Omit<ReturnedItem<A,F,C,S,S["attributes"]>, RequiredAttributes<A,F,C,S>>>
type ResponseItem<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> =
Omit<TableItem<A,F,C,S>, HiddenAttributes<A,F,C,S>>
type RequiredPutItems<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = {
[Attribute in keyof S["attributes"]]:
"default" extends keyof S["attributes"][Attribute]
? false
: "required" extends keyof S["attributes"][Attribute]
? true extends S["attributes"][Attribute]["required"]
? true
: Attribute extends keyof TableIndexCompositeAttributes<A,F,C,S>
? true
: false
: Attribute extends keyof TableIndexCompositeAttributes<A,F,C,S>
? true
: false
}
type PutItem<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> =
Pick<CreatedItem<A,F,C,S,S["attributes"]>, ExtractKeysOfValueType<RequiredPutItems<A,F,C,S>,true>>
& Partial<CreatedItem<A,F,C,S,S["attributes"]>>
type UpdateData<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> =
Omit<{
[Attr in keyof S["attributes"]]: EditableItemAttribute<S["attributes"][Attr]>
}, keyof AllTableIndexCompositeAttributes<A,F,C,S> | ReadOnlyAttributes<A,F,C,S>>
type SetItem<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> =
// UpdatableItemAttribute
Omit<{
[Attr in keyof S["attributes"]]?: UpdatableItemAttribute<S["attributes"][Attr]>
}, keyof AllTableIndexCompositeAttributes<A,F,C,S> | ReadOnlyAttributes<A,F,C,S>>
// type RemoveItem<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> =
// Array<keyof SetItem<A,F,C,S>>
type RemoveItem<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> =
Array< keyof Omit<{
[Attr in keyof S["attributes"]]?: RemovableItemAttribute<S["attributes"][Attr]>
}, keyof AllTableIndexCompositeAttributes<A,F,C,S> | ReadOnlyAttributes<A,F,C,S> | RequiredAttributes<A,F,C,S>>>
type AppendItem<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> =
Partial<{
[P in ExtractKeysOfValueType<ItemTypeDescription<A,F,C,S>, "list" | "any">]?: P extends keyof SetItem<A,F,C,S>
? SetItem<A,F,C,S>[P]
: never
}>
type AddItem<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> =
Partial<{
[P in ExtractKeysOfValueType<ItemTypeDescription<A,F,C,S>, "number" | "any" | "set">]?: P extends keyof SetItem<A,F,C,S>
? SetItem<A,F,C,S>[P]
: never
}>
type SubtractItem<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> =
Partial<{
[P in ExtractKeysOfValueType<ItemTypeDescription<A,F,C,S>, "number" | "any">]?: P extends keyof SetItem<A,F,C,S>
? SetItem<A,F,C,S>[P]
: never
}>
type DeleteItem<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> =
Partial<{
[P in ExtractKeysOfValueType<ItemTypeDescription<A,F,C,S>, "any" | "set">]?: P extends keyof SetItem<A,F,C,S>
? SetItem<A,F,C,S>[P]
: never
}>
export type WhereAttributeSymbol<T extends any> =
{ [WhereSymbol]: void }
& T extends string ? T
: T extends number ? T
: T extends boolean ? T
: T extends {[key: string]: any}
? {[key in keyof T]: WhereAttributeSymbol<T[key]>}
: T extends ReadonlyArray<infer A>
? ReadonlyArray<WhereAttributeSymbol<A>>
: T extends Array<infer I>
? Array<WhereAttributeSymbol<I>>
: T
type WhereAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends Item<A,F,C,S,S["attributes"]>> = {
[Attr in keyof I]: WhereAttributeSymbol<I[Attr]>
}
export type DataUpdateAttributeSymbol<T extends any> =
{ [UpdateDataSymbol]: void }
& T extends string ? T
: T extends number ? T
: T extends boolean ? T
: T extends {[key: string]: any}
? {[key in keyof T]: DataUpdateAttributeSymbol<T[key]>}
: T extends ReadonlyArray<infer A>
? ReadonlyArray<DataUpdateAttributeSymbol<A>>
: T extends Array<infer I>
? Array<DataUpdateAttributeSymbol<I>>
: [T] extends [never]
? never
: T
type DataUpdateAttributeValues<A extends DataUpdateAttributeSymbol<any>> =
A extends DataUpdateAttributeSymbol<infer T>
? T extends string ? T
: T extends number ? T
: T extends boolean ? T
: T extends {[key: string]: any}
? {[key in keyof T]?: DataUpdateAttributeValues<T[key]>}
: T extends ReadonlyArray<infer A> ? ReadonlyArray<DataUpdateAttributeValues<A>>
: T extends Array<infer I> ? Array<DataUpdateAttributeValues<I>>
: [T] extends [never]
? never
: T
: never
type DataUpdateAttributes<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends UpdateData<A,F,C,S>> = {
[Attr in keyof I]: DataUpdateAttributeSymbol<I[Attr]>
}
type WhereOperations<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends Item<A,F,C,S,S["attributes"]>> = {
eq: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
ne: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
gt: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
lt: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
gte: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
lte: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
between: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T, value2: T) => string;
begins: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
exists: <A extends WhereAttributeSymbol<any>>(attr: A) => string;
notExists: <A extends WhereAttributeSymbol<any>>(attr: A) => string;
contains: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
notContains: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
value: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: A extends WhereAttributeSymbol<infer V> ? V : never) => A extends WhereAttributeSymbol<infer V> ? V : never;
name: <A extends WhereAttributeSymbol<any>>(attr: A) => string;
};
type DataUpdateOperations<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends UpdateData<A,F,C,S>> = {
set: <T, A extends DataUpdateAttributeSymbol<T>>(attr: A, value: DataUpdateAttributeValues<A>) => any;
remove: <T, A extends DataUpdateAttributeSymbol<T>>(attr: [T] extends [never] ? never : A) => any;
append: <T, A extends DataUpdateAttributeSymbol<T>>(attr: A, value: DataUpdateAttributeValues<A> extends Array<any> ? DataUpdateAttributeValues<A> : never) => any;
add: <T, A extends DataUpdateAttributeSymbol<T>>(attr: A, value: A extends DataUpdateAttributeSymbol<infer V> ? V extends number | Array<any> ? V : [V] extends [any] ? V : never : never ) => any;
subtract: <T, A extends DataUpdateAttributeSymbol<T>>(attr: A, value: A extends DataUpdateAttributeSymbol<infer V> ? V extends number ? V : [V] extends [any] ? V : never : never ) => any;
delete: <T, A extends DataUpdateAttributeSymbol<T>>(attr: A, value: A extends DataUpdateAttributeSymbol<infer V> ? V extends Array<any> ? V : [V] extends [any] ? V : never : never ) => any;
del: <T, A extends DataUpdateAttributeSymbol<T>>(attr: A, value: A extends DataUpdateAttributeSymbol<infer V> ? V extends Array<any> ? V : never : never ) => any;
value: <T, A extends DataUpdateAttributeSymbol<T>>(attr: A, value: DataUpdateAttributeValues<A>) => Required<DataUpdateAttributeValues<A>>;
name: <T, A extends DataUpdateAttributeSymbol<T>>(attr: A) => any;
};
type WhereCallback<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends Item<A,F,C,S,S["attributes"]>> =
<W extends WhereAttributes<A,F,C,S,I>>(attributes: W, operations: WhereOperations<A,F,C,S,I>) => string;
type DataUpdateCallback<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends UpdateData<A,F,C,S>> =
<W extends DataUpdateAttributes<A,F,C,S,I>>(attributes: W, operations: DataUpdateOperations<A,F,C,S,I>) => any;
type ReturnValues = "default" | "none" | 'all_old' | 'updated_old' | 'all_new' | 'updated_new';
interface QueryOptions {
raw?: boolean;
table?: string;
limit?: number;
params?: object;
includeKeys?: boolean;
originalErr?: boolean;
ignoreOwnership?: boolean;
}
// subset of QueryOptions
interface ParseOptions {
ignoreOwnership?: boolean;
}
interface UpdateQueryOptions extends QueryOptions {
response?: "default" | "none" | 'all_old' | 'updated_old' | 'all_new' | 'updated_new';
}
interface DeleteQueryOptions extends QueryOptions {
response?: "default" | "none" | 'all_old';
}
interface PutQueryOptions extends QueryOptions {
response?: "default" | "none" | 'all_old';
}
interface ParamOptions {
params?: object;
table?: string;
limit?: number;
response?: "default" | "none" | 'all_old' | 'updated_old' | 'all_new' | 'updated_new';
}
interface PaginationOptions extends QueryOptions {
pager?: "raw" | "item" | "named";
limit?: number;
}
interface BulkOptions extends QueryOptions {
unprocessed?: "raw" | "item";
concurrency?: number;
}
type OptionalDefaultEntityIdentifiers = {
__edb_e__?: string;
__edb_v__?: string;
}
type GoRecord<ResponseType, Options = QueryOptions> = <T = ResponseType>(options?: Options) => Promise<T>;
type PageRecord<ResponseType, CompositeAttributes> = (page?: (CompositeAttributes & OptionalDefaultEntityIdentifiers) | null, options?: PaginationOptions) => Promise<[
(CompositeAttributes & OptionalDefaultEntityIdentifiers) | null,
ResponseType
]>;
type ParamRecord<Options = ParamOptions> = <P>(options?: Options) => P;
type RecordsActionOptions<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, Items, IndexCompositeAttributes> = {
go: GoRecord<Items>;
params: ParamRecord;
page: PageRecord<Items,IndexCompositeAttributes>;
where: WhereClause<A,F,C,S,Item<A,F,C,S,S["attributes"]>,RecordsActionOptions<A,F,C,S,Items,IndexCompositeAttributes>>;
}
type SingleRecordOperationOptions<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, ResponseType> = {
go: GoRecord<ResponseType, QueryOptions>;
params: ParamRecord<QueryOptions>;
where: WhereClause<A,F,C,S,Item<A,F,C,S,S["attributes"]>,SingleRecordOperationOptions<A,F,C,S,ResponseType>>;
};
type PutRecordOperationOptions<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, ResponseType> = {
go: GoRecord<ResponseType, PutQueryOptions>;
params: ParamRecord<PutQueryOptions>;
where: WhereClause<A,F,C,S,Item<A,F,C,S,S["attributes"]>,SingleRecordOperationOptions<A,F,C,S,ResponseType>>;
};
type DeleteRecordOperationOptions<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, ResponseType> = {
go: GoRecord<ResponseType, DeleteQueryOptions>;
params: ParamRecord<DeleteQueryOptions>;
where: WhereClause<A,F,C,S,Item<A,F,C,S,S["attributes"]>,DeleteRecordOperationOptions<A,F,C,S,ResponseType>>;
};
type BulkRecordOperationOptions<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, ResponseType> = {
go: GoRecord<ResponseType, BulkOptions>;
params: ParamRecord<BulkOptions>;
};
type SetRecordActionOptions<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, SetAttr,IndexCompositeAttributes,TableItem> = {
go: GoRecord<Partial<TableItem>, UpdateQueryOptions>;
params: ParamRecord<UpdateQueryOptions>;
set: SetRecord<A,F,C,S, SetItem<A,F,C,S>,IndexCompositeAttributes,TableItem>;
remove: SetRecord<A,F,C,S, Array<keyof SetItem<A,F,C,S>>,IndexCompositeAttributes,TableItem>;
add: SetRecord<A,F,C,S, AddItem<A,F,C,S>,IndexCompositeAttributes,TableItem>;
subtract: SetRecord<A,F,C,S, SubtractItem<A,F,C,S>,IndexCompositeAttributes,TableItem>;
append: SetRecord<A,F,C,S, AppendItem<A,F,C,S>,IndexCompositeAttributes,TableItem>;
delete: SetRecord<A,F,C,S, DeleteItem<A,F,C,S>,IndexCompositeAttributes,TableItem>;
data: DataUpdateMethodRecord<A,F,C,S, Item<A,F,C,S,S["attributes"]>,IndexCompositeAttributes,TableItem>;
where: WhereClause<A,F,C,S, Item<A,F,C,S,S["attributes"]>,RecordsActionOptions<A,F,C,S,TableItem,IndexCompositeAttributes>>;
}
type SetRecord<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, SetAttr, IndexCompositeAttributes, TableItem> = (properties: SetAttr) => SetRecordActionOptions<A,F,C,S, SetAttr, IndexCompositeAttributes, TableItem>;
type RemoveRecord<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, RemoveAttr, IndexCompositeAttributes, TableItem> = (properties: RemoveAttr) => SetRecordActionOptions<A,F,C,S, RemoveAttr, IndexCompositeAttributes, TableItem>;
type DataUpdateMethodRecord<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, SetAttr, IndexCompositeAttributes, TableItem> =
DataUpdateMethod<A,F,C,S, UpdateData<A,F,C,S>, SetRecordActionOptions<A,F,C,S, SetAttr, IndexCompositeAttributes, TableItem>>
type WhereClause<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends Item<A,F,C,S,S["attributes"]>, T> = (where: WhereCallback<A,F,C,S,I>) => T;
type DataUpdateMethod<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends UpdateData<A,F,C,S>, T> = (update: DataUpdateCallback<A,F,C,S,I>) => T;
type QueryOperations<A extends string, F extends A, C extends string, S extends Schema<A,F,C>, CompositeAttributes, TableItem, IndexCompositeAttributes> = {
between: (skCompositeAttributesStart: CompositeAttributes, skCompositeAttributesEnd: CompositeAttributes) => RecordsActionOptions<A,F,C,S, Array<TableItem>,IndexCompositeAttributes>;
gt: (skCompositeAttributes: CompositeAttributes) => RecordsActionOptions<A,F,C,S, Array<TableItem>,IndexCompositeAttributes>;
gte: (skCompositeAttributes: CompositeAttributes) => RecordsActionOptions<A,F,C,S, Array<TableItem>,IndexCompositeAttributes>;
lt: (skCompositeAttributes: CompositeAttributes) => RecordsActionOptions<A,F,C,S, Array<TableItem>,IndexCompositeAttributes>;
lte: (skCompositeAttributes: CompositeAttributes) => RecordsActionOptions<A,F,C,S, Array<TableItem>,IndexCompositeAttributes>;
begins: (skCompositeAttributes: CompositeAttributes) => RecordsActionOptions<A,F,C,S, Array<TableItem>,IndexCompositeAttributes>;
go: GoRecord<Array<TableItem>>;
params: ParamRecord;
page: PageRecord<Array<TableItem>,IndexCompositeAttributes>;
where: WhereClause<A,F,C,S,Item<A,F,C,S,S["attributes"]>,RecordsActionOptions<A,F,C,S,Array<TableItem>,IndexCompositeAttributes>>
}
type Queries<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> = {
[I in keyof S["indexes"]]: <CompositeAttributes extends IndexCompositeAttributes<A,F,C,S,I>>(composite: CompositeAttributes) =>
IndexSKAttributes<A,F,C,S,I> extends infer SK
// If there is no SK, dont show query operations (when an empty array is provided)
? [keyof SK] extends [never]
? RecordsActionOptions<A,F,C,S, ResponseItem<A,F,C,S>[], AllTableIndexCompositeAttributes<A,F,C,S> & Required<CompositeAttributes>>
// If there is no SK, dont show query operations (When no PK is specified)
: S["indexes"][I] extends IndexWithSortKey
? QueryOperations<
A,F,C,S,
// Omit the composite attributes already provided
Omit<Partial<IndexSKAttributes<A,F,C,S,I>>, keyof CompositeAttributes>,
ResponseItem<A,F,C,S>,
AllTableIndexCompositeAttributes<A,F,C,S> & Required<CompositeAttributes> & SK
>
: RecordsActionOptions<A,F,C,S, ResponseItem<A,F,C,S>[], AllTableIndexCompositeAttributes<A,F,C,S> & Required<CompositeAttributes> & SK>
: never
}
type DocumentClientMethod = (parameters: any) => {promise: () => Promise<any>};
type DocumentClient = {
get: DocumentClientMethod;
put: DocumentClientMethod;
delete: DocumentClientMethod;
update: DocumentClientMethod;
batchWrite: DocumentClientMethod;
batchGet: DocumentClientMethod;
scan: DocumentClientMethod;
}
type EntityConfiguration = {
table?: string;
client?: DocumentClient
};
type ServiceConfiguration = {
table?: string;
client?: DocumentClient
};
type ParseSingleInput = {
Item?: {[key: string]: any}
} | {
Attributes?: {[key: string]: any}
} | null
type ParseMultiInput = {
Items?: {[key: string]: any}[]
}
export class Entity<A extends string, F extends A, C extends string, S extends Schema<A,F,C>> {
readonly schema: S;
constructor(schema: S, config?: EntityConfiguration);
get(key: AllTableIndexCompositeAttributes<A,F,C,S>): SingleRecordOperationOptions<A,F,C,S, ResponseItem<A,F,C,S> | null>;
get(key: AllTableIndexCompositeAttributes<A,F,C,S>[]): BulkRecordOperationOptions<A,F,C,S, [AllTableIndexCompositeAttributes<A,F,C,S>[], ResponseItem<A,F,C,S>[]]>;
delete(key: AllTableIndexCompositeAttributes<A,F,C,S>): DeleteRecordOperationOptions<A,F,C,S, ResponseItem<A,F,C,S>>;
delete(key: AllTableIndexCompositeAttributes<A,F,C,S>[]): BulkRecordOperationOptions<A,F,C,S, AllTableIndexCompositeAttributes<A,F,C,S>[]>;
remove(key: AllTableIndexCompositeAttributes<A,F,C,S>): DeleteRecordOperationOptions<A,F,C,S, ResponseItem<A,F,C,S>>;
update(key: AllTableIndexCompositeAttributes<A,F,C,S>): {
set: SetRecord<A,F,C,S, SetItem<A,F,C,S>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
remove: RemoveRecord<A,F,C,S, RemoveItem<A,F,C,S>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
add: SetRecord<A,F,C,S, AddItem<A,F,C,S>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
subtract: SetRecord<A,F,C,S, SubtractItem<A,F,C,S>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
append: SetRecord<A,F,C,S, AppendItem<A,F,C,S>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
delete: SetRecord<A,F,C,S, DeleteItem<A,F,C,S>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
data: DataUpdateMethodRecord<A,F,C,S, Item<A,F,C,S,S["attributes"]>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
};
patch(key: AllTableIndexCompositeAttributes<A,F,C,S>): {
set: SetRecord<A,F,C,S, SetItem<A,F,C,S>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
remove: RemoveRecord<A,F,C,S, RemoveItem<A,F,C,S>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
add: SetRecord<A,F,C,S, AddItem<A,F,C,S>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
subtract: SetRecord<A,F,C,S, SubtractItem<A,F,C,S>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
append: SetRecord<A,F,C,S, AppendItem<A,F,C,S>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
delete: SetRecord<A,F,C,S, DeleteItem<A,F,C,S>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
data: DataUpdateMethodRecord<A,F,C,S, Item<A,F,C,S,S["attributes"]>, TableIndexCompositeAttributes<A,F,C,S>, ResponseItem<A,F,C,S>>;
};
put(record: PutItem<A,F,C,S>): PutRecordOperationOptions<A,F,C,S, ResponseItem<A,F,C,S>>;
put(record: PutItem<A,F,C,S>[]): BulkRecordOperationOptions<A,F,C,S, AllTableIndexCompositeAttributes<A,F,C,S>[]>;
create(record: PutItem<A,F,C,S>): PutRecordOperationOptions<A,F,C,S, ResponseItem<A,F,C,S>>;
find(record: Partial<Item<A,F,C,S,S["attributes"]>>): RecordsActionOptions<A,F,C,S, ResponseItem<A,F,C,S>[], AllTableIndexCompositeAttributes<A,F,C,S>>;
match(record: Partial<Item<A,F,C,S,S["attributes"]>>): RecordsActionOptions<A,F,C,S, ResponseItem<A,F,C,S>[], AllTableIndexCompositeAttributes<A,F,C,S>>;
scan: RecordsActionOptions<A,F,C,S, ResponseItem<A,F,C,S>[], TableIndexCompositeAttributes<A,F,C,S>>
query: Queries<A,F,C,S>;
parse(item: ParseSingleInput, options?: ParseOptions): ResponseItem<A,F,C,S> | null;
parse(item: ParseMultiInput, options?: ParseOptions): ResponseItem<A,F,C,S>[];
setIdentifier(type: "entity" | "version", value: string): void;
client: any;
}
type AllCollectionNames<E extends {[name: string]: Entity<any, any, any, any>}> = {
[Name in keyof E]:
E[Name] extends Entity<infer A, infer F, infer C, infer S>
? {
[Collection in keyof EntityCollections<A,F,C,S>]: Collection
}[keyof EntityCollections<A,F,C,S>]
: never
}[keyof E];
type AllEntityAttributeNames<E extends {[name: string]: Entity<any, any, any, any>}> = {
[Name in keyof E]: {
[A in keyof E[Name]["schema"]["attributes"]]: A
}[keyof E[Name]["schema"]["attributes"]]
}[keyof E];
type AllEntityAttributes<E extends {[name: string]: Entity<any, any, any, any>}> = {
[Attr in AllEntityAttributeNames<E>]: {
[Name in keyof E]: Attr extends keyof E[Name]["schema"]["attributes"]
? ItemAttribute<E[Name]["schema"]["attributes"][Attr]>
: never
}[keyof E];
};
type CollectionAssociations<E extends {[name: string]: Entity<any, any, any, any>}> = {
[Collection in AllCollectionNames<E>]: {
[Name in keyof E]: E[Name] extends Entity<infer A, infer F, infer C, infer S>
? Collection extends keyof EntityCollections<A,F,C,S>
? Name
: never
: never
}[keyof E];
}
type CollectionAttributes<E extends {[name: string]: Entity<any, any, any, any>}, Collections extends CollectionAssociations<E>> = {
[Collection in keyof Collections]: {
[EntityName in keyof E]: E[EntityName] extends Entity<infer A, infer F, infer C, infer S>
? EntityName extends Collections[Collection]
? keyof S["attributes"]
: never
: never
}[keyof E]
}
type CollectionWhereOperations = {
eq: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
ne: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
gt: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
lt: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
gte: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
lte: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
between: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T, value2: T) => string;
begins: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
exists: <T, A extends WhereAttributeSymbol<T>>(attr: A) => string;
notExists: <T, A extends WhereAttributeSymbol<T>>(attr: A) => string;
contains: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
notContains: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
value: <T, A extends WhereAttributeSymbol<T>>(attr: A, value: T) => string;
name: <T, A extends WhereAttributeSymbol<T>>(attr: A) => string;
}
type CollectionWhereCallback<E extends {[name: string]: Entity<any, any, any, any>}, I extends Partial<AllEntityAttributes<E>>> =
<W extends {[A in keyof I]: WhereAttributeSymbol<I[A]>}>(attributes: W, operations: CollectionWhereOperations) => string;
type CollectionWhereClause<E extends {[name: string]: Entity<any, any, any, any>}, A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends Partial<AllEntityAttributes<E>>, T> = (where: CollectionWhereCallback<E, I>) => T;
type WhereRecordsActionOptions<E extends {[name: string]: Entity<any, any, any, any>}, A extends string, F extends A, C extends string, S extends Schema<A,F,C>, I extends Partial<AllEntityAttributes<E>>, Items, IndexCompositeAttributes> = {
go: GoRecord<Items>;
params: ParamRecord;
page: PageRecord<Items,IndexCompositeAttributes>;
where: CollectionWhereClause<E,A,F,C,S,I, WhereRecordsActionOptions<E,A,F,C,S,I,Items,IndexCompositeAttributes>>;
}
type CollectionIndexKeys<Entities extends {[name: string]: Entity<any, any, any, any>}, Collections extends CollectionAssociations<Entities>> = {
[Collection in keyof Collections]: {
[EntityResultName in Collections[Collection]]:
EntityResultName extends keyof Entities
? Entities[EntityResultName] extends Entity<infer A, infer F, infer C, infer S>
? keyof TableIndexCompositeAttributes<A, F, C, S>
: never
: never
}[Collections[Collection]]
}
type CollectionPageKeys<Entities extends {[name: string]: Entity<any, any, any, any>}, Collections extends CollectionAssociations<Entities>> = {
[Collection in keyof Collections]: {
[EntityResultName in Collections[Collection]]:
EntityResultName extends keyof Entities
? Entities[EntityResultName] extends Entity<infer A, infer F, infer C, infer S>
? keyof Parameters<Entities[EntityResultName]["query"][
Collection extends keyof EntityCollections<A,F,C,S>
? EntityCollections<A,F,C,S>[Collection]
: never
]>[0]
: never
: never
}[Collections[Collection]]
}
type CollectionIndexAttributes<Entities extends {[name: string]: Entity<any, any, any, any>}, Collections extends CollectionAssociations<Entities>> = {
[Collection in keyof CollectionIndexKeys<Entities, Collections>]: {
[key in CollectionIndexKeys<Entities, Collections>[Collection]]:
key extends keyof AllEntityAttributes<Entities>
? AllEntityAttributes<Entities>[key]
: never
}
}
type CollectionPageAttributes<Entities extends {[name: string]: Entity<any, any, any, any>}, Collections extends CollectionAssociations<Entities>> = {
[Collection in keyof CollectionPageKeys<Entities, Collections>]: {
[key in CollectionPageKeys<Entities, Collections>[Collection]]:
key extends keyof AllEntityAttributes<Entities>
? AllEntityAttributes<Entities>[key]
: never
}
}
type OptionalPropertyNames<T> =
{ [K in keyof T]: undefined extends T[K] ? K : never }[keyof T];
// Common properties from L and R with undefined in R[K] replaced by type in L[K]
type SpreadProperties<L, R, K extends keyof L & keyof R> =
{ [P in K]: L[P] | Exclude<R[P], undefined> };
type Id<T> = {[K in keyof T]: T[K]} // see note at bottom*
// Type of { ...L, ...R }
type Spread<L, R> = Id<
// Properties in L that don't exist in R
& Pick<L, Exclude<keyof L, keyof R>>
// Properties in R with types that exclude undefined
& Pick<R, Exclude<keyof R, OptionalPropertyNames<R>>>
// Properties in R, with types that include undefined, that don't exist in L
& Pick<R, Exclude<OptionalPropertyNames<R>, keyof L>>
// Properties in R, with types that include undefined, that exist in L
& SpreadProperties<L, R, OptionalPropertyNames<R> & keyof L>
>;
type CollectionQueries<E extends {[name: string]: Entity<any, any, any, any>}, Collections extends CollectionAssociations<E>> = {
[Collection in keyof Collections]: {
[EntityName in keyof E]:
EntityName extends Collections[Collection]
? (params:
RequiredProperties<
Parameters<
E[EntityName]["query"][
E[EntityName] extends Entity<infer A, infer F, infer C, infer S>
? Collection extends keyof EntityCollections<A,F,C,S>
? EntityCollections<A,F,C,S>[Collection]
: never
: never
]
>[0]
>) => {
go: GoRecord<{
[EntityResultName in Collections[Collection]]:
EntityResultName extends keyof E
? E[EntityResultName] extends Entity<infer A, infer F, infer C, infer S>
? ResponseItem<A,F,C,S>[]
: never
: never
}>;
params: ParamRecord;
page: {
[EntityResultName in Collections[Collection]]: EntityResultName extends keyof E
? Pick<AllEntityAttributes<E>, Extract<AllEntityAttributeNames<E>, CollectionAttributes<E,Collections>[Collection]>> extends Partial<AllEntityAttributes<E>>
?
PageRecord<
{
[EntityResultName in Collections[Collection]]:
EntityResultName extends keyof E
? E[EntityResultName] extends Entity<infer A, infer F, infer C, infer S>
? ResponseItem<A,F,C,S>[]
: never
: never
},
Partial<
Spread<
Collection extends keyof CollectionPageAttributes<E, Collections>
? CollectionPageAttributes<E, Collections>[Collection]
: {},
Collection extends keyof CollectionIndexAttributes<E, Collections>
? CollectionIndexAttributes<E, Collections>[Collection]
: {}
>
>
>
: never
: never
}[Collections[Collection]];
where: {
[EntityResultName in Collections[Collection]]: EntityResultName extends keyof E
? E[EntityResultName] extends Entity<infer A, infer F, infer C, infer S>
? Pick<AllEntityAttributes<E>, Extract<AllEntityAttributeNames<E>, CollectionAttributes<E,Collections>[Collection]>> extends Partial<AllEntityAttributes<E>>
? CollectionWhereClause<E,A,F,C,S,
Pick<AllEntityAttributes<E>, Extract<AllEntityAttributeNames<E>, CollectionAttributes<E,Collections>[Collection]>>,
WhereRecordsActionOptions<E,A,F,C,S,
Pick<AllEntityAttributes<E>, Extract<AllEntityAttributeNames<E>, CollectionAttributes<E,Collections>[Collection]>>,
{
[EntityResultName in Collections[Collection]]:
EntityResultName extends keyof E
? E[EntityResultName] extends Entity<infer A, infer F, infer C, infer S>
? ResponseItem<A,F,C,S>[]
: never
: never
},
Partial<
Spread<
Collection extends keyof CollectionPageAttributes<E, Collections>
? CollectionPageAttributes<E, Collections>[Collection]
: {},
Collection extends keyof CollectionIndexAttributes<E, Collections>
? CollectionIndexAttributes<E, Collections>[Collection]
: {}
>
>
>>
: never
: never
: never
}[Collections[Collection]];
}
: never
}[keyof E];
}
type RequiredProperties<T> = Pick<T, {[K in keyof T]-?: {} extends Pick<T, K> ? never : K }[keyof T]>
export class Service<E extends {[name: string]: Entity<any, any, any, any>}> {
entities: E;
collections: CollectionQueries<E, CollectionAssociations<E>>
constructor(entities: E, config?: ServiceConfiguration);
}
export type EntityItem<E extends Entity<any, any, any, any>> =
E extends Entity<infer A, infer F, infer C, infer S>
? ResponseItem<A, F, C, S>
: never;
export type CreateEntityItem<E extends Entity<any, any, any, any>> =
E extends Entity<infer A, infer F, infer C, infer S>
? PutItem<A, F, C, S>
: never;
export type UpdateEntityItem<E extends Entity<any, any, any, any>> =
E extends Entity<infer A, infer F, infer C, infer S>
? SetItem<A, F, C, S>
: never;
export type UpdateAddEntityItem<E extends Entity<any, any, any, any>> =
E extends Entity<infer A, infer F, infer C, infer S>
? AddItem<A, F, C, S>
: never;
export type UpdateSubtractEntityItem<E extends Entity<any, any, any, any>> =
E extends Entity<infer A, infer F, infer C, infer S>
? SubtractItem<A, F, C, S>
: never;
export type UpdateAppendEntityItem<E extends Entity<any, any, any, any>> =
E extends Entity<infer A, infer F, infer C, infer S>
? AppendItem<A, F, C, S>
: never;
export type UpdateRemoveEntityItem<E extends Entity<any, any, any, any>> =
E extends Entity<infer A, infer F, infer C, infer S>
? RemoveItem<A, F, C, S>
: never;
export type UpdateDeleteEntityItem<E extends Entity<any, any, any, any>> =
E extends Entity<infer A, infer F, infer C, infer S>
? DeleteItem<A, F, C, S>
: never;
export type EntityRecord<E extends Entity<any, any, any, any>> =
E extends Entity<infer A, infer F, infer C, infer S>
? Item<A,F,C,S,S["attributes"]>
: never;
export type CollectionItem<SERVICE extends Service<any>, COLLECTION extends keyof SERVICE["collections"]> =
SERVICE extends Service<infer E> ? Pick<{
[EntityName in keyof E]: E[EntityName] extends Entity<infer A, infer F, infer C, infer S>
? COLLECTION extends keyof CollectionAssociations<E>
? EntityName extends CollectionAssociations<E>[COLLECTION]
? ResponseItem<A,F,C,S>[]
: never
: never
: never
}, COLLECTION extends keyof CollectionAssociations<E>
? CollectionAssociations<E>[COLLECTION]
: never>
: never | the_stack |
//let RayTrace = new BenchmarkSuite('RayTrace', 739989, [
// new Benchmark('RayTrace', renderScene)
//]);
// Variable used to hold a number that can be used to verify that
// the scene was ray traced correctly.
//TODO: move this stuff to prelude?
/*@ qualif HasP (x: string, y: A): hasProperty(x, y) */
/*@ qualif EnumP(x: string, y: A): enumProp(x, y) */
interface HTMLCanvasElement<M extends ReadOnly> {
/*@ getContext : (string) => {CanvasRenderingContext2D<Mutable> | 0 < 1} */
getContext(s:string):CanvasRenderingContext2D<Mutable>; //or WebGLRenderingContext or null
}
interface CanvasRenderingContext2D<M extends ReadOnly> {
/*@ fillStyle : string */
fillStyle:string;
fillRect(a:number, b:number, c:number, d:number):void;
}
/*@ type EngineOptions = (Mutable) {
canvasHeight: number;
canvasWidth: number;
pixelWidth: {number | v > 0};
pixelHeight: {number | v > 0};
renderDiffuse: boolean;
renderShadows: boolean;
renderHighlights: boolean;
renderReflections: boolean;
rayDepth: number
} */
//TODO: field initializers not actually doing anything, since constructors require all arguments
//TODO: had to add explicit toString calls in toStrings
//TODO: many classes allowed some members to be null; where usage made this seem inappropriate I removed that feature
module VERSION {
export module RayTracer {
declare type MVector = Vector<Mutable>
declare type MColor = Color<Mutable>
declare type IColor = Color<Immutable>
declare type MIntersectionInfo = IntersectionInfo<Mutable>
/*@ checkNumber :: number */
let checkNumber:number=0;
export class Color<M extends ReadOnly> {
/*@ red : number */
public red=0;
/*@ green : number */
public green=0;
/*@ blue : number */
public blue=0;
/*@ new (red:number, green:number, blue:number) : {Color<M> | 0 < 1} */
constructor(red?, green?, blue?) {
this.red = red;
this.green = green;
this.blue = blue;
}
/*@ add <M1 extends ReadOnly, M2 extends ReadOnly> (c1:Color<M1>, c2:Color<M2>) : {MColor | 0 < 1} */
public static add(c1, c2) {
let result = new Color(0, 0, 0);
result.red = c1.red + c2.red;
result.green = c1.green + c2.green;
result.blue = c1.blue + c2.blue;
return result;
}
/*@ addScalar <M extends ReadOnly> (c1:Color<M>, s:number) : {MColor | 0 < 1} */
public static addScalar(c1, s:number) {
let result = new Color(0, 0, 0);
result.red = c1.red + s;
result.green = c1.green + s;
result.blue = c1.blue + s;
result.limit();
return result;
}
/*@ subtract <M1 extends ReadOnly, M2 extends ReadOnly> (c1:Color<M1>, c2:Color<M2>) : {MColor | 0 < 1} */
public static subtract(c1, c2) {
let result = new Color(0, 0, 0);
result.red = c1.red - c2.red;
result.green = c1.green - c2.green;
result.blue = c1.blue - c2.blue;
return result;
}
/*@ multiply <M1 extends ReadOnly, M2 extends ReadOnly> (c1:Color<M1>, c2:Color<M2>) : {MColor | 0 < 1} */
public static multiply(c1, c2) {
let result = new Color(0, 0, 0);
result.red = c1.red * c2.red;
result.green = c1.green * c2.green;
result.blue = c1.blue * c2.blue;
return result;
}
/*@ multiplyScalar <M extends ReadOnly> (c1:Color<M>, f:number) : {MColor | 0 < 1} */
public static multiplyScalar(c1, f:number) {
let result = new Color(0, 0, 0);
result.red = c1.red * f;
result.green = c1.green * f;
result.blue = c1.blue * f;
return result;
}
/*@ divideFactor <M extends ReadOnly> (c1:Color<M>, f:{number | v != 0}) : {MColor | 0 < 1} */
public static divideFactor(c1, f:number) {
let result = new Color(0, 0, 0);
result.red = c1.red / f;
result.green = c1.green / f;
result.blue = c1.blue / f;
return result;
}
/*@ @Mutable limit () : {void | 0 < 1} */
public limit() {
this.red = (this.red > 0) ? ((this.red > 1) ? 1 : this.red) : 0;
this.green = (this.green > 0) ? ((this.green > 1) ? 1 : this.green) : 0;
this.blue = (this.blue > 0) ? ((this.blue > 1) ? 1 : this.blue) : 0;
}
/*@ distance <M extends ReadOnly> (color:Color<M>) : {number | 0 < 1} */
public distance(color) {
let d = Math.abs(this.red - color.red) + Math.abs(this.green - color.green) + Math.abs(this.blue - color.blue);
return d;
}
/*@ blend <M1 extends ReadOnly, M2 extends ReadOnly> (c1:Color<M1>, c2:Color<M2>, w:number) : {MColor | 0 < 1} */
public static blend(c1, c2, w:number) {
let result = new Color(0, 0, 0);
result = Color.add(
Color.multiplyScalar(c1, 1 - w),
Color.multiplyScalar(c2, w)
);
return result;
}
public brightness() {
let r = Math.floor(this.red * 255);
let g = Math.floor(this.green * 255);
let b = Math.floor(this.blue * 255);
return (r * 77 + g * 150 + b * 29) / 256 //ORIG: >> 8;
}
public toString() {
let r = Math.floor(this.red * 255);
let g = Math.floor(this.green * 255);
let b = Math.floor(this.blue * 255);
return "rgb(" + r + "," + g + "," + b + ")";
}
}
export class Light<M extends ReadOnly> {
/*@ position : MVector */
public position:MVector;
/*@ color : IColor */
public color:IColor;
public intensity:number=10;
/*@ new (position:MVector, color:IColor, intensity:number) : {Light<M> | 0 < 1} */
constructor(position:MVector, color:IColor, intensity?) {
this.position = position;
this.color = color;
this.intensity = intensity;
}
public toString() {
return 'Light [' + this.position.x + ',' + this.position.y + ',' + this.position.z + ']';
}
}
export class Vector<M extends ReadOnly> {
/*@ x : number */
public x = 0;
/*@ y : number */
public y = 0;
/*@ z : number */
public z = 0;
/*@ new (x:number, y:number, z:number) : {Vector<M> | 0 < 1} */
constructor(x?, y?, z?) {
this.x = x;
this.y = y;
this.z = z;
}
/*@ @Mutable copy <M extends ReadOnly> (vector:Vector<M>) : {void | 0 < 1} */
public copy(vector) {
this.x = vector.x;
this.y = vector.y;
this.z = vector.z;
}
/*@ normalize () : Vector<Unique> */
public normalize() {
let m = this.magnitude();
if (m === 0) throw new Error("Cannot normalize the 0-vector!");
return new Vector(this.x / m, this.y / m, this.z / m);
}
public magnitude() {
let x = this.x;
let y = this.y;
let z = this.z;
return Math.sqrt((x * x) + (y * y) + (z * z));
}
/*@ cross <M extends ReadOnly> (w:Vector<M>) : {Vector<Unique> | 0 < 1} */
public cross(w) {
return new Vector(
-this.z * w.y + this.y * w.z,
this.z * w.x - this.x * w.z,
-this.y * w.x + this.x * w.y);
}
/*@ dot <M extends ReadOnly> (w:Vector<M>) : {number | 0 < 1} */
public dot(w) {
return this.x * w.x + this.y * w.y + this.z * w.z;
}
/*@ add <M1 extends ReadOnly, M2 extends ReadOnly> (v:Vector<M1>, w:Vector<M2>) : {Vector<Unique> | 0 < 1} */
public static add(v, w) {
return new Vector(w.x + v.x, w.y + v.y, w.z + v.z);
}
/*@ subtract <M1 extends ReadOnly, M2 extends ReadOnly> (v:Vector<M1>, w:Vector<M2>) : {Vector<Unique> | 0 < 1} */
public static subtract(v, w) {
if (!w || !v) throw 'Vectors must be defined [' + v + ',' + w + ']';
return new Vector(v.x - w.x, v.y - w.y, v.z - w.z);
}
/*@ multiplyVector <M1 extends ReadOnly, M2 extends ReadOnly> (v:Vector<M1>, w:Vector<M2>) : {Vector<Unique> | 0 < 1} */
public static multiplyVector(v, w) {
return new Vector(v.x * w.x, v.y * w.y, v.z * w.z);
}
/*@ multiplyScalar <M extends ReadOnly> (v:Vector<M>, w:number) : {Vector<Unique> | 0 < 1} */
public static multiplyScalar(v, w:number) {
return new Vector(v.x * w, v.y * w, v.z * w);
}
public toString() {
return 'Vector [' + this.x + ',' + this.y + ',' + this.z + ']';
}
}
export class Ray<M extends ReadOnly> {
/*@ position : MVector */
public position:MVector;
/*@ direction : MVector */
public direction:MVector;
/*@ new (position:MVector, direction:MVector) : {Ray<M> | 0 < 1} */
constructor(position:MVector, direction:MVector) {
this.position = position;
this.direction = direction;
}
public toString() {
return 'Ray [' + this.position.toString() + ',' + this.direction.toString() + ']';
}
}
export class Scene<M extends ReadOnly> {
public camera : Camera<Immutable>;
/*@ shapes : IArray<Shape<Immutable>> */
public shapes;
/*@ lights : IArray<Light<Immutable>> */
public lights;
public background : Background<Immutable>;
constructor() {
this.camera = new Camera(
new Vector(0, 0, -5),
new Vector(0, 0, 1),
new Vector(0, 1, 0)
);
this.shapes = new Array<Shape<Immutable>>(0);
this.lights = new Array<Light<Immutable>>(0);
this.background = new Background(new Color(0, 0, 1/2), 1/5);
}
}
// module Material {
export class BaseMaterial<M extends ReadOnly> {
public gloss:number = 2;
public transparency:number = 0;
public reflection:number = 0;
public refraction:number = 1/2;
public hasTexture:boolean = false;
/*@ new (gloss:number, transparency:number, reflection:number, refraction:number, hasTexture:boolean) : {BaseMaterial<M> | 0 < 1} */
constructor(gloss?, // [0...infinity] 0 = matt
transparency?, // 0=opaque
reflection?, // [0...infinity] 0 = no reflection
refraction?,
hasTexture?) {
this.gloss = gloss;
this.transparency = transparency;
this.reflection = reflection;
this.refraction = refraction;
this.hasTexture = hasTexture;
}
/*@ getColor (u:number, v:number) : {IColor | 0 < 1} */
public getColor(u:number, v:number) : IColor {
throw "Abstract method";
}
/*@ wrapUp (t:number) : {number | 0 < 1} */
public wrapUp(t:number) {
t = t % 2;
if (t < -1) t = t + 2 //ORIG: t += 2;
if (t >= 1) t = t - 2 //ORIG: t -= 2;
return t;
}
public toString() {
return 'Material [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture + ']';
}
}
export class Solid<M extends ReadOnly> extends BaseMaterial<M> {
public color:IColor;
/*@ new (color:IColor, reflection:number, refraction:number, transparency:number, gloss:number) : {Solid<M> | 0 < 1} */
constructor(color:IColor, reflection:number, refraction:number, transparency:number, gloss:number) {
super(gloss, transparency, reflection, refraction, false);
this.color = color;
}
/*@ getColor (u:number, v:number) : {IColor | 0 < 1} */
public getColor(u:number, v:number) : IColor {
return this.color;
}
public toString() {
return 'SolidMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture + ']';
}
}
export class Chessboard<M extends ReadOnly> extends BaseMaterial<M> {
public colorEven:IColor;
public colorOdd:IColor;
public density:number = 1/2;
/*@ new (colorEven:IColor, colorOdd:IColor, reflection:number, transparency:number, gloss:number, density:number) : {Chessboard<M> | 0 < 1} */
constructor(colorEven:IColor, colorOdd:IColor,
reflection:number,
transparency:number,
gloss:number,
density?) {
super(gloss, transparency, reflection, 1/2, true);
this.colorEven = colorEven;
this.colorOdd = colorOdd;
this.density = density;
}
/*@ getColor (u:number, v:number) : {IColor | 0 < 1} */
public getColor(u:number, v:number) : IColor {
let t = this.wrapUp(u * this.density) * this.wrapUp(v * this.density);
if (t < 0)
return this.colorEven;
else
return this.colorOdd;
}
public toString() {
return 'ChessMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture + ']';
}
}
export class Shape<M extends ReadOnly> {
/*@ position : MVector */
public position:MVector;
public material:BaseMaterial<Immutable>;
/*@ new (position:MVector, material:BaseMaterial<Immutable>) : {Shape<M> | 0 < 1} */
constructor(position:MVector, material) {
this.position = position;
this.material = material;
}
/*@ intersect <M extends ReadOnly> (ray:Ray<M>) : {MIntersectionInfo | 0 < 1} */
public intersect(ray) : MIntersectionInfo {
throw "Abstract method";
}
}
export class Sphere<M extends ReadOnly> extends Shape<M> {
public radius:number;
/*@ new (position:MVector, radius:number, material:BaseMaterial<Immutable>) : {Sphere<M> | 0 < 1} */
constructor(position:MVector, radius:number, material) {
super(position, material);
this.radius = radius;
}
/*@ intersect <M extends ReadOnly> (ray:Ray<M>) : {MIntersectionInfo | 0 < 1} */
public intersect(ray) : MIntersectionInfo {
let info = new IntersectionInfo(false, 0, null, null, null, null, null);
info.shape = <Shape<ReadOnly>>this;
let dst:MVector = Vector.subtract(ray.position, this.position);
let B = dst.dot(ray.direction);
let C = dst.dot(dst) - (this.radius * this.radius);
let D = (B * B) - C;
if (D > 0) { // intersection!
info.isHit = true;
let infoDist = (-B) - Math.sqrt(D);
info.distance = infoDist;
let infoPos:MVector = Vector.add(
ray.position,
Vector.multiplyScalar(
ray.direction,
infoDist
)
);
info.position = infoPos;
info.normal = Vector.subtract(
infoPos,
this.position
).normalize();
info.color = this.material.getColor(0, 0);
} else {
info.isHit = false;
}
return info;
}
public toString() {
return 'Sphere [position=' + this.position.toString() + ', radius=' + this.radius + ']';
}
}
export class Plane<M extends ReadOnly> extends Shape<M> {
public d:number;
/*@ new (position:MVector, d:number, material:BaseMaterial<Immutable>) : {Plane<M> | 0 < 1} */
constructor(position:MVector, d:number, material) {
super(position, material);
this.d = d;
}
/*@ intersect <M extends ReadOnly> (ray:Ray<M>) : {MIntersectionInfo | 0 < 1} */
public intersect(ray) : MIntersectionInfo {
let info = new IntersectionInfo(false, 0, null, null, null, null, null);
let Vd = this.position.dot(ray.direction);
if (Vd === 0) return info; // no intersection
let t = -(this.position.dot(ray.position) + this.d) / Vd;
if (t <= 0) return info;
info.shape = <Shape<ReadOnly>>this;
info.isHit = true;
let infoPos:MVector = Vector.add(
ray.position,
Vector.multiplyScalar(
ray.direction,
t
)
);
info.position = infoPos;
info.normal = this.position;
info.distance = t;
if (this.material.hasTexture) {
let vU:MVector = new Vector(this.position.y, this.position.z, -this.position.x);
let vV:MVector = vU.cross(this.position);
let u = infoPos.dot(vU);
let v = infoPos.dot(vV);
info.color = this.material.getColor(u, v);
} else {
info.color = this.material.getColor(0, 0);
}
return info;
}
public toString() {
return 'Plane [' + this.position.toString() + ', d=' + this.d + ']';
}
}
// }
export class IntersectionInfo<M extends ReadOnly> {
/*@ isHit : boolean */
public isHit = false;
/*@ hitCount : number */
public hitCount = 0;
/*@ shape : Shape<ReadOnly> + null */
public shape = null;
/*@ position : MVector + null */
public position = null;
/*@ normal : MVector + null */
public normal = null;
/*@ color : IColor + null */
public color = null;
/*@ distance : number + null */
public distance = null;
/*@ new (isHit:boolean,
hitCount:number,
shape:Shape<Immutable> + null,
position:MVector + null,
normal:MVector + null,
color:IColor + null,
distance:number + null) : {IntersectionInfo<M> | 0 < 1} */
constructor(isHit?, hitCount?, shape?, position?, normal?, color?, distance?) {
this.isHit = isHit;
this.hitCount = hitCount;
this.shape = shape;
this.position = position;
this.normal = normal;
this.color = color;
this.distance = distance;
}
/*@ @Mutable initialize () : {void | 0 < 1} */
public initialize() {
this.color = <IColor>(new Color(0, 0, 0));
}
public toString() {
let position = this.position;
if (!position) return 'Intersection [position==null]';
return 'Intersection [' + position.toString() + ']';
}
}
export class Camera<M extends ReadOnly> {
public equator:MVector;
public screen:MVector;
/*@ position : MVector */
public position:MVector;
/*@ lookAt : MVector */
public lookAt:MVector;
/*@ up : MVector */
public up:MVector;
/*@ new (position:MVector, lookAt:MVector, up:MVector) : {Camera<M> | 0 < 1} */
constructor(position:MVector,
lookAt:MVector,
up:MVector) {
this.equator = lookAt.normalize().cross(up);
this.screen = Vector.add(position, lookAt);
this.position = position;
this.lookAt = lookAt;
this.up = up;
}
/*@ getRay (vx:number, vy:number) : {Ray<Unique> | 0 < 1} */
public getRay(vx:number, vy:number) {
let pos:MVector = Vector.subtract(
this.screen,
Vector.subtract(
Vector.multiplyScalar(this.equator, vx),
Vector.multiplyScalar(this.up, vy)
)
);
pos.y = pos.y * -1;
let dir = Vector.subtract(
pos,
this.position
);
let ray = new Ray(pos, dir.normalize());
return ray;
}
public toString() {
return 'Ray []';
}
}
export class Background<M extends ReadOnly> {
/*@ color : MColor */
public color:MColor;
public ambience:number = 0;
/*@ new (color:MColor, ambience:number) : {Background<M> | 0 < 1} */
constructor(color, ambience?) {
this.color = color;
this.ambience = ambience;
}
}
/*@ extend :: (dest:(Mutable){[s:string]:top}, src:(Immutable){[s:string]:top}) => {(Mutable){[s:string]:top} | 0 < 1} */
function extend(dest, src) {
// PV TODO
for (let p in src) {
dest[p] = src[p];
}
return dest;
}
export class Engine<M extends ReadOnly> {
/*@ canvas : CanvasRenderingContext2D<Mutable> + null */
public canvas:CanvasRenderingContext2D<Mutable> = null; /* 2d context we can render to */
/*@ options : EngineOptions */
public options;
/*@ new (options:EngineOptions) : {Engine<M> | 0 < 1} */
constructor(options) {
// ORIG:
// let this_options = extend({
// canvasHeight: 100,
// canvasWidth: 100,
// pixelWidth: 2,
// pixelHeight: 2,
// renderDiffuse: false,
// renderShadows: false,
// renderHighlights: false,
// renderReflections: false,
// rayDepth: 2
// }, options || {});
let this_options = options;
this_options.canvasHeight = this_options.canvasHeight / this_options.pixelHeight; //ORIG: /=
this_options.canvasWidth = this_options.canvasWidth / this_options.pixelWidth; //ORIG: /=
this.options = this_options;
/* TODO: dynamically include other scripts */
}
/*@ setPixel <M extends ReadOnly>(x:number, y:number, color:Color<M>) : {void | 0 < 1} */
public setPixel(x, y, color) {
let pxW = this.options.pixelWidth;
let pxH = this.options.pixelHeight;
let canvas = this.canvas;
if (canvas) {
(<CanvasRenderingContext2D<Mutable>>canvas).fillStyle = color.toString();
canvas.fillRect(x * pxW, y * pxH, pxW, pxH);
} else {
if (x === y) {
checkNumber += color.brightness();
}
// print(x * pxW, y * pxH, pxW, pxH);
}
}
/*@ @Mutable renderScene <M1 extends ReadOnly, M2 extends ReadOnly> (scene:Scene<M1>, canvas:HTMLCanvasElement<M2> + undefined) : {void | 0 < 1} */
public renderScene(scene, canvas) {
checkNumber = 0;
/* Get canvas */
if (canvas) {
this.canvas = canvas.getContext("2d");
} else {
this.canvas = null;
}
let canvasHeight = this.options.canvasHeight;
let canvasWidth = this.options.canvasWidth;
for (let y = 0; y < canvasHeight; y++) {
for (let x = 0; x < canvasWidth; x++) {
let yp = y * 1 / canvasHeight * 2 - 1;
let xp = x * 1 / canvasWidth * 2 - 1;
let ray:Ray<Mutable> = scene.camera.getRay(xp, yp);
let color = this.getPixelColor(ray, scene);
this.setPixel(x, y, color);
}
}
if (checkNumber !== 2321) {
throw new Error("Scene rendered incorrectly");
}
}
/*@ getPixelColor <M1 extends ReadOnly, M2 extends ReadOnly> (ray:Ray<M1>, scene:Scene<M2>) : {MColor | 0 < 1} */
public getPixelColor(ray, scene) {
let info = this.testIntersection(ray, scene, undefined);
if (info.isHit) {
let color = this.rayTrace(info, ray, scene, 0);
return color;
}
return scene.background.color;
}
/*@ testIntersection <M1 extends ReadOnly, M2 extends ReadOnly, M3 extends ReadOnly> (ray:Ray<M1>, scene:Scene<M2>, exclude:Shape<M3> + undefined) : {MIntersectionInfo | 0 < 1} */
public testIntersection(ray, scene, exclude?) {
let hits = 0;
/*@ best :: MIntersectionInfo */
let best = new IntersectionInfo(false, 0, null, null, null, null, null);
best.distance = 2000;
let sceneShapes = scene.shapes;
for (let i = 0; i < sceneShapes.length; i++) {
let shape = sceneShapes[i];
if (shape !== exclude) {
let info = shape.intersect(ray);
if (info.isHit && info.distance >= 0 && info.distance < best.distance) {
best = info;
hits++;
}
}
}
best.hitCount = hits;
return best;
}
/*@ getReflectionRay <M1 extends ReadOnly, M2 extends ReadOnly> (P:MVector, N:Vector<M1>, V:Vector<M2>) : {Ray<M> | 0 < 1} */
public getReflectionRay(P, N, V) {
let c1 = -N.dot(V);
let R1 = Vector.add(
Vector.multiplyScalar(N, 2 * c1),
V
);
return new Ray(P, R1);
}
/*@ rayTrace <M1 extends ReadOnly, M2 extends ReadOnly, M3 extends ReadOnly> (info:IntersectionInfo<M1>, ray:Ray<M2>, scene:Scene<M3>, depth:number) : {MColor | 0 < 1} */
public rayTrace(info, ray, scene, depth) {
let infoColor = info.color;
let infoShape = info.shape;
let infoNormal = info.normal;
let infoPosition = info.position;
// if (!infoColor ||
// !infoShape ||
// !infoNormal ||
// !infoPosition) throw new Error('incomplete IntersectionInfo'); //TODO is there a way to get rid of this check?
if (!infoColor) throw new Error('incomplete IntersectionInfo'); //TODO can we at least get the more compact version above?
if (!infoShape) throw new Error('incomplete IntersectionInfo');
if (!infoNormal) throw new Error('incomplete IntersectionInfo');
if (!infoPosition) throw new Error('incomplete IntersectionInfo');
// Calc ambient
let color = Color.multiplyScalar(infoColor, scene.background.ambience);
let oldColor = color;
let shininess = Math.pow(10, infoShape.material.gloss + 1);
let sceneLights = scene.lights;
for (let i = 0; i < sceneLights.length; i++) {
let light = sceneLights[i];
// Calc diffuse lighting
let v:MVector = Vector.subtract(
light.position,
infoPosition
).normalize();
if (this.options.renderDiffuse) {
let L = v.dot(infoNormal);
if (L > 0) {
color = Color.add(
color,
Color.multiply(
infoColor,
Color.multiplyScalar(
light.color,
L
)
)
);
}
}
// The greater the depth the more accurate the colours, but
// this is exponentially (!) expensive
if (depth <= this.options.rayDepth) {
// calculate reflection ray
if (this.options.renderReflections && infoShape.material.reflection > 0) {
let reflectionRay = this.getReflectionRay(infoPosition, infoNormal, ray.direction);
let refl = this.testIntersection(reflectionRay, scene, infoShape);
let reflColor;
if (refl.isHit && refl.distance > 0) {
reflColor = this.rayTrace(refl, reflectionRay, scene, depth + 1);
} else {
reflColor = scene.background.color;
}
color = Color.blend(
color,
reflColor,
infoShape.material.reflection
);
}
// Refraction
/* TODO */
}
/* Render shadows and highlights */
let shadowInfo = new IntersectionInfo(false, 0, null, null, null, null, null);
if (this.options.renderShadows) {
let shadowRay:Ray<ReadOnly> = new Ray(infoPosition, v);
shadowInfo = this.testIntersection(shadowRay, scene, infoShape);
if (shadowInfo.isHit && shadowInfo.shape !== infoShape /*&& shadowInfo.shape.type != 'PLANE'*/) {
let vA = Color.multiplyScalar(color, 1/2);
let shadowInfoShape = shadowInfo.shape;
if (!shadowInfoShape) throw new Error('This should probably never happen');
let dB = (1/2 * Math.pow(shadowInfoShape.material.transparency, 1/2));
color = Color.addScalar(vA, dB);
}
}
// Phong specular highlights
if (this.options.renderHighlights && !shadowInfo.isHit && infoShape.material.gloss > 0) {
let Lv = Vector.subtract(
infoShape.position,
light.position
).normalize();
let E = Vector.subtract(
scene.camera.position,
infoShape.position
).normalize();
let H:MVector = Vector.subtract(
E,
Lv
).normalize();
let glossWeight = Math.pow(Math.max(infoNormal.dot(H), 0), shininess);
color = Color.add(
Color.multiplyScalar(light.color, glossWeight),
color
);
}
}
color.limit();
return color;
}
}
// }
export function renderScene() {
let scene:Scene<Mutable> = new Scene();
scene.camera = new Camera(
new Vector(0, 0, -15),
new Vector(-1/5, 0, 5),
new Vector(0, 1, 0)
);
scene.background = new Background(
new Color(1/2, 1/2, 1/2),
2/5
);
let sphere:Shape<Immutable> = new Sphere(
new Vector(-3/2, 3/2, 2),
3/2,
new Solid(
new Color(0, 1/2, 1/2),
3/10,
0,
0,
2
)
);
let sphere1:Shape<Immutable> = new Sphere(
new Vector(1, 1/4, 1),
1/2,
new Solid(
new Color(9/10, 9/10, 9/10),
1/10,
0,
0,
3/2
)
);
let plane:Shape<Immutable> = new Plane(
new Vector(1/10, 9/10, -1/2).normalize(),
6/5,
new Chessboard(
new Color(1, 1, 1),
new Color(0, 0, 0),
1/5,
0,
1,
7/10
)
);
// ORIG:
// scene.shapes.push(plane);
// scene.shapes.push(sphere);
// scene.shapes.push(sphere1);
scene.shapes = [plane, sphere, sphere1];
let light:Light<Immutable> = new Light(
new Vector(5, 10, -1),
new Color(4/5, 4/5, 4/5),
10 // (ORIG: default param omitted)
);
let light1:Light<Immutable> = new Light(
new Vector(-3, 5, -15),
new Color(4/5, 4/5, 4/5),
100
);
// ORIG:
// scene.lights.push(light);
// scene.lights.push(light1);
scene.lights = [light, light1];
let imageWidth = 100; // $F('imageWidth');
let imageHeight = 100; // $F('imageHeight');
/*@ pixelSize :: {IArray<{number | v > 0}> | len(v) = 2} */
let pixelSize = [5,5];//"5,5".split(','); // $F('pixelSize').split(',');
let renderDiffuse = true; // $F('renderDiffuse');
let renderShadows = true; // $F('renderShadows');
let renderHighlights = true; // $F('renderHighlights');
let renderReflections = true; // $F('renderReflections');
let rayDepth = 2;//$F('rayDepth');
let raytracer = new Engine(
{
canvasWidth: imageWidth,
canvasHeight: imageHeight,
pixelWidth: pixelSize[0],
pixelHeight: pixelSize[1],
renderDiffuse: renderDiffuse,
renderHighlights: renderHighlights,
renderShadows: renderShadows,
renderReflections: renderReflections,
rayDepth: rayDepth
}
);
raytracer.renderScene(scene, undefined);
}
}
} | the_stack |
import type {Mutable, Class, Initable, AnyTiming} from "@swim/util";
import {Affinity, MemberFastenerClass, Property, Animator} from "@swim/component";
import {AnyLength, Length, R2Point, R2Box} from "@swim/math";
import {AnyFont, Font, AnyColor, Color} from "@swim/style";
import {ThemeAnimator} from "@swim/theme";
import {ViewContextType, AnyView, View, ViewRef} from "@swim/view";
import {
GraphicsViewInit,
GraphicsView,
CanvasContext,
CanvasRenderer,
TypesetView,
TextRunView,
} from "@swim/graphics";
import type {DataPointCategory, DataPointLabelPlacement} from "./DataPoint";
import type {DataPointViewObserver} from "./DataPointViewObserver";
/** @public */
export type AnyDataPointView<X = unknown, Y = unknown> = DataPointView<X, Y> | DataPointViewInit<X, Y>;
/** @public */
export interface DataPointViewInit<X = unknown, Y = unknown> extends GraphicsViewInit {
x: X;
y: Y;
y2?: Y;
radius?: AnyLength;
hitRadius?: number;
color?: AnyColor;
opacity?: number;
font?: AnyFont;
textColor?: AnyColor;
category?: DataPointCategory;
labelPadding?: AnyLength;
labelPlacement?: DataPointLabelPlacement;
label?: GraphicsView | string;
}
/** @public */
export class DataPointView<X = unknown, Y = unknown> extends GraphicsView {
constructor() {
super();
this.xCoord = NaN;
this.yCoord = NaN;
this.y2Coord = void 0;
this.gradientStop = false;
}
override readonly observerType?: Class<DataPointViewObserver<X, Y>>;
readonly xCoord: number
/** @internal */
setXCoord(xCoord: number): void {
(this as Mutable<this>).xCoord = xCoord;
}
readonly yCoord: number
/** @internal */
setYCoord(yCoord: number): void {
(this as Mutable<this>).yCoord = yCoord;
}
readonly y2Coord: number | undefined;
/** @internal */
setY2Coord(y2Coord: number | undefined): void {
(this as Mutable<this>).y2Coord = y2Coord;
}
@Animator<DataPointView<X, Y>, X | undefined>({
willSetValue(newX: X | undefined, oldX: X | undefined): void {
this.owner.callObservers("viewWillSetDataPointX", newX, oldX, this.owner);
},
didSetValue(newX: X | undefined, oldX: X | undefined): void {
this.owner.callObservers("viewDidSetDataPointX", newX, oldX, this.owner);
},
})
readonly x!: Animator<this, X | undefined>;
@Animator<DataPointView<X, Y>, Y>({
willSetValue(newY: Y | undefined, oldY: Y | undefined): void {
this.owner.callObservers("viewWillSetDataPointY", newY, oldY, this.owner);
},
didSetValue(newY: Y | undefined, oldY: Y | undefined): void {
this.owner.callObservers("viewDidSetDataPointY", newY, oldY, this.owner);
},
})
readonly y!: Animator<this, Y>;
@Animator<DataPointView<X, Y>, Y | undefined>({
willSetValue(newY2: Y | undefined, oldY2: Y | undefined): void {
this.owner.callObservers("viewWillSetDataPointY2", newY2, oldY2, this.owner);
},
didSetValue(newY2: Y | undefined, oldY2: Y | undefined): void {
this.owner.callObservers("viewDidSetDataPointY2", newY2, oldY2, this.owner);
},
})
readonly y2!: Animator<this, Y | undefined>;
@ThemeAnimator<DataPointView<X, Y>, Length | null, AnyLength | null>({
type: Length,
value: null,
willSetValue(newRadius: Length | null, oldRadius: Length | null): void {
this.owner.callObservers("viewWillSetDataPointRadius", newRadius, oldRadius, this.owner);
},
didSetValue(newRadius: Length | null, oldRadius: Length | null): void {
this.owner.callObservers("viewDidSetDataPointRadius", newRadius, oldRadius, this.owner);
},
})
readonly radius!: ThemeAnimator<this, Length | null, AnyLength | null>;
@Property({type: Number, value: 5})
readonly hitRadius!: Property<this, number>;
@ThemeAnimator<DataPointView<X, Y>, Color | null, AnyColor | null>({
type: Color,
value: null,
willSetValue(newColor: Color | null, oldColor: Color | null): void {
this.owner.callObservers("viewWillSetDataPointColor", newColor, oldColor, this.owner);
},
didSetValue(newColor: Color | null, oldColor: Color | null): void {
this.owner.updateGradientStop();
this.owner.callObservers("viewDidSetDataPointColor", newColor, oldColor, this.owner);
},
})
readonly color!: ThemeAnimator<this, Color | null, AnyColor | null>;
@ThemeAnimator<DataPointView<X, Y>, number | undefined>({
type: Number,
willSetValue(newOpacity: number | undefined, oldOpacity: number | undefined): void {
this.owner.callObservers("viewWillSetDataPointOpacity", newOpacity, oldOpacity, this.owner);
},
didSetValue(newOpacity: number | undefined, oldOpacity: number | undefined): void {
this.owner.updateGradientStop();
this.owner.callObservers("viewDidSetDataPointOpacity", newOpacity, oldOpacity, this.owner);
},
})
readonly opacity!: ThemeAnimator<this, number | undefined>;
@ThemeAnimator({type: Font, inherits: true})
readonly font!: ThemeAnimator<this, Font | undefined, AnyFont | undefined>;
@ThemeAnimator({type: Color, inherits: true})
readonly textColor!: ThemeAnimator<this, Color | undefined, AnyColor | undefined>;
@Property({type: String})
readonly category!: Property<this, DataPointCategory | undefined>;
@ThemeAnimator({type: Length, value: Length.zero(), updateFlags: View.NeedsLayout})
readonly labelPadding!: ThemeAnimator<this, Length, AnyLength>;
@ViewRef<DataPointView<X, Y>, GraphicsView & Initable<GraphicsViewInit | string>>({
key: true,
type: TextRunView,
binds: true,
willAttachView(labelView: GraphicsView): void {
this.owner.callObservers("viewWillAttachDataPointLabel", labelView, this.owner);
},
didDetachView(labelView: GraphicsView): void {
this.owner.callObservers("viewDidDetachDataPointLabel", labelView, this.owner);
},
fromAny(value: AnyView<GraphicsView> | string): GraphicsView {
if (typeof value === "string") {
if (this.view instanceof TextRunView) {
this.view.text(value);
return this.view;
} else {
return TextRunView.fromAny(value);
}
} else {
return GraphicsView.fromAny(value);
}
},
})
readonly label!: ViewRef<this, GraphicsView & Initable<GraphicsViewInit | string>>;
static readonly label: MemberFastenerClass<DataPointView, "label">;
@Property({type: String, value: "auto"})
readonly labelPlacement!: Property<this, DataPointLabelPlacement>;
setState(point: DataPointViewInit<X, Y>, timing?: AnyTiming | boolean): void {
if (point.x !== void 0) {
this.x(point.x, timing);
}
if (point.y !== void 0) {
this.y(point.y, timing);
}
if (point.y2 !== void 0) {
this.y2(point.y2, timing);
}
if (point.radius !== void 0) {
this.radius(point.radius, timing);
}
if (point.hitRadius !== void 0) {
this.hitRadius(point.hitRadius);
}
if (point.color !== void 0) {
this.color(point.color, timing);
}
if (point.opacity !== void 0) {
this.opacity(point.opacity, timing);
}
if (point.font !== void 0) {
this.font(point.font, timing);
}
if (point.textColor !== void 0) {
this.textColor(point.textColor, timing);
}
if (point.category !== void 0) {
this.category(point.category);
}
if (point.labelPadding !== void 0) {
this.labelPadding(point.labelPadding, timing);
}
if (point.labelPlacement !== void 0) {
this.labelPlacement(point.labelPlacement);
}
if (point.label !== void 0) {
this.label(point.label);
}
}
/** @internal */
readonly gradientStop: boolean;
isGradientStop(): boolean {
return this.gradientStop;
}
protected updateGradientStop(): void {
(this as Mutable<this>).gradientStop = this.color.value !== null || this.opacity.value !== void 0;
}
protected override onLayout(viewContext: ViewContextType<this>): void {
super.onLayout(viewContext);
this.layoutDataPoint(this.viewFrame);
}
protected layoutDataPoint(frame: R2Box): void {
const labelView = this.label.view;
if (labelView !== null) {
this.layoutLabel(labelView, frame);
}
}
protected layoutLabel(labelView: GraphicsView, frame: R2Box): void {
let placement = this.labelPlacement.value;
if (placement !== "above" && placement !== "below" && placement !== "middle") {
const category = this.category.value;
if (category === "increasing" || category === "maxima") {
placement = "above";
} else if (category === "decreasing" || category === "minima") {
placement = "below";
} else {
placement = "above";
}
}
const x = this.xCoord;
const y0 = this.yCoord;
let y1 = y0;
if (placement === "above") {
y1 -= this.labelPadding.getValue().pxValue(Math.min(frame.width, frame.height));
} else if (placement === "below") {
y1 += this.labelPadding.getValue().pxValue(Math.min(frame.width, frame.height));
}
if (TypesetView.is(labelView)) {
labelView.textAlign.setState("center", Affinity.Intrinsic);
if (placement === "above") {
labelView.textBaseline.setState("bottom", Affinity.Intrinsic);
} else if (placement === "below") {
labelView.textBaseline.setState("top", Affinity.Intrinsic);
} else if (placement === "middle") {
labelView.textBaseline.setState("middle", Affinity.Intrinsic);
}
labelView.textOrigin.setState(new R2Point(x, y1), Affinity.Intrinsic);
}
}
protected override hitTest(x: number, y: number, viewContext: ViewContextType<this>): GraphicsView | null {
const renderer = viewContext.renderer;
if (renderer instanceof CanvasRenderer) {
return this.hitTestPoint(x, y, renderer.context, this.viewFrame);
}
return null;
}
protected hitTestPoint(x: number, y: number, context: CanvasContext, frame: R2Box): GraphicsView | null {
let hitRadius = this.hitRadius.value;
const radius = this.radius.value;
if (radius !== null) {
const size = Math.min(frame.width, frame.height);
hitRadius = Math.max(hitRadius, radius.pxValue(size));
}
const dx = this.xCoord - x;
const dy = this.yCoord - y;
if (dx * dx + dy * dy < hitRadius * hitRadius) {
return this;
}
return null;
}
override init(init: DataPointViewInit<X, Y>): void {
super.init(init);
this.setState(init);
}
static override fromAny<X, Y>(value: AnyDataPointView<X, Y>): DataPointView<X, Y>;
static override fromAny<S extends abstract new (...args: any) => InstanceType<S>>(this: S, value: AnyView<InstanceType<S>>): InstanceType<S>;
static override fromAny<S extends abstract new (...args: any) => InstanceType<S>>(this: S, value: AnyView<InstanceType<S>>): InstanceType<S> {
return super.fromAny(value as any) as InstanceType<S>;
}
} | the_stack |
import "jquery";
import {
Config,
ImageIconOptions,
SvgIconOptions,
Identifiable,
SvgIconSetOptions,
SvgCumulativeIconSetOptions,
CssIconSetOptions,
ImageIcon,
DynamicUrlDeclaration,
SvgIconSet,
SvgCumulativeIconSet,
CssIconSet
} from "webicon";
/**
* Provides tests for the `webicon`-module.
*/
export class WebiconTests {
getUrlObject<TUriParam = undefined>(): DynamicUrlDeclaration<TUriParam> {
const result: DynamicUrlDeclaration<TUriParam> = {
url: "",
params: {}
};
return result;
}
getStringUrlCallback<TUriParam = undefined>(): DynamicUrlDeclaration<TUriParam> {
const result: DynamicUrlDeclaration<TUriParam> = {
url: (arg) => {
// $ExpectType TUriParam
arg;
return "";
},
params: {}
};
return result;
}
getObjectUrlCallback<TUriParam = undefined>(): DynamicUrlDeclaration<TUriParam> {
const result: DynamicUrlDeclaration<TUriParam> = {
url: (arg) => {
// $ExpectType TUriParam
arg;
return {
url: "",
params: {}
};
}
};
return result;
}
/**
* Tests for the `webicon`-module.
*/
Test() {
const config: Config = {};
const IDParser: ImageIconOptions["iconIdParser"] = (id, params) => {
// $ExpectType string
id;
// $ExpectType string[]
params;
return "";
};
const IDResolver: ImageIconOptions["iconIdResolver"] = (id) => {
// $ExpectType string
id;
return "";
};
const ClassResolver: CssIconSetOptions["className"] = (id, params) => {
// $ExpectType string
id;
// $ExpectType string[]
params;
return "";
};
const icon: ImageIcon = {
iconIdParser: IDParser
};
const set: SvgIconSet = {
cumulative: false,
iconIdParser: IDParser,
iconSize: 1,
viewBox: ""
};
const cumulativeSet: SvgCumulativeIconSet = {
cumulative: true,
iconIdParser: IDParser,
iconSize: 1,
viewBox: "",
waitDuration: 1
};
const cssIconSet: CssIconSet = {
iconIdParser: IDParser
};
const iconOptions: SvgIconOptions = {
iconIdParser: IDParser,
iconIdResolver: IDResolver,
iconSize: 1,
svgIconSize: 1,
preloadable: true,
size: 1,
url: "",
uri: "",
viewBox: ""
};
const idIconOptions: Identifiable & SvgIconOptions = {
id: "clock",
iconIdParser: IDParser,
iconIdResolver: IDResolver,
iconSize: 1,
svgIconSize: 1,
preloadable: true,
size: 1,
url: "",
uri: "",
viewBox: ""
};
const setOptions: SvgIconSetOptions = {
cumulative: false,
iconIdParser: IDParser,
iconIdResolver: IDResolver,
iconSize: 1,
preloadable: true,
size: 1,
svgIconSize: 1,
uri: "",
url: "",
viewBox: ""
};
const cumulativeSetOptions: SvgCumulativeIconSetOptions = {
cumulative: true,
iconIdParser: IDParser,
iconSize: 1,
size: 1,
svgIconSize: 1,
uri: "",
url: "",
viewBox: "",
waitDuration: 0
};
const idSetOptions: Identifiable & SvgIconSetOptions = {
id: "",
cumulative: false,
iconIdParser: IDParser,
iconIdResolver: IDResolver,
iconSize: 1,
preloadable: true,
size: 1,
svgIconSize: 1,
uri: "",
url: "",
viewBox: ""
};
const cssIconSetOptions: CssIconSetOptions = {
class: "",
className: "",
cssClass: "",
iconIdParser: IDParser
};
const idCssIconOptions: Identifiable & CssIconSetOptions = {
id: "",
class: "",
className: "",
cssClass: "",
iconIdParser: IDParser
};
/**
* Configuring `webicon` using a configuration-handler.
*/
$().webicons(
(config) => {
// $ExpectType PublicApi
config;
config.icon("", "", icon);
config.icon("", this.getUrlObject(), icon);
config.icon("", this.getStringUrlCallback(), icon);
config.icon("", this.getObjectUrlCallback(), icon);
config.svgSet("", "");
config.svgSet("", "", set);
config.svgSet("", "", cumulativeSet);
config.svgSet("", this.getUrlObject());
config.svgSet("", this.getUrlObject(), set);
config.svgSet("", this.getUrlObject<string[]>(), cumulativeSet);
config.svgSet("", this.getStringUrlCallback());
config.svgSet("", this.getStringUrlCallback(), set);
config.svgSet("", this.getStringUrlCallback<string[]>(), cumulativeSet);
config.svgSet("", this.getObjectUrlCallback());
config.svgSet("", this.getObjectUrlCallback(), set);
config.svgSet("", this.getObjectUrlCallback<string[]>(), cumulativeSet);
config.iconSet("", "");
config.iconSet("", "", set);
config.iconSet("", "", cumulativeSet);
config.iconSet("", this.getUrlObject());
config.iconSet("", this.getUrlObject(), set);
config.iconSet("", this.getUrlObject<string[]>(), cumulativeSet);
config.iconSet("", this.getStringUrlCallback());
config.iconSet("", this.getStringUrlCallback(), set);
config.iconSet("", this.getStringUrlCallback<string[]>(), cumulativeSet);
config.iconSet("", this.getObjectUrlCallback());
config.iconSet("", this.getObjectUrlCallback(), set);
config.iconSet("", this.getObjectUrlCallback<string[]>(), cumulativeSet);
config.font("", "", cssIconSet);
config.font("", ClassResolver, cssIconSet);
config.sprite("", "", cssIconSet);
config.sprite("", ClassResolver, cssIconSet);
config.alias("", "");
config.sourceAlias("", "");
config.defaultIconSetUrl("");
config.defaultIconSetUrl("", set);
config.defaultSvgSetUrl("");
config.defaultSvgSetUrl("", set);
config.defaultSvgIconSetUrl("");
config.defaultSvgIconSetUrl("", set);
config.defaultSource("");
config.default("");
config.defaultSvgIconSize(1);
config.preload(
(loader) => {
// $ExpectType IconPreloader
loader;
});
config.ready(
(injector) => {
// $ExpectType Injector
injector;
});
});
/**
* Declaring urls
* Using a string
*/
setOptions.url =
setOptions.uri =
iconOptions.url =
iconOptions.uri = "";
/**
* Using an object
*/
setOptions.url =
setOptions.uri =
iconOptions.url =
iconOptions.uri = this.getUrlObject();
/**
* Using a function
* Returning a string
*/
setOptions.url =
setOptions.uri =
iconOptions.url =
iconOptions.uri = this.getStringUrlCallback();
/**
* Returning an object
*/
setOptions.url =
setOptions.uri =
iconOptions.url =
iconOptions.uri = this.getObjectUrlCallback();
/**
* Declaring class-resolvers
* Using a string
*/
cssIconSetOptions.className =
cssIconSetOptions.cssClass =
cssIconSetOptions.class = "";
/**
* Using a function
*/
cssIconSetOptions.className =
cssIconSetOptions.cssClass =
cssIconSetOptions.class = ClassResolver;
/**
* Setting icons
* Simple
*/
config.icons =
config.icon = {
clock: ""
};
/**
* Complex
*/
config.icons =
config.icon = {
clock: iconOptions
};
/**
* Array
*/
config.icons =
config.icon = [
idIconOptions
];
/**
* Setting svg-sets
* Simple
*/
config.svgSets =
config.svgSet =
config.iconSets =
config.iconSet = {
clock: ""
};
/**
* Complex
*/
config.svgSets =
config.svgSet =
config.iconSets =
config.iconSet = {
clock: setOptions,
alt: cumulativeSetOptions
};
/**
* Array
*/
config.svgSets =
config.svgSet =
config.iconSets =
config.iconSet = [
idSetOptions
];
/**
* Setting css-class icons
* Simple
*/
config.fonts =
config.font =
config.sprites =
config.sprite = {
clock: ""
};
/**
* Complex
*/
config.fonts =
config.font =
config.sprites =
config.sprite = {
clock: cssIconSetOptions
};
/**
* Array
*/
config.fonts =
config.font =
config.sprites =
config.sprite = [
idCssIconOptions
];
/**
* Setting aliases
* Simple
*/
config.alias =
config.sourceAlias = {
alt: "clock"
};
/**
* Complex
*/
config.alias =
config.sourceAlias = {
id: {
alias: ""
}
};
/**
* Array
*/
config.alias =
config.sourceAlias = [
{
id: "id",
alias: ""
}
];
/**
* Setting a default icon-set url
* Simple
*/
config.defaultIconSetUrl =
config.defaultSvgSetUrl =
config.defaultSvgIconSetUrl = "";
/**
* Complex
*/
config.defaultIconSetUrl =
config.defaultSvgSetUrl =
config.defaultSvgIconSetUrl = setOptions;
/**
* Setting a default icon-set
* Simple
*/
config.defaultSource =
config.default = "";
/**
* Complex
*/
config.defaultSource =
config.default = {
id: ""
};
/**
* Setting a default icon-size for vector-icons
* Simple
*/
config.defaultSvgIconSize = 1;
/**
* Complex
*/
config.defaultSvgIconSize = {
iconSize: 1,
size: 1,
svgIconSize: 1
};
$().webicons(config);
}
} | the_stack |
import * as React from 'react';
import * as Common from '../index';
import * as Styled from './styled';
const RestoreScrollOnMount = Common.createRestoreScrollOnMount();
export const createMoveExamples = (options: { useDistinctEnd: boolean; namePrefix: string }) => (
Motion: React.ComponentType<{ name: string; in?: boolean }>,
MotionComponent: React.ComponentType<{
[key: string]: any;
children: (opts: any) => React.ReactNode;
}>
) => ({
Default: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
{!shown ? (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-1`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItem ref={ref} onClick={() => toggle()} {...props} />
)}
</MotionComponent>
</Motion>
) : (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-2`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItemFloatingRight
ref={ref}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
{...props}
/>
)}
</MotionComponent>
</Motion>
)}
</div>
)}
</Common.Toggler>
),
WithAbsolutePositioning: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
<Styled.Padding />
{!shown ? (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-1`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.RelativeListItem ref={ref} onClick={() => toggle()} {...props} />
)}
</MotionComponent>
</Motion>
) : (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-2`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.AbsoluteListItem
ref={ref}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
{...props}
/>
)}
</MotionComponent>
</Motion>
)}
<Styled.Padding />
</div>
)}
</Common.Toggler>
),
WithFixedPositioning: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
<Styled.Padding />
{!shown ? (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-1`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.RelativeListItem ref={ref} onClick={() => toggle()} {...props} />
)}
</MotionComponent>
</Motion>
) : (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-2`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.FixedListItem
ref={ref}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
{...props}
/>
)}
</MotionComponent>
</Motion>
)}
<Styled.Padding />
</div>
)}
</Common.Toggler>
),
WithMargin: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
{!shown ? (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-1`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItem ref={ref} onClick={() => toggle()} {...props} />
)}
</MotionComponent>
</Motion>
) : (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-2`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItemFloatingRight
margin={100}
ref={ref}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
{...props}
/>
)}
</MotionComponent>
</Motion>
)}
</div>
)}
</Common.Toggler>
),
ToLarge: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
{!shown ? (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-1`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItem ref={ref} onClick={() => toggle()} {...props} />
)}
</MotionComponent>
</Motion>
) : (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-2`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItemFloatingRight
size={2}
ref={ref}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
{...props}
/>
)}
</MotionComponent>
</Motion>
)}
</div>
)}
</Common.Toggler>
),
ToLargeWithMargin: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
{!shown ? (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-1`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItem margin={20} ref={ref} onClick={() => toggle()} {...props} />
)}
</MotionComponent>
</Motion>
) : (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-2`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItemFloatingRight
size={2}
ref={ref}
margin={50}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
{...props}
/>
)}
</MotionComponent>
</Motion>
)}
</div>
)}
</Common.Toggler>
),
ToRectangle: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
{!shown ? (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-1`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItem ref={ref} onClick={() => toggle()} {...props} />
)}
</MotionComponent>
</Motion>
) : (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-2`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItemFloatingRight
width={2}
ref={ref}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
{...props}
/>
)}
</MotionComponent>
</Motion>
)}
</div>
)}
</Common.Toggler>
),
ToCircle: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
{!shown ? (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-1`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItem ref={ref} onClick={() => toggle()} {...props} />
)}
</MotionComponent>
</Motion>
) : (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-2`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItemFloatingRight
ref={ref}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
borderRadius="50%"
{...props}
/>
)}
</MotionComponent>
</Motion>
)}
</div>
)}
</Common.Toggler>
),
FromOffscreen: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
{!shown ? (
<div>
<Styled.Padding />
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-1`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItem ref={ref} onClick={() => toggle()} {...props} />
)}
</MotionComponent>
</Motion>
</div>
) : (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-2`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItemFloatingRight
ref={ref}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
{...props}
/>
)}
</MotionComponent>
</Motion>
)}
</div>
)}
</Common.Toggler>
),
ToOffscreen: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
{!shown ? (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-1`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItem ref={ref} onClick={() => toggle()} {...props} />
)}
</MotionComponent>
</Motion>
) : (
<div>
<Styled.Padding />
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-2`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItemFloatingRight
ref={ref}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
{...props}
/>
)}
</MotionComponent>
</Motion>
</div>
)}
</div>
)}
</Common.Toggler>
),
ToIndiscriminateSize: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
{!shown ? (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-1`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItem ref={ref} onClick={() => toggle()} {...props} />
)}
</MotionComponent>
</Motion>
) : (
<Styled.ContainerFloatingRight>
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-2`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItemFillSpace
ref={ref}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
{...props}
/>
)}
</MotionComponent>
</Motion>
</Styled.ContainerFloatingRight>
)}
</div>
)}
</Common.Toggler>
),
FromLongPage: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
{!shown ? (
<Styled.LongContainer>
<RestoreScrollOnMount />
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-1`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItem ref={ref} onClick={() => toggle()} {...props} />
)}
</MotionComponent>
</Motion>
</Styled.LongContainer>
) : (
<Motion name={`${options.namePrefix}-anim`} key={`${options.namePrefix}-2`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItemFloatingRight
ref={ref}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
{...props}
/>
)}
</MotionComponent>
</Motion>
)}
</div>
)}
</Common.Toggler>
),
FromAlwaysMounted: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
<Motion name={`${options.namePrefix}-default`} in={!shown}>
<MotionComponent>
{({ ref, style, ...props }) => (
<Styled.ListItem
ref={ref}
onClick={() => toggle()}
// !! CURRENT LIMITATION ALERT !!
// Consumers need to set their own opacity depending if it's shown or not.
style={{ ...style, opacity: shown ? 0 : style.opacity }}
{...props}
/>
)}
</MotionComponent>
</Motion>
{shown && (
<Motion name={`${options.namePrefix}-default`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItemFloatingRight
ref={ref}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
{...props}
/>
)}
</MotionComponent>
</Motion>
)}
</div>
)}
</Common.Toggler>
),
ToAlwaysMounted: () => (
<Common.Toggler>
{({ shown, toggle }) => (
<div>
{!shown && (
<Motion name={`${options.namePrefix}-default`}>
<MotionComponent>
{({ ref, ...props }) => (
<Styled.ListItem ref={ref} onClick={() => toggle()} {...props} />
)}
</MotionComponent>
</Motion>
)}
<Motion name={`${options.namePrefix}-default`} in={!!shown}>
<MotionComponent>
{({ ref, style, ...props }) => (
<Styled.ListItemFloatingRight
ref={ref}
onClick={() => toggle()}
alternate={options.useDistinctEnd}
// !! CURRENT LIMITATION ALERT !!
// Consumers need to set their own opacity depending if it's shown or not.
style={{ ...style, opacity: !shown ? 0 : style.opacity }}
{...props}
/>
)}
</MotionComponent>
</Motion>
</div>
)}
</Common.Toggler>
),
}); | the_stack |
module android.widget {
import ColorStateList = android.content.res.ColorStateList;
import Canvas = android.graphics.Canvas;
import Color = android.graphics.Color;
import Paint = android.graphics.Paint;
import Align = android.graphics.Paint.Align;
import Rect = android.graphics.Rect;
import Drawable = android.graphics.drawable.Drawable;
import TextUtils = android.text.TextUtils;
import SparseArray = android.util.SparseArray;
import TypedValue = android.util.TypedValue;
import KeyEvent = android.view.KeyEvent;
import MotionEvent = android.view.MotionEvent;
import VelocityTracker = android.view.VelocityTracker;
import View = android.view.View;
import ViewConfiguration = android.view.ViewConfiguration;
import DecelerateInterpolator = android.view.animation.DecelerateInterpolator;
import ArrayList = java.util.ArrayList;
import Collections = java.util.Collections;
import List = java.util.List;
import Integer = java.lang.Integer;
import StringBuilder = java.lang.StringBuilder;
import Runnable = java.lang.Runnable;
import Button = android.widget.Button;
import ImageButton = android.widget.ImageButton;
import LinearLayout = android.widget.LinearLayout;
import OverScroller = android.widget.OverScroller;
import Scroller = android.widget.OverScroller;
import TextView = android.widget.TextView;
import R = android.R;
import AttrBinder = androidui.attr.AttrBinder;
/**
* A widget that enables the user to select a number form a predefined range.
* There are two flavors of this widget and which one is presented to the user
* depends on the current theme.
* <ul>
* <li>
* If the current theme is derived from {@link android.R.style#Theme} the widget
* presents the current value as an editable input field with an increment button
* above and a decrement button below. Long pressing the buttons allows for a quick
* change of the current value. Tapping on the input field allows to type in
* a desired value.
* </li>
* <li>
* If the current theme is derived from {@link android.R.style#Theme_Holo} or
* {@link android.R.style#Theme_Holo_Light} the widget presents the current
* value as an editable input field with a lesser value above and a greater
* value below. Tapping on the lesser or greater value selects it by animating
* the number axis up or down to make the chosen value current. Flinging up
* or down allows for multiple increments or decrements of the current value.
* Long pressing on the lesser and greater values also allows for a quick change
* of the current value. Tapping on the current value allows to type in a
* desired value.
* </li>
* </ul>
* <p>
* For an example of using this widget, see {@link android.widget.TimePicker}.
* </p>
*/
export class NumberPicker extends LinearLayout {
/**
* The number of items show in the selector wheel.
*/
private SELECTOR_WHEEL_ITEM_COUNT:number = 3;
/**
* The default update interval during long press.
*/
private static DEFAULT_LONG_PRESS_UPDATE_INTERVAL:number = 300;
/**
* The index of the middle selector item.
*/
private SELECTOR_MIDDLE_ITEM_INDEX:number = Math.floor(this.SELECTOR_WHEEL_ITEM_COUNT / 2);
/**
* The coefficient by which to adjust (divide) the max fling velocity.
*/
private static SELECTOR_MAX_FLING_VELOCITY_ADJUSTMENT:number = 8;
/**
* The the duration for adjusting the selector wheel.
*/
private static SELECTOR_ADJUSTMENT_DURATION_MILLIS:number = 800;
/**
* The duration of scrolling while snapping to a given position.
*/
private static SNAP_SCROLL_DURATION:number = 300;
/**
* The strength of fading in the top and bottom while drawing the selector.
*/
private static TOP_AND_BOTTOM_FADING_EDGE_STRENGTH:number = 0.9;
/**
* The default unscaled height of the selection divider.
*/
private static UNSCALED_DEFAULT_SELECTION_DIVIDER_HEIGHT:number = 2;
/**
* The default unscaled distance between the selection dividers.
*/
private static UNSCALED_DEFAULT_SELECTION_DIVIDERS_DISTANCE:number = 48;
///**
// * The resource id for the default layout.
// */
//private static DEFAULT_LAYOUT_RESOURCE_ID:number = R.layout.number_picker;
/**
* Constant for unspecified size.
*/
private static SIZE_UNSPECIFIED:number = -1;
private static sTwoDigitFormatter:NumberPicker.TwoDigitFormatter;
/**
* @hide
*/
static getTwoDigitFormatter():NumberPicker.Formatter {
if(!NumberPicker.sTwoDigitFormatter){
NumberPicker.sTwoDigitFormatter = new NumberPicker.TwoDigitFormatter();
}
return NumberPicker.sTwoDigitFormatter;
}
///**
// * The increment button.
// */
//private mIncrementButton:ImageButton;
///**
// * The decrement button.
// */
//private mDecrementButton:ImageButton;
///**
// * The text for showing the current value.
// */
//private mInputText:EditText;
/**
* The distance between the two selection dividers.
*/
private mSelectionDividersDistance:number = 0;
/**
* The min height of this widget.
*/
private mMinHeight_:number = NumberPicker.SIZE_UNSPECIFIED;
/**
* The max height of this widget.
*/
private mMaxHeight:number = NumberPicker.SIZE_UNSPECIFIED;
/**
* The max width of this widget.
*/
private mMinWidth_:number = NumberPicker.SIZE_UNSPECIFIED;
/**
* The max width of this widget.
*/
private mMaxWidth:number = NumberPicker.SIZE_UNSPECIFIED;
/**
* Flag whether to compute the max width.
*/
private mComputeMaxWidth:boolean;
/**
* The height of the text.
*/
private mTextSize:number = 0;
/**
* The height of the gap between text elements if the selector wheel.
*/
private mSelectorTextGapHeight:number = 0;
/**
* The values to be displayed instead the indices.
*/
private mDisplayedValues:string[];
/**
* Lower value of the range of numbers allowed for the NumberPicker
*/
private mMinValue:number = 0;
/**
* Upper value of the range of numbers allowed for the NumberPicker
*/
private mMaxValue:number = 0;
/**
* Current value of this NumberPicker
*/
private mValue:number = 0;
/**
* Listener to be notified upon current value change.
*/
private mOnValueChangeListener:NumberPicker.OnValueChangeListener;
/**
* Listener to be notified upon scroll state change.
*/
private mOnScrollListener:NumberPicker.OnScrollListener;
/**
* Formatter for for displaying the current value.
*/
private mFormatter:NumberPicker.Formatter;
/**
* The speed for updating the value form long press.
*/
private mLongPressUpdateInterval:number = NumberPicker.DEFAULT_LONG_PRESS_UPDATE_INTERVAL;
/**
* Cache for the string representation of selector indices.
*/
private mSelectorIndexToStringCache:SparseArray<string> = new SparseArray<string>();
/**
* The selector indices whose value are show by the selector.
*/
private mSelectorIndices:number[];
/**
* The {@link Paint} for drawing the selector.
*/
private mSelectorWheelPaint:Paint;
/**
* The {@link Drawable} for pressed virtual (increment/decrement) buttons.
*/
private mVirtualButtonPressedDrawable:Drawable;
/**
* The height of a selector element (text + gap).
*/
private mSelectorElementHeight:number = 0;
/**
* The initial offset of the scroll selector.
*/
private mInitialScrollOffset:number = Integer.MIN_VALUE;
/**
* The current offset of the scroll selector.
*/
private mCurrentScrollOffset:number = 0;
/**
* The {@link Scroller} responsible for flinging the selector.
*/
private mFlingScroller:Scroller;
/**
* The {@link Scroller} responsible for adjusting the selector.
*/
private mAdjustScroller:Scroller;
/**
* The previous Y coordinate while scrolling the selector.
*/
private mPreviousScrollerY:number = 0;
/**
* Handle to the reusable command for setting the input text selection.
*/
private mSetSelectionCommand:NumberPicker.SetSelectionCommand;
/**
* Handle to the reusable command for changing the current value from long
* press by one.
*/
private mChangeCurrentByOneFromLongPressCommand:NumberPicker.ChangeCurrentByOneFromLongPressCommand;
/**
* Command for beginning an edit of the current value via IME on long press.
*/
private mBeginSoftInputOnLongPressCommand:NumberPicker.BeginSoftInputOnLongPressCommand;
/**
* The Y position of the last down event.
*/
private mLastDownEventY:number = 0;
/**
* The time of the last down event.
*/
private mLastDownEventTime:number = 0;
/**
* The Y position of the last down or move event.
*/
private mLastDownOrMoveEventY:number = 0;
/**
* Determines speed during touch scrolling.
*/
private mVelocityTracker:VelocityTracker;
/**
* @see ViewConfiguration#getScaledTouchSlop()
*/
//private mTouchSlop:number = 0;
/**
* @see ViewConfiguration#getScaledMinimumFlingVelocity()
*/
private mMinimumFlingVelocity:number = 0;
/**
* @see ViewConfiguration#getScaledMaximumFlingVelocity()
*/
private mMaximumFlingVelocity:number = 0;
/**
* Flag whether the selector should wrap around.
*/
private mWrapSelectorWheel:boolean;
/**
* The back ground color used to optimize scroller fading.
*/
private mSolidColor:number = 0;
/**
* Flag whether this widget has a selector wheel.
*/
private mHasSelectorWheel:boolean;
/**
* Divider for showing item to be selected while scrolling
*/
private mSelectionDivider:Drawable;
/**
* The height of the selection divider.
*/
private mSelectionDividerHeight:number = 0;
/**
* The current scroll state of the number picker.
*/
private mScrollState:number = NumberPicker.OnScrollListener.SCROLL_STATE_IDLE;
/**
* Flag whether to ignore move events - we ignore such when we show in IME
* to prevent the content from scrolling.
*/
private mIngonreMoveEvents:boolean;
/**
* Flag whether to show soft input on tap.
*/
private mShowSoftInputOnTap:boolean;
/**
* The top of the top selection divider.
*/
private mTopSelectionDividerTop:number = 0;
/**
* The bottom of the bottom selection divider.
*/
private mBottomSelectionDividerBottom:number = 0;
/**
* The virtual id of the last hovered child.
*/
private mLastHoveredChildVirtualViewId:number = 0;
/**
* Whether the increment virtual button is pressed.
*/
private mIncrementVirtualButtonPressed:boolean;
/**
* Whether the decrement virtual button is pressed.
*/
private mDecrementVirtualButtonPressed:boolean;
/**
* Provider to report to clients the semantic structure of this widget.
*/
//private mAccessibilityNodeProvider:NumberPicker.AccessibilityNodeProviderImpl;
/**
* Helper class for managing pressed state of the virtual buttons.
*/
private mPressedStateHelper:NumberPicker.PressedStateHelper;
/**
* The keycode of the last handled DPAD down event.
*/
private mLastHandledDownDpadKeyCode:number = -1;
/**
* Create a new number picker
*
* @param context the application environment.
* @param bindElement a collection of attributes.
* @param defStyle The default style to apply to this view.
*/
constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle=android.R.attr.numberPickerStyle) {
super(context, bindElement, defStyle);
// process style attributes
let attributesArray = context.obtainStyledAttributes(bindElement, defStyle);
// const layoutResId:number = attributesArray.getResourceId('internalLayout', NumberPicker.DEFAULT_LAYOUT_RESOURCE_ID);
this.mHasSelectorWheel = true; // (layoutResId != NumberPicker.DEFAULT_LAYOUT_RESOURCE_ID);
this.mSolidColor = attributesArray.getColor('solidColor', 0);
this.mSelectionDivider = attributesArray.getDrawable('selectionDivider');
const defSelectionDividerHeight:number = Math.floor(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, NumberPicker.UNSCALED_DEFAULT_SELECTION_DIVIDER_HEIGHT, this.getResources().getDisplayMetrics()));
this.mSelectionDividerHeight = attributesArray.getDimensionPixelSize('selectionDividerHeight', defSelectionDividerHeight);
const defSelectionDividerDistance:number = Math.floor(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, NumberPicker.UNSCALED_DEFAULT_SELECTION_DIVIDERS_DISTANCE, this.getResources().getDisplayMetrics()));
this.mSelectionDividersDistance = attributesArray.getDimensionPixelSize('selectionDividersDistance', defSelectionDividerDistance);
this.mMinHeight = attributesArray.getDimensionPixelSize('internalMinHeight', NumberPicker.SIZE_UNSPECIFIED);
this.mMaxHeight = attributesArray.getDimensionPixelSize('internalMaxHeight', NumberPicker.SIZE_UNSPECIFIED);
if (this.mMinHeight != NumberPicker.SIZE_UNSPECIFIED && this.mMaxHeight != NumberPicker.SIZE_UNSPECIFIED && this.mMinHeight > this.mMaxHeight) {
throw Error(`new IllegalArgumentException("minHeight > maxHeight")`);
}
this.mMinWidth = attributesArray.getDimensionPixelSize('internalMinWidth', NumberPicker.SIZE_UNSPECIFIED);
this.mMaxWidth = attributesArray.getDimensionPixelSize('internalMaxWidth', NumberPicker.SIZE_UNSPECIFIED);
if (this.mMinWidth != NumberPicker.SIZE_UNSPECIFIED && this.mMaxWidth != NumberPicker.SIZE_UNSPECIFIED && this.mMinWidth > this.mMaxWidth) {
throw Error(`new IllegalArgumentException("minWidth > maxWidth")`);
}
this.mComputeMaxWidth = (this.mMaxWidth == NumberPicker.SIZE_UNSPECIFIED);
this.mVirtualButtonPressedDrawable = attributesArray.getDrawable('virtualButtonPressedDrawable');
this.mTextSize = attributesArray.getDimensionPixelSize('textSize', Math.floor(16 * this.getResources().getDisplayMetrics().density)); // AndroidUIX modify
// create the selector wheel paint
let paint:Paint = new Paint();
paint.setAntiAlias(true);
paint.setTextAlign(Align.CENTER);
paint.setTextSize(this.mTextSize);
//paint.setTypeface(this.mInputText.getTypeface());
//let colors:ColorStateList = this.mInputText.getTextColors();
paint.setColor(attributesArray.getColor('textColor', Color.DKGRAY)); // AndroidUIX modify
this.mSelectorWheelPaint = paint;
this.SELECTOR_WHEEL_ITEM_COUNT = attributesArray.getInt('itemCount', this.SELECTOR_WHEEL_ITEM_COUNT); // AndroidUIX modify
this.SELECTOR_MIDDLE_ITEM_INDEX = Math.floor(this.SELECTOR_WHEEL_ITEM_COUNT / 2); // AndroidUIX modify
this.mSelectorIndices = androidui.util.ArrayCreator.newNumberArray(this.SELECTOR_WHEEL_ITEM_COUNT);
if (this.mMinHeight_ != NumberPicker.SIZE_UNSPECIFIED && this.mMaxHeight != NumberPicker.SIZE_UNSPECIFIED && this.mMinHeight_ > this.mMaxHeight) {
throw Error(`new IllegalArgumentException("minHeight > maxHeight")`);
}
if (this.mMinWidth_ != NumberPicker.SIZE_UNSPECIFIED && this.mMaxWidth != NumberPicker.SIZE_UNSPECIFIED && this.mMinWidth_ > this.mMaxWidth) {
throw Error(`new IllegalArgumentException("minWidth > maxWidth")`);
}
this.mComputeMaxWidth = (this.mMaxWidth == NumberPicker.SIZE_UNSPECIFIED);
this.setMinValue(attributesArray.getInt('minValue', this.mMinValue)); // AndroidUIX modify
this.setMaxValue(attributesArray.getInt('maxValue', this.mMaxValue)); // AndroidUIX modify
attributesArray.recycle();
this.mPressedStateHelper = new NumberPicker.PressedStateHelper(this);
// By default Linearlayout that we extend is not drawn. This is
// its draw() method is not called but dispatchDraw() is called
// directly (see ViewGroup.drawChild()). However, this class uses
// the fading edge effect implemented by View and we need our
// draw() method to be called. Therefore, we declare we will draw.
this.setWillNotDraw(!this.mHasSelectorWheel);
//let inflater:LayoutInflater = <LayoutInflater> this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//inflater.inflate(layoutResId, this, true);
//let onClickListener:View.OnClickListener = (()=>{
// const inner_this=this;
// class _Inner implements View.OnClickListener {
// onClick(v:View):void {
// inner_this.hideSoftInput();
// inner_this.mInputText.clearFocus();
// if (v.getId() == R.id.increment) {
// inner_this.changeValueByOne(true);
// } else {
// inner_this.changeValueByOne(false);
// }
// }
// }
// return new _Inner();
//})();
//let onLongClickListener:View.OnLongClickListener = (()=>{
// const inner_this=this;
// class _Inner implements View.OnLongClickListener {
//
// onLongClick(v:View):boolean {
// this.hideSoftInput();
// this.mInputText.clearFocus();
// if (v.getId() == R.id.increment) {
// this.postChangeCurrentByOneFromLongPress(true, 0);
// } else {
// this.postChangeCurrentByOneFromLongPress(false, 0);
// }
// return true;
// }
// }
// return new _Inner(this);
//})();
//// increment button
//if (!this.mHasSelectorWheel) {
// this.mIncrementButton = <ImageButton> this.findViewById(R.id.increment);
// this.mIncrementButton.setOnClickListener(onClickListener);
// this.mIncrementButton.setOnLongClickListener(onLongClickListener);
//} else {
// this.mIncrementButton = null;
//}
//// decrement button
//if (!this.mHasSelectorWheel) {
// this.mDecrementButton = <ImageButton> this.findViewById(R.id.decrement);
// this.mDecrementButton.setOnClickListener(onClickListener);
// this.mDecrementButton.setOnLongClickListener(onLongClickListener);
//} else {
// this.mDecrementButton = null;
//}
// input text
//this.mInputText = <EditText> this.findViewById(R.id.numberpicker_input);
//this.mInputText.setOnFocusChangeListener((()=>{
// const inner_this=this;
// class _Inner extends View.OnFocusChangeListener {
//
// onFocusChange(v:View, hasFocus:boolean):void {
// if (hasFocus) {
// this.mInputText.selectAll();
// } else {
// this.mInputText.setSelection(0, 0);
// this.validateInputTextView(v);
// }
// }
// }
// return new _Inner(this);
//})());
//this.mInputText.setFilters( [ new NumberPicker.InputTextFilter(this) ]);
//this.mInputText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
//this.mInputText.setImeOptions(EditorInfo.IME_ACTION_DONE);
// initialize constants
let configuration:ViewConfiguration = ViewConfiguration.get();
//this.mTouchSlop = configuration.getScaledTouchSlop();
this.mMinimumFlingVelocity = configuration.getScaledMinimumFlingVelocity();
this.mMaximumFlingVelocity = configuration.getScaledMaximumFlingVelocity() / NumberPicker.SELECTOR_MAX_FLING_VELOCITY_ADJUSTMENT;
// create the fling and adjust scrollers
this.mFlingScroller = new OverScroller(null, true);
this.mAdjustScroller = new OverScroller(new DecelerateInterpolator(2.5));
this.updateInputTextView();
// If not explicitly specified this view is important for accessibility.
//if (this.getImportantForAccessibility() == NumberPicker.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
// this.setImportantForAccessibility(NumberPicker.IMPORTANT_FOR_ACCESSIBILITY_YES);
//}
}
protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap {
return super.createClassAttrBinder().set('solidColor', {
setter(v:NumberPicker, value:any, attrBinder:AttrBinder) {
v.mSolidColor = attrBinder.parseColor(value, v.mSolidColor);
v.invalidate();
}, getter(v:NumberPicker) {
return v.mSolidColor;
}
}).set('selectionDivider', {
setter(v:NumberPicker, value:any, attrBinder:AttrBinder) {
v.mSelectionDivider = attrBinder.parseDrawable(value);
v.invalidate();
}, getter(v:NumberPicker) {
return v.mSelectionDivider;
}
}).set('selectionDividerHeight', {
setter(v:NumberPicker, value:any, attrBinder:AttrBinder) {
v.mSelectionDividerHeight = attrBinder.parseNumberPixelSize(value, v.mSelectionDividerHeight);
v.invalidate();
}, getter(v:NumberPicker) {
return v.mSelectionDividerHeight;
}
}).set('selectionDividersDistance', {
setter(v:NumberPicker, value:any, attrBinder:AttrBinder) {
v.mSelectionDividersDistance = attrBinder.parseNumberPixelSize(value, v.mSelectionDividersDistance);
v.invalidate();
}, getter(v:NumberPicker) {
return v.mSelectionDividersDistance;
}
}).set('internalMinHeight', {
setter(v:NumberPicker, value:any, attrBinder:AttrBinder) {
v.mMinHeight_ = attrBinder.parseNumberPixelSize(value, v.mMinHeight_);
v.invalidate();
}, getter(v:NumberPicker) {
return v.mMinHeight_;
}
}).set('internalMaxHeight', {
setter(v:NumberPicker, value:any, attrBinder:AttrBinder) {
v.mMaxHeight = attrBinder.parseNumberPixelSize(value, v.mMaxHeight);
v.invalidate();
}, getter(v:NumberPicker) {
return v.mMaxHeight;
}
}).set('internalMinWidth', {
setter(v:NumberPicker, value:any, attrBinder:AttrBinder) {
v.mMinWidth_ = attrBinder.parseNumberPixelSize(value, v.mMinWidth_);
v.invalidate();
}, getter(v:NumberPicker) {
return v.mMinWidth_;
}
}).set('internalMaxWidth', {
setter(v:NumberPicker, value:any, attrBinder:AttrBinder) {
v.mMaxWidth = attrBinder.parseNumberPixelSize(value, v.mMaxWidth);
v.invalidate();
}, getter(v:NumberPicker) {
return v.mMaxWidth;
}
}).set('virtualButtonPressedDrawable', {
setter(v:NumberPicker, value:any, attrBinder:AttrBinder) {
v.mVirtualButtonPressedDrawable = attrBinder.parseDrawable(value);
v.invalidate();
}, getter(v:NumberPicker) {
return v.mVirtualButtonPressedDrawable;
}
});
}
protected onLayout(changed:boolean, left:number, top:number, right:number, bottom:number):void {
if (!this.mHasSelectorWheel) {
super.onLayout(changed, left, top, right, bottom);
return;
}
const msrdWdth:number = this.getMeasuredWidth();
const msrdHght:number = this.getMeasuredHeight();
// Input text centered horizontally.
//const inptTxtMsrdWdth:number = this.mInputText.getMeasuredWidth();
//const inptTxtMsrdHght:number = this.mInputText.getMeasuredHeight();
//const inptTxtLeft:number = (msrdWdth - inptTxtMsrdWdth) / 2;
//const inptTxtTop:number = (msrdHght - inptTxtMsrdHght) / 2;
//const inptTxtRight:number = inptTxtLeft + inptTxtMsrdWdth;
//const inptTxtBottom:number = inptTxtTop + inptTxtMsrdHght;
//this.mInputText.layout(inptTxtLeft, inptTxtTop, inptTxtRight, inptTxtBottom);
if (changed) {
// need to do all this when we know our size
this.initializeSelectorWheel();
this.initializeFadingEdges();
this.mTopSelectionDividerTop = (this.getHeight() - this.mSelectionDividersDistance) / 2 - this.mSelectionDividerHeight;
this.mBottomSelectionDividerBottom = this.mTopSelectionDividerTop + 2 * this.mSelectionDividerHeight + this.mSelectionDividersDistance;
}
}
protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void {
if (!this.mHasSelectorWheel) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
// Try greedily to fit the max width and height.
const newWidthMeasureSpec:number = this.makeMeasureSpec(widthMeasureSpec, this.mMaxWidth);
const newHeightMeasureSpec:number = this.makeMeasureSpec(heightMeasureSpec, this.mMaxHeight);
super.onMeasure(newWidthMeasureSpec, newHeightMeasureSpec);
// Flag if we are measured with width or height less than the respective min.
const widthSize:number = this.resolveSizeAndStateRespectingMinSize(this.mMinWidth_, this.getMeasuredWidth(), widthMeasureSpec);
const heightSize:number = this.resolveSizeAndStateRespectingMinSize(this.mMinHeight_, this.getMeasuredHeight(), heightMeasureSpec);
this.setMeasuredDimension(widthSize, heightSize);
}
/**
* Move to the final position of a scroller. Ensures to force finish the scroller
* and if it is not at its final position a scroll of the selector wheel is
* performed to fast forward to the final position.
*
* @param scroller The scroller to whose final position to get.
* @return True of the a move was performed, i.e. the scroller was not in final position.
*/
private moveToFinalScrollerPosition(scroller:Scroller):boolean {
scroller.forceFinished(true);
let amountToScroll:number = scroller.getFinalY() - scroller.getCurrY();
let futureScrollOffset:number = (this.mCurrentScrollOffset + amountToScroll) % this.mSelectorElementHeight;
let overshootAdjustment:number = this.mInitialScrollOffset - futureScrollOffset;
if (overshootAdjustment != 0) {
if (Math.abs(overshootAdjustment) > this.mSelectorElementHeight / 2) {
if (overshootAdjustment > 0) {
overshootAdjustment -= this.mSelectorElementHeight;
} else {
overshootAdjustment += this.mSelectorElementHeight;
}
}
amountToScroll += overshootAdjustment;
this.scrollBy(0, amountToScroll);
return true;
}
return false;
}
onInterceptTouchEvent(event:MotionEvent):boolean {
if (!this.mHasSelectorWheel || !this.isEnabled()) {
return false;
}
const action:number = event.getActionMasked();
switch(action) {
case MotionEvent.ACTION_DOWN:
{
this.removeAllCallbacks();
//this.mInputText.setVisibility(View.INVISIBLE);
this.mLastDownOrMoveEventY = this.mLastDownEventY = event.getY();
this.mLastDownEventTime = event.getEventTime();
this.mIngonreMoveEvents = false;
this.mShowSoftInputOnTap = false;
// Handle pressed state before any state change.
if (this.mLastDownEventY < this.mTopSelectionDividerTop) {
if (this.mScrollState == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE) {
this.mPressedStateHelper.buttonPressDelayed(NumberPicker.PressedStateHelper.BUTTON_DECREMENT);
}
} else if (this.mLastDownEventY > this.mBottomSelectionDividerBottom) {
if (this.mScrollState == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE) {
this.mPressedStateHelper.buttonPressDelayed(NumberPicker.PressedStateHelper.BUTTON_INCREMENT);
}
}
// Make sure we support flinging inside scrollables.
this.getParent().requestDisallowInterceptTouchEvent(true);
if (!this.mFlingScroller.isFinished()) {
this.mFlingScroller.forceFinished(true);
this.mAdjustScroller.forceFinished(true);
this.onScrollStateChange(NumberPicker.OnScrollListener.SCROLL_STATE_IDLE);
} else if (!this.mAdjustScroller.isFinished()) {
this.mFlingScroller.forceFinished(true);
this.mAdjustScroller.forceFinished(true);
} else if (this.mLastDownEventY < this.mTopSelectionDividerTop) {
this.hideSoftInput();
this.postChangeCurrentByOneFromLongPress(false, ViewConfiguration.getLongPressTimeout());
} else if (this.mLastDownEventY > this.mBottomSelectionDividerBottom) {
this.hideSoftInput();
this.postChangeCurrentByOneFromLongPress(true, ViewConfiguration.getLongPressTimeout());
} else {
this.mShowSoftInputOnTap = true;
this.postBeginSoftInputOnLongPressCommand();
}
return true;
}
}
return false;
}
onTouchEvent(event:MotionEvent):boolean {
if (!this.isEnabled() || !this.mHasSelectorWheel) {
return false;
}
if (this.mVelocityTracker == null) {
this.mVelocityTracker = VelocityTracker.obtain();
}
this.mVelocityTracker.addMovement(event);
let action:number = event.getActionMasked();
switch(action) {
case MotionEvent.ACTION_MOVE:
{
if (this.mIngonreMoveEvents) {
break;
}
let currentMoveY:number = event.getY();
if (this.mScrollState != NumberPicker.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
let deltaDownY:number = Math.floor(Math.abs(currentMoveY - this.mLastDownEventY));
if (deltaDownY > this.mTouchSlop) {
this.removeAllCallbacks();
this.onScrollStateChange(NumberPicker.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
} else {
let deltaMoveY:number = Math.floor(((currentMoveY - this.mLastDownOrMoveEventY)));
this.scrollBy(0, deltaMoveY);
this.invalidate();
}
this.mLastDownOrMoveEventY = currentMoveY;
}
break;
case MotionEvent.ACTION_UP:
{
this.removeBeginSoftInputCommand();
this.removeChangeCurrentByOneFromLongPress();
this.mPressedStateHelper.cancel();
let velocityTracker:VelocityTracker = this.mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, this.mMaximumFlingVelocity);
let initialVelocity:number = Math.floor(velocityTracker.getYVelocity());
if (Math.abs(initialVelocity) > this.mMinimumFlingVelocity) {
this.fling(initialVelocity);
this.onScrollStateChange(NumberPicker.OnScrollListener.SCROLL_STATE_FLING);
} else {
let eventY:number = Math.floor(event.getY());
let deltaMoveY:number = Math.floor(Math.abs(eventY - this.mLastDownEventY));
let deltaTime:number = event.getEventTime() - this.mLastDownEventTime;
if (deltaMoveY <= this.mTouchSlop && deltaTime < ViewConfiguration.getTapTimeout()) {
if (this.mShowSoftInputOnTap) {
this.mShowSoftInputOnTap = false;
this.showSoftInput();
} else {
let selectorIndexOffset:number = (eventY / this.mSelectorElementHeight) - this.SELECTOR_MIDDLE_ITEM_INDEX;
if (selectorIndexOffset > 0) {
this.changeValueByOne(true);
this.mPressedStateHelper.buttonTapped(NumberPicker.PressedStateHelper.BUTTON_INCREMENT);
} else if (selectorIndexOffset < 0) {
this.changeValueByOne(false);
this.mPressedStateHelper.buttonTapped(NumberPicker.PressedStateHelper.BUTTON_DECREMENT);
}
}
} else {
this.ensureScrollWheelAdjusted();
}
this.onScrollStateChange(NumberPicker.OnScrollListener.SCROLL_STATE_IDLE);
}
this.mVelocityTracker.recycle();
this.mVelocityTracker = null;
}
break;
}
return true;
}
dispatchTouchEvent(event:MotionEvent):boolean {
const action:number = event.getActionMasked();
switch(action) {
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
this.removeAllCallbacks();
break;
}
return super.dispatchTouchEvent(event);
}
dispatchKeyEvent(event:KeyEvent):boolean {
const keyCode:number = event.getKeyCode();
switch(keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
this.removeAllCallbacks();
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
if (!this.mHasSelectorWheel) {
break;
}
switch(event.getAction()) {
case KeyEvent.ACTION_DOWN:
if (this.mWrapSelectorWheel || (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) ? this.getValue() < this.getMaxValue() : this.getValue() > this.getMinValue()) {
this.requestFocus();
this.mLastHandledDownDpadKeyCode = keyCode;
this.removeAllCallbacks();
if (this.mFlingScroller.isFinished()) {
this.changeValueByOne(keyCode == KeyEvent.KEYCODE_DPAD_DOWN);
}
return true;
}
break;
case KeyEvent.ACTION_UP:
if (this.mLastHandledDownDpadKeyCode == keyCode) {
this.mLastHandledDownDpadKeyCode = -1;
return true;
}
break;
}
}
return super.dispatchKeyEvent(event);
}
//dispatchTrackballEvent(event:MotionEvent):boolean {
// const action:number = event.getActionMasked();
// switch(action) {
// case MotionEvent.ACTION_CANCEL:
// case MotionEvent.ACTION_UP:
// this.removeAllCallbacks();
// break;
// }
// return super.dispatchTrackballEvent(event);
//}
//protected dispatchHoverEvent(event:MotionEvent):boolean {
// if (!this.mHasSelectorWheel) {
// return super.dispatchHoverEvent(event);
// }
// if (AccessibilityManager.getInstance(this.mContext).isEnabled()) {
// const eventY:number = Math.floor(event.getY());
// let hoveredVirtualViewId:number;
// if (eventY < this.mTopSelectionDividerTop) {
// hoveredVirtualViewId = NumberPicker.AccessibilityNodeProviderImpl.VIRTUAL_VIEW_ID_DECREMENT;
// } else if (eventY > this.mBottomSelectionDividerBottom) {
// hoveredVirtualViewId = NumberPicker.AccessibilityNodeProviderImpl.VIRTUAL_VIEW_ID_INCREMENT;
// } else {
// hoveredVirtualViewId = NumberPicker.AccessibilityNodeProviderImpl.VIRTUAL_VIEW_ID_INPUT;
// }
// const action:number = event.getActionMasked();
// let provider:NumberPicker.AccessibilityNodeProviderImpl = <NumberPicker.AccessibilityNodeProviderImpl> this.getAccessibilityNodeProvider();
// switch(action) {
// case MotionEvent.ACTION_HOVER_ENTER:
// {
// provider.sendAccessibilityEventForVirtualView(hoveredVirtualViewId, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
// this.mLastHoveredChildVirtualViewId = hoveredVirtualViewId;
// provider.performAction(hoveredVirtualViewId, AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, null);
// }
// break;
// case MotionEvent.ACTION_HOVER_MOVE:
// {
// if (this.mLastHoveredChildVirtualViewId != hoveredVirtualViewId && this.mLastHoveredChildVirtualViewId != View.NO_ID) {
// provider.sendAccessibilityEventForVirtualView(this.mLastHoveredChildVirtualViewId, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
// provider.sendAccessibilityEventForVirtualView(hoveredVirtualViewId, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
// this.mLastHoveredChildVirtualViewId = hoveredVirtualViewId;
// provider.performAction(hoveredVirtualViewId, AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, null);
// }
// }
// break;
// case MotionEvent.ACTION_HOVER_EXIT:
// {
// provider.sendAccessibilityEventForVirtualView(hoveredVirtualViewId, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
// this.mLastHoveredChildVirtualViewId = View.NO_ID;
// }
// break;
// }
// }
// return false;
//}
computeScroll():void {
let scroller:Scroller = this.mFlingScroller;
if (scroller.isFinished()) {
scroller = this.mAdjustScroller;
if (scroller.isFinished()) {
return;
}
}
scroller.computeScrollOffset();
let currentScrollerY:number = scroller.getCurrY();
if (this.mPreviousScrollerY == 0) {
this.mPreviousScrollerY = scroller.getStartY();
}
this.scrollBy(0, currentScrollerY - this.mPreviousScrollerY);
this.mPreviousScrollerY = currentScrollerY;
if (scroller.isFinished()) {
this.onScrollerFinished(scroller);
} else {
this.invalidate();
}
}
setEnabled(enabled:boolean):void {
super.setEnabled(enabled);
if (!this.mHasSelectorWheel) {
//this.mIncrementButton.setEnabled(enabled);
}
if (!this.mHasSelectorWheel) {
//this.mDecrementButton.setEnabled(enabled);
}
//this.mInputText.setEnabled(enabled);
}
scrollBy(x:number, y:number):void {
let selectorIndices:number[] = this.mSelectorIndices;
if (!this.mWrapSelectorWheel && y > 0 && selectorIndices[this.SELECTOR_MIDDLE_ITEM_INDEX] <= this.mMinValue) {
this.mCurrentScrollOffset = this.mInitialScrollOffset;
return;
}
if (!this.mWrapSelectorWheel && y < 0 && selectorIndices[this.SELECTOR_MIDDLE_ITEM_INDEX] >= this.mMaxValue) {
this.mCurrentScrollOffset = this.mInitialScrollOffset;
return;
}
this.mCurrentScrollOffset += y;
while (this.mCurrentScrollOffset - this.mInitialScrollOffset > this.mSelectorTextGapHeight) {
this.mCurrentScrollOffset -= this.mSelectorElementHeight;
this.decrementSelectorIndices(selectorIndices);
this.setValueInternal(selectorIndices[this.SELECTOR_MIDDLE_ITEM_INDEX], true);
if (!this.mWrapSelectorWheel && selectorIndices[this.SELECTOR_MIDDLE_ITEM_INDEX] <= this.mMinValue) {
this.mCurrentScrollOffset = this.mInitialScrollOffset;
}
}
while (this.mCurrentScrollOffset - this.mInitialScrollOffset < -this.mSelectorTextGapHeight) {
this.mCurrentScrollOffset += this.mSelectorElementHeight;
this.incrementSelectorIndices(selectorIndices);
this.setValueInternal(selectorIndices[this.SELECTOR_MIDDLE_ITEM_INDEX], true);
if (!this.mWrapSelectorWheel && selectorIndices[this.SELECTOR_MIDDLE_ITEM_INDEX] >= this.mMaxValue) {
this.mCurrentScrollOffset = this.mInitialScrollOffset;
}
}
}
protected computeVerticalScrollOffset():number {
return this.mCurrentScrollOffset;
}
protected computeVerticalScrollRange():number {
return (this.mMaxValue - this.mMinValue + 1) * this.mSelectorElementHeight;
}
protected computeVerticalScrollExtent():number {
return this.getHeight();
}
getSolidColor():number {
return this.mSolidColor;
}
/**
* Sets the listener to be notified on change of the current value.
*
* @param onValueChangedListener The listener.
*/
setOnValueChangedListener(onValueChangedListener:NumberPicker.OnValueChangeListener):void {
this.mOnValueChangeListener = onValueChangedListener;
}
/**
* Set listener to be notified for scroll state changes.
*
* @param onScrollListener The listener.
*/
setOnScrollListener(onScrollListener:NumberPicker.OnScrollListener):void {
this.mOnScrollListener = onScrollListener;
}
/**
* Set the formatter to be used for formatting the current value.
* <p>
* Note: If you have provided alternative values for the values this
* formatter is never invoked.
* </p>
*
* @param formatter The formatter object. If formatter is <code>null</code>,
* {@link String#valueOf(int)} will be used.
*@see #setDisplayedValues(String[])
*/
setFormatter(formatter:NumberPicker.Formatter):void {
if (formatter == this.mFormatter) {
return;
}
this.mFormatter = formatter;
this.initializeSelectorWheelIndices();
this.updateInputTextView();
}
/**
* Set the current value for the number picker.
* <p>
* If the argument is less than the {@link NumberPicker#getMinValue()} and
* {@link NumberPicker#getWrapSelectorWheel()} is <code>false</code> the
* current value is set to the {@link NumberPicker#getMinValue()} value.
* </p>
* <p>
* If the argument is less than the {@link NumberPicker#getMinValue()} and
* {@link NumberPicker#getWrapSelectorWheel()} is <code>true</code> the
* current value is set to the {@link NumberPicker#getMaxValue()} value.
* </p>
* <p>
* If the argument is less than the {@link NumberPicker#getMaxValue()} and
* {@link NumberPicker#getWrapSelectorWheel()} is <code>false</code> the
* current value is set to the {@link NumberPicker#getMaxValue()} value.
* </p>
* <p>
* If the argument is less than the {@link NumberPicker#getMaxValue()} and
* {@link NumberPicker#getWrapSelectorWheel()} is <code>true</code> the
* current value is set to the {@link NumberPicker#getMinValue()} value.
* </p>
*
* @param value The current value.
* @see #setWrapSelectorWheel(boolean)
* @see #setMinValue(int)
* @see #setMaxValue(int)
*/
setValue(value:number):void {
this.setValueInternal(value, false);
}
/**
* Shows the soft input for its input text.
*/
private showSoftInput():void {
//let inputMethodManager:InputMethodManager = InputMethodManager.peekInstance();
//if (inputMethodManager != null) {
// if (this.mHasSelectorWheel) {
// this.mInputText.setVisibility(View.VISIBLE);
// }
// this.mInputText.requestFocus();
// inputMethodManager.showSoftInput(this.mInputText, 0);
//}
}
/**
* Hides the soft input if it is active for the input text.
*/
private hideSoftInput():void {
//let inputMethodManager:InputMethodManager = InputMethodManager.peekInstance();
//if (inputMethodManager != null && inputMethodManager.isActive(this.mInputText)) {
// inputMethodManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
// if (this.mHasSelectorWheel) {
// this.mInputText.setVisibility(View.INVISIBLE);
// }
//}
}
/**
* Computes the max width if no such specified as an attribute.
*/
private tryComputeMaxWidth():void {
if (!this.mComputeMaxWidth) {
return;
}
let maxTextWidth:number = 0;
if (this.mDisplayedValues == null) {
let maxDigitWidth:number = 0;
for (let i:number = 0; i <= 9; i++) {
const digitWidth:number = this.mSelectorWheelPaint.measureText(NumberPicker.formatNumberWithLocale(i));
if (digitWidth > maxDigitWidth) {
maxDigitWidth = digitWidth;
}
}
let numberOfDigits:number = 0;
let current:number = this.mMaxValue;
while (current > 0) {
numberOfDigits++;
current = current / 10;
}
maxTextWidth = Math.floor((numberOfDigits * maxDigitWidth));
} else {
const valueCount:number = this.mDisplayedValues.length;
for (let i:number = 0; i < valueCount; i++) {
const textWidth:number = this.mSelectorWheelPaint.measureText(this.mDisplayedValues[i]);
if (textWidth > maxTextWidth) {
maxTextWidth = Math.floor(textWidth);
}
}
}
//maxTextWidth += this.mInputText.getPaddingLeft() + this.mInputText.getPaddingRight();
if (this.mMaxWidth != maxTextWidth) {
if (maxTextWidth > this.mMinWidth_) {
this.mMaxWidth = maxTextWidth;
} else {
this.mMaxWidth = this.mMinWidth_;
}
this.invalidate();
}
}
/**
* Gets whether the selector wheel wraps when reaching the min/max value.
*
* @return True if the selector wheel wraps.
*
* @see #getMinValue()
* @see #getMaxValue()
*/
getWrapSelectorWheel():boolean {
return this.mWrapSelectorWheel;
}
/**
* Sets whether the selector wheel shown during flinging/scrolling should
* wrap around the {@link NumberPicker#getMinValue()} and
* {@link NumberPicker#getMaxValue()} values.
* <p>
* By default if the range (max - min) is more than the number of items shown
* on the selector wheel the selector wheel wrapping is enabled.
* </p>
* <p>
* <strong>Note:</strong> If the number of items, i.e. the range (
* {@link #getMaxValue()} - {@link #getMinValue()}) is less than
* the number of items shown on the selector wheel, the selector wheel will
* not wrap. Hence, in such a case calling this method is a NOP.
* </p>
*
* @param wrapSelectorWheel Whether to wrap.
*/
setWrapSelectorWheel(wrapSelectorWheel:boolean):void {
const wrappingAllowed:boolean = (this.mMaxValue - this.mMinValue) >= this.mSelectorIndices.length;
if ((!wrapSelectorWheel || wrappingAllowed) && wrapSelectorWheel != this.mWrapSelectorWheel) {
this.mWrapSelectorWheel = wrapSelectorWheel;
}
}
/**
* Sets the speed at which the numbers be incremented and decremented when
* the up and down buttons are long pressed respectively.
* <p>
* The default value is 300 ms.
* </p>
*
* @param intervalMillis The speed (in milliseconds) at which the numbers
* will be incremented and decremented.
*/
setOnLongPressUpdateInterval(intervalMillis:number):void {
this.mLongPressUpdateInterval = intervalMillis;
}
/**
* Returns the value of the picker.
*
* @return The value.
*/
getValue():number {
return this.mValue;
}
/**
* Returns the min value of the picker.
*
* @return The min value
*/
getMinValue():number {
return this.mMinValue;
}
/**
* Sets the min value of the picker.
*
* @param minValue The min value inclusive.
*
* <strong>Note:</strong> The length of the displayed values array
* set via {@link #setDisplayedValues(String[])} must be equal to the
* range of selectable numbers which is equal to
* {@link #getMaxValue()} - {@link #getMinValue()} + 1.
*/
setMinValue(minValue:number):void {
if (this.mMinValue == minValue) {
return;
}
if (minValue < 0) {
throw Error(`new IllegalArgumentException("minValue must be >= 0")`);
}
this.mMinValue = minValue;
if (this.mMinValue > this.mValue) {
this.mValue = this.mMinValue;
}
let wrapSelectorWheel:boolean = this.mMaxValue - this.mMinValue > this.mSelectorIndices.length;
this.setWrapSelectorWheel(wrapSelectorWheel);
this.initializeSelectorWheelIndices();
this.updateInputTextView();
this.tryComputeMaxWidth();
this.invalidate();
}
/**
* Returns the max value of the picker.
*
* @return The max value.
*/
getMaxValue():number {
return this.mMaxValue;
}
/**
* Sets the max value of the picker.
*
* @param maxValue The max value inclusive.
*
* <strong>Note:</strong> The length of the displayed values array
* set via {@link #setDisplayedValues(String[])} must be equal to the
* range of selectable numbers which is equal to
* {@link #getMaxValue()} - {@link #getMinValue()} + 1.
*/
setMaxValue(maxValue:number):void {
if (this.mMaxValue == maxValue) {
return;
}
if (maxValue < 0) {
throw Error(`new IllegalArgumentException("maxValue must be >= 0")`);
}
this.mMaxValue = maxValue;
if (this.mMaxValue < this.mValue) {
this.mValue = this.mMaxValue;
}
let wrapSelectorWheel:boolean = this.mMaxValue - this.mMinValue > this.mSelectorIndices.length;
this.setWrapSelectorWheel(wrapSelectorWheel);
this.initializeSelectorWheelIndices();
this.updateInputTextView();
this.tryComputeMaxWidth();
this.invalidate();
}
/**
* Gets the values to be displayed instead of string values.
*
* @return The displayed values.
*/
getDisplayedValues():string[] {
return this.mDisplayedValues;
}
/**
* Sets the values to be displayed.
*
* @param displayedValues The displayed values.
*
* <strong>Note:</strong> The length of the displayed values array
* must be equal to the range of selectable numbers which is equal to
* {@link #getMaxValue()} - {@link #getMinValue()} + 1.
*/
setDisplayedValues(displayedValues:string[]):void {
if (this.mDisplayedValues == displayedValues) {
return;
}
this.mDisplayedValues = displayedValues;
if (this.mDisplayedValues != null) {
// Allow text entry rather than strictly numeric entry.
//this.mInputText.setRawInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
} else {
//this.mInputText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
}
this.updateInputTextView();
this.initializeSelectorWheelIndices();
this.tryComputeMaxWidth();
}
protected getTopFadingEdgeStrength():number {
return NumberPicker.TOP_AND_BOTTOM_FADING_EDGE_STRENGTH;
}
protected getBottomFadingEdgeStrength():number {
return NumberPicker.TOP_AND_BOTTOM_FADING_EDGE_STRENGTH;
}
protected onDetachedFromWindow():void {
super.onDetachedFromWindow();
this.removeAllCallbacks();
}
protected onDraw(canvas:Canvas):void {
if (!this.mHasSelectorWheel) {
super.onDraw(canvas);
return;
}
let x:number = (this.mRight - this.mLeft) / 2;
let y:number = this.mCurrentScrollOffset;
// draw the virtual buttons pressed state if needed
if (this.mVirtualButtonPressedDrawable != null && this.mScrollState == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE) {
if (this.mDecrementVirtualButtonPressed) {
this.mVirtualButtonPressedDrawable.setState(NumberPicker.PRESSED_STATE_SET);
this.mVirtualButtonPressedDrawable.setBounds(0, 0, this.mRight, this.mTopSelectionDividerTop);
this.mVirtualButtonPressedDrawable.draw(canvas);
}
if (this.mIncrementVirtualButtonPressed) {
this.mVirtualButtonPressedDrawable.setState(NumberPicker.PRESSED_STATE_SET);
this.mVirtualButtonPressedDrawable.setBounds(0, this.mBottomSelectionDividerBottom, this.mRight, this.mBottom);
this.mVirtualButtonPressedDrawable.draw(canvas);
}
}
// draw the selector wheel
let selectorIndices:number[] = this.mSelectorIndices;
for (let i:number = 0; i < selectorIndices.length; i++) {
let selectorIndex:number = selectorIndices[i];
let scrollSelectorValue:string = this.mSelectorIndexToStringCache.get(selectorIndex);
// with the new one.
//if (i != this.SELECTOR_MIDDLE_ITEM_INDEX || this.mInputText.getVisibility() != NumberPicker.VISIBLE) {
canvas.drawText(scrollSelectorValue, x, y, this.mSelectorWheelPaint);
//}
y += this.mSelectorElementHeight;
}
// draw the selection dividers
if (this.mSelectionDivider != null) {
// draw the top divider
let topOfTopDivider:number = this.mTopSelectionDividerTop;
let bottomOfTopDivider:number = topOfTopDivider + this.mSelectionDividerHeight;
this.mSelectionDivider.setBounds(0, topOfTopDivider, this.mRight, bottomOfTopDivider);
this.mSelectionDivider.draw(canvas);
// draw the bottom divider
let bottomOfBottomDivider:number = this.mBottomSelectionDividerBottom;
let topOfBottomDivider:number = bottomOfBottomDivider - this.mSelectionDividerHeight;
this.mSelectionDivider.setBounds(0, topOfBottomDivider, this.mRight, bottomOfBottomDivider);
this.mSelectionDivider.draw(canvas);
}
}
//onInitializeAccessibilityEvent(event:AccessibilityEvent):void {
// super.onInitializeAccessibilityEvent(event);
// event.setClassName(NumberPicker.class.getName());
// event.setScrollable(true);
// event.setScrollY((this.mMinValue + this.mValue) * this.mSelectorElementHeight);
// event.setMaxScrollY((this.mMaxValue - this.mMinValue) * this.mSelectorElementHeight);
//}
//
//getAccessibilityNodeProvider():AccessibilityNodeProvider {
// if (!this.mHasSelectorWheel) {
// return super.getAccessibilityNodeProvider();
// }
// if (this.mAccessibilityNodeProvider == null) {
// this.mAccessibilityNodeProvider = new NumberPicker.AccessibilityNodeProviderImpl(this);
// }
// return this.mAccessibilityNodeProvider;
//}
/**
* Makes a measure spec that tries greedily to use the max value.
*
* @param measureSpec The measure spec.
* @param maxSize The max value for the size.
* @return A measure spec greedily imposing the max size.
*/
private makeMeasureSpec(measureSpec:number, maxSize:number):number {
if (maxSize == NumberPicker.SIZE_UNSPECIFIED) {
return measureSpec;
}
const size:number = View.MeasureSpec.getSize(measureSpec);
const mode:number = View.MeasureSpec.getMode(measureSpec);
switch(mode) {
case View.MeasureSpec.EXACTLY:
return measureSpec;
case View.MeasureSpec.AT_MOST:
return View.MeasureSpec.makeMeasureSpec(Math.min(size, maxSize), View.MeasureSpec.EXACTLY);
case View.MeasureSpec.UNSPECIFIED:
return View.MeasureSpec.makeMeasureSpec(maxSize, View.MeasureSpec.EXACTLY);
default:
throw Error(`new IllegalArgumentException("Unknown measure mode: " + mode)`);
}
}
/**
* Utility to reconcile a desired size and state, with constraints imposed
* by a MeasureSpec. Tries to respect the min size, unless a different size
* is imposed by the constraints.
*
* @param minSize The minimal desired size.
* @param measuredSize The currently measured size.
* @param measureSpec The current measure spec.
* @return The resolved size and state.
*/
private resolveSizeAndStateRespectingMinSize(minSize:number, measuredSize:number, measureSpec:number):number {
if (minSize != NumberPicker.SIZE_UNSPECIFIED) {
const desiredWidth:number = Math.max(minSize, measuredSize);
return NumberPicker.resolveSizeAndState(desiredWidth, measureSpec, 0);
} else {
return measuredSize;
}
}
/**
* Resets the selector indices and clear the cached string representation of
* these indices.
*/
private initializeSelectorWheelIndices():void {
this.mSelectorIndexToStringCache.clear();
let selectorIndices:number[] = this.mSelectorIndices;
let current:number = this.getValue();
for (let i:number = 0; i < this.mSelectorIndices.length; i++) {
let selectorIndex:number = Math.floor(current + (i - this.SELECTOR_MIDDLE_ITEM_INDEX));
if (this.mWrapSelectorWheel) {
selectorIndex = this.getWrappedSelectorIndex(selectorIndex);
}
selectorIndices[i] = selectorIndex;
this.ensureCachedScrollSelectorValue(selectorIndices[i]);
}
}
/**
* Sets the current value of this NumberPicker.
*
* @param current The new value of the NumberPicker.
* @param notifyChange Whether to notify if the current value changed.
*/
private setValueInternal(current:number, notifyChange:boolean):void {
if (this.mValue == current) {
return;
}
// Wrap around the values if we go past the start or end
if (this.mWrapSelectorWheel) {
current = this.getWrappedSelectorIndex(current);
} else {
current = Math.max(current, this.mMinValue);
current = Math.min(current, this.mMaxValue);
}
let previous:number = this.mValue;
this.mValue = current;
this.updateInputTextView();
if (notifyChange) {
this.notifyChange(previous, current);
}
this.initializeSelectorWheelIndices();
this.invalidate();
}
/**
* Changes the current value by one which is increment or
* decrement based on the passes argument.
* decrement the current value.
*
* @param increment True to increment, false to decrement.
*/
private changeValueByOne(increment:boolean):void {
if (this.mHasSelectorWheel) {
//this.mInputText.setVisibility(View.INVISIBLE);
if (!this.moveToFinalScrollerPosition(this.mFlingScroller)) {
this.moveToFinalScrollerPosition(this.mAdjustScroller);
}
this.mPreviousScrollerY = 0;
if (increment) {
this.mFlingScroller.startScroll(0, 0, 0, -this.mSelectorElementHeight, NumberPicker.SNAP_SCROLL_DURATION);
} else {
this.mFlingScroller.startScroll(0, 0, 0, this.mSelectorElementHeight, NumberPicker.SNAP_SCROLL_DURATION);
}
this.invalidate();
} else {
if (increment) {
this.setValueInternal(this.mValue + 1, true);
} else {
this.setValueInternal(this.mValue - 1, true);
}
}
}
private initializeSelectorWheel():void {
this.initializeSelectorWheelIndices();
let selectorIndices:number[] = this.mSelectorIndices;
let totalTextHeight:number = selectorIndices.length * this.mTextSize;
let totalTextGapHeight:number = (this.mBottom - this.mTop) - totalTextHeight;
let textGapCount:number = selectorIndices.length;
this.mSelectorTextGapHeight = Math.floor((totalTextGapHeight / textGapCount + 0.5));
this.mSelectorElementHeight = this.mTextSize + this.mSelectorTextGapHeight;
// Ensure that the middle item is positioned the same as the text in
// mInputText
let editTextTextPosition:number = this.getHeight()/2 + this.mTextSize/2;
this.mInitialScrollOffset = editTextTextPosition - (this.mSelectorElementHeight * this.SELECTOR_MIDDLE_ITEM_INDEX);
this.mCurrentScrollOffset = this.mInitialScrollOffset;
this.updateInputTextView();
}
private initializeFadingEdges():void {
this.setVerticalFadingEdgeEnabled(true);
this.setFadingEdgeLength((this.mBottom - this.mTop - this.mTextSize) / 2);
}
/**
* Callback invoked upon completion of a given <code>scroller</code>.
*/
private onScrollerFinished(scroller:Scroller):void {
if (scroller == this.mFlingScroller) {
if (!this.ensureScrollWheelAdjusted()) {
this.updateInputTextView();
}
this.onScrollStateChange(NumberPicker.OnScrollListener.SCROLL_STATE_IDLE);
} else {
if (this.mScrollState != NumberPicker.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
this.updateInputTextView();
}
}
}
/**
* Handles transition to a given <code>scrollState</code>
*/
private onScrollStateChange(scrollState:number):void {
if (this.mScrollState == scrollState) {
return;
}
this.mScrollState = scrollState;
if (this.mOnScrollListener != null) {
this.mOnScrollListener.onScrollStateChange(this, scrollState);
}
}
/**
* Flings the selector with the given <code>velocityY</code>.
*/
private fling(velocityY:number):void {
this.mPreviousScrollerY = 0;
if (velocityY > 0) {
this.mFlingScroller.fling(0, 0, 0, velocityY, 0, 0, 0, Integer.MAX_VALUE);
} else {
this.mFlingScroller.fling(0, Integer.MAX_VALUE, 0, velocityY, 0, 0, 0, Integer.MAX_VALUE);
}
this.invalidate();
}
/**
* @return The wrapped index <code>selectorIndex</code> value.
*/
private getWrappedSelectorIndex(selectorIndex:number):number {
if (selectorIndex > this.mMaxValue) {
return this.mMinValue + (selectorIndex - this.mMaxValue) % (this.mMaxValue - this.mMinValue) - 1;
} else if (selectorIndex < this.mMinValue) {
return this.mMaxValue - (this.mMinValue - selectorIndex) % (this.mMaxValue - this.mMinValue) + 1;
}
return selectorIndex;
}
/**
* Increments the <code>selectorIndices</code> whose string representations
* will be displayed in the selector.
*/
private incrementSelectorIndices(selectorIndices:number[]):void {
for (let i:number = 0; i < selectorIndices.length - 1; i++) {
selectorIndices[i] = selectorIndices[i + 1];
}
let nextScrollSelectorIndex:number = selectorIndices[selectorIndices.length - 2] + 1;
if (this.mWrapSelectorWheel && nextScrollSelectorIndex > this.mMaxValue) {
nextScrollSelectorIndex = this.mMinValue;
}
selectorIndices[selectorIndices.length - 1] = nextScrollSelectorIndex;
this.ensureCachedScrollSelectorValue(nextScrollSelectorIndex);
}
/**
* Decrements the <code>selectorIndices</code> whose string representations
* will be displayed in the selector.
*/
private decrementSelectorIndices(selectorIndices:number[]):void {
for (let i:number = selectorIndices.length - 1; i > 0; i--) {
selectorIndices[i] = selectorIndices[i - 1];
}
let nextScrollSelectorIndex:number = selectorIndices[1] - 1;
if (this.mWrapSelectorWheel && nextScrollSelectorIndex < this.mMinValue) {
nextScrollSelectorIndex = this.mMaxValue;
}
selectorIndices[0] = nextScrollSelectorIndex;
this.ensureCachedScrollSelectorValue(nextScrollSelectorIndex);
}
/**
* Ensures we have a cached string representation of the given <code>
* selectorIndex</code> to avoid multiple instantiations of the same string.
*/
private ensureCachedScrollSelectorValue(selectorIndex:number):void {
let cache:SparseArray<string> = this.mSelectorIndexToStringCache;
let scrollSelectorValue:string = cache.get(selectorIndex);
if (scrollSelectorValue != null) {
return;
}
if (selectorIndex < this.mMinValue || selectorIndex > this.mMaxValue) {
scrollSelectorValue = "";
} else {
if (this.mDisplayedValues != null) {
let displayedValueIndex:number = selectorIndex - this.mMinValue;
scrollSelectorValue = this.mDisplayedValues[displayedValueIndex];
} else {
scrollSelectorValue = this.formatNumber(selectorIndex);
}
}
cache.put(selectorIndex, scrollSelectorValue);
}
private formatNumber(value:number):string {
return (this.mFormatter != null) ? this.mFormatter.format(value) : NumberPicker.formatNumberWithLocale(value);
}
private validateInputTextView(v:View):void {
//let str:string = String.valueOf((<TextView> v).getText());
//if (TextUtils.isEmpty(str)) {
// // Restore to the old value as we don't allow empty values
// this.updateInputTextView();
//} else {
// // Check the new value and ensure it's in range
// let current:number = this.getSelectedPos(str.toString());
// this.setValueInternal(current, true);
//}
}
/**
* Updates the view of this NumberPicker. If displayValues were specified in
* the string corresponding to the index specified by the current value will
* be returned. Otherwise, the formatter specified in {@link #setFormatter}
* will be used to format the number.
*
* @return Whether the text was updated.
*/
private updateInputTextView():boolean {
/*
* If we don't have displayed values then use the current number else
* find the correct value in the displayed values for the current
* number.
*/
//let text:string = (this.mDisplayedValues == null) ? this.formatNumber(this.mValue) : this.mDisplayedValues[this.mValue - this.mMinValue];
//if (!TextUtils.isEmpty(text) && !text.equals(this.mInputText.getText().toString())) {
// this.mInputText.setText(text);
// return true;
//}
return false;
}
/**
* Notifies the listener, if registered, of a change of the value of this
* NumberPicker.
*/
private notifyChange(previous:number, current:number):void {
if (this.mOnValueChangeListener != null) {
this.mOnValueChangeListener.onValueChange(this, previous, this.mValue);
}
}
/**
* Posts a command for changing the current value by one.
*
* @param increment Whether to increment or decrement the value.
*/
private postChangeCurrentByOneFromLongPress(increment:boolean, delayMillis:number):void {
if (this.mChangeCurrentByOneFromLongPressCommand == null) {
this.mChangeCurrentByOneFromLongPressCommand = new NumberPicker.ChangeCurrentByOneFromLongPressCommand(this);
} else {
this.removeCallbacks(this.mChangeCurrentByOneFromLongPressCommand);
}
this.mChangeCurrentByOneFromLongPressCommand.setStep(increment);
this.postDelayed(this.mChangeCurrentByOneFromLongPressCommand, delayMillis);
}
/**
* Removes the command for changing the current value by one.
*/
private removeChangeCurrentByOneFromLongPress():void {
if (this.mChangeCurrentByOneFromLongPressCommand != null) {
this.removeCallbacks(this.mChangeCurrentByOneFromLongPressCommand);
}
}
/**
* Posts a command for beginning an edit of the current value via IME on
* long press.
*/
private postBeginSoftInputOnLongPressCommand():void {
if (this.mBeginSoftInputOnLongPressCommand == null) {
this.mBeginSoftInputOnLongPressCommand = new NumberPicker.BeginSoftInputOnLongPressCommand(this);
} else {
this.removeCallbacks(this.mBeginSoftInputOnLongPressCommand);
}
this.postDelayed(this.mBeginSoftInputOnLongPressCommand, ViewConfiguration.getLongPressTimeout());
}
/**
* Removes the command for beginning an edit of the current value via IME.
*/
private removeBeginSoftInputCommand():void {
if (this.mBeginSoftInputOnLongPressCommand != null) {
this.removeCallbacks(this.mBeginSoftInputOnLongPressCommand);
}
}
/**
* Removes all pending callback from the message queue.
*/
private removeAllCallbacks():void {
if (this.mChangeCurrentByOneFromLongPressCommand != null) {
this.removeCallbacks(this.mChangeCurrentByOneFromLongPressCommand);
}
if (this.mSetSelectionCommand != null) {
this.removeCallbacks(this.mSetSelectionCommand);
}
if (this.mBeginSoftInputOnLongPressCommand != null) {
this.removeCallbacks(this.mBeginSoftInputOnLongPressCommand);
}
this.mPressedStateHelper.cancel();
}
/**
* @return The selected index given its displayed <code>value</code>.
*/
private getSelectedPos(value:string):number {
if (this.mDisplayedValues == null) {
try {
return Integer.parseInt(value);
} catch (e){
}
} else {
for (let i:number = 0; i < this.mDisplayedValues.length; i++) {
// Don't force the user to type in jan when ja will do
value = value.toLowerCase();
if (this.mDisplayedValues[i].toLowerCase().startsWith(value)) {
return this.mMinValue + i;
}
}
/*
* The user might have typed in a number into the month field i.e.
* 10 instead of OCT so support that too.
*/
try {
return Integer.parseInt(value);
} catch (e){
}
}
return this.mMinValue;
}
/**
* Posts an {@link SetSelectionCommand} from the given <code>selectionStart
* </code> to <code>selectionEnd</code>.
*/
private postSetSelectionCommand(selectionStart:number, selectionEnd:number):void {
if (this.mSetSelectionCommand == null) {
this.mSetSelectionCommand = new NumberPicker.SetSelectionCommand(this);
} else {
this.removeCallbacks(this.mSetSelectionCommand);
}
this.mSetSelectionCommand.mSelectionStart = selectionStart;
this.mSetSelectionCommand.mSelectionEnd = selectionEnd;
this.post(this.mSetSelectionCommand);
}
/**
* The numbers accepted by the input text's {@link Filter}
*/
//private static DIGIT_CHARACTERS:char[] = [ // Latin digits are the common case
// '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', // Arabic-Indic
// '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩', // Extended Arabic-Indic
// '۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹' ];
/**
* Ensures that the scroll wheel is adjusted i.e. there is no offset and the
* middle element is in the middle of the widget.
*
* @return Whether an adjustment has been made.
*/
private ensureScrollWheelAdjusted():boolean {
// adjust to the closest value
let deltaY:number = this.mInitialScrollOffset - this.mCurrentScrollOffset;
if (deltaY != 0) {
this.mPreviousScrollerY = 0;
if (Math.abs(deltaY) > this.mSelectorElementHeight / 2) {
deltaY += (deltaY > 0) ? -this.mSelectorElementHeight : this.mSelectorElementHeight;
}
this.mAdjustScroller.startScroll(0, 0, 0, deltaY, NumberPicker.SELECTOR_ADJUSTMENT_DURATION_MILLIS);
this.invalidate();
return true;
}
return false;
}
private static formatNumberWithLocale(value:number):string {
return value + '';
}
}
export module NumberPicker{
/**
* Use a custom NumberPicker formatting callback to use two-digit minutes
* strings like "01". Keeping a static formatter etc. is the most efficient
* way to do this; it avoids creating temporary objects on every call to
* format().
*/
export class TwoDigitFormatter implements NumberPicker.Formatter {
format(value:number):string {
let s = value+'';
if(s.length===1) s = '0' + s;
return s;
}
}
/**
* Interface to listen for changes of the current value.
*/
export interface OnValueChangeListener {
/**
* Called upon a change of the current value.
*
* @param picker The NumberPicker associated with this listener.
* @param oldVal The previous value.
* @param newVal The new value.
*/
onValueChange(picker:NumberPicker, oldVal:number, newVal:number):void ;
}
/**
* Interface to listen for the picker scroll state.
*/
export interface OnScrollListener {
/**
* Callback invoked while the number picker scroll state has changed.
*
* @param view The view whose scroll state is being reported.
* @param scrollState The current scroll state. One of
* {@link #SCROLL_STATE_IDLE},
* {@link #SCROLL_STATE_TOUCH_SCROLL} or
* {@link #SCROLL_STATE_IDLE}.
*/
onScrollStateChange(view:NumberPicker, scrollState:number):void ;
}
export module OnScrollListener{
/**
* The view is not scrolling.
*/
export var SCROLL_STATE_IDLE:number = 0;/**
* The user is scrolling using touch, and his finger is still on the screen.
*/
export var SCROLL_STATE_TOUCH_SCROLL:number = 1;/**
* The user had previously been scrolling using touch and performed a fling.
*/
export var SCROLL_STATE_FLING:number = 2;}
/**
* Interface used to format current value into a string for presentation.
*/
export interface Formatter {
/**
* Formats a string representation of the current value.
*
* @param value The currently selected value.
* @return A formatted string representation.
*/
format(value:number):string ;
}
///**
// * Filter for accepting only valid indices or prefixes of the string
// * representation of valid indices.
// */
//export class InputTextFilter extends NumberKeyListener {
// _NumberPicker_this:NumberPicker;
// constructor(arg:NumberPicker){
// super();
// this._NumberPicker_this = arg;
// }
//
// // XXX This doesn't allow for range limits when controlled by a
// // soft input method!
// getInputType():number {
// return InputType.TYPE_CLASS_TEXT;
// }
//
// protected getAcceptedChars():char[] {
// return NumberPicker.DIGIT_CHARACTERS;
// }
//
// filter(source:CharSequence, start:number, end:number, dest:Spanned, dstart:number, dend:number):CharSequence {
// if (this._NumberPicker_this.mDisplayedValues == null) {
// let filtered:CharSequence = super.filter(source, start, end, dest, dstart, dend);
// if (filtered == null) {
// filtered = source.subSequence(start, end);
// }
// let result:string = String.valueOf(dest.subSequence(0, dstart)) + filtered + dest.subSequence(dend, dest.length());
// if ("".equals(result)) {
// return result;
// }
// let val:number = this._NumberPicker_this.getSelectedPos(result);
// /*
// * Ensure the user can't type in a value greater than the max
// * allowed. We have to allow less than min as the user might
// * want to delete some numbers and then type a new number.
// * And prevent multiple-"0" that exceeds the length of upper
// * bound number.
// */
// if (val > this._NumberPicker_this.mMaxValue || result.length() > String.valueOf(this._NumberPicker_this.mMaxValue).length()) {
// return "";
// } else {
// return filtered;
// }
// } else {
// let filtered:CharSequence = String.valueOf(source.subSequence(start, end));
// if (TextUtils.isEmpty(filtered)) {
// return "";
// }
// let result:string = String.valueOf(dest.subSequence(0, dstart)) + filtered + dest.subSequence(dend, dest.length());
// let str:string = String.valueOf(result).toLowerCase();
// for (let val:string of this._NumberPicker_this.mDisplayedValues) {
// let valLowerCase:string = val.toLowerCase();
// if (valLowerCase.startsWith(str)) {
// this._NumberPicker_this.postSetSelectionCommand(result.length(), val.length());
// return val.subSequence(dstart, val.length());
// }
// }
// return "";
// }
// }
//}
export class PressedStateHelper implements Runnable {
_NumberPicker_this:NumberPicker;
constructor(arg:NumberPicker){
this._NumberPicker_this = arg;
}
static BUTTON_INCREMENT:number = 1;
static BUTTON_DECREMENT:number = 2;
private MODE_PRESS:number = 1;
private MODE_TAPPED:number = 2;
private mManagedButton:number = 0;
private mMode:number = 0;
cancel():void {
this.mMode = 0;
this.mManagedButton = 0;
this._NumberPicker_this.removeCallbacks(this);
if (this._NumberPicker_this.mIncrementVirtualButtonPressed) {
this._NumberPicker_this.mIncrementVirtualButtonPressed = false;
this._NumberPicker_this.invalidate(0, this._NumberPicker_this.mBottomSelectionDividerBottom, this._NumberPicker_this.mRight, this._NumberPicker_this.mBottom);
}
if (this._NumberPicker_this.mDecrementVirtualButtonPressed) {
this._NumberPicker_this.mDecrementVirtualButtonPressed = false;
this._NumberPicker_this.invalidate(0, 0, this._NumberPicker_this.mRight, this._NumberPicker_this.mTopSelectionDividerTop);
}
}
buttonPressDelayed(button:number):void {
this.cancel();
this.mMode = this.MODE_PRESS;
this.mManagedButton = button;
this._NumberPicker_this.postDelayed(this, ViewConfiguration.getTapTimeout());
}
buttonTapped(button:number):void {
this.cancel();
this.mMode = this.MODE_TAPPED;
this.mManagedButton = button;
this._NumberPicker_this.post(this);
}
run():void {
switch(this.mMode) {
case this.MODE_PRESS:
{
switch(this.mManagedButton) {
case PressedStateHelper.BUTTON_INCREMENT:
{
this._NumberPicker_this.mIncrementVirtualButtonPressed = true;
this._NumberPicker_this.invalidate(0, this._NumberPicker_this.mBottomSelectionDividerBottom, this._NumberPicker_this.mRight, this._NumberPicker_this.mBottom);
}
break;
case PressedStateHelper.BUTTON_DECREMENT:
{
this._NumberPicker_this.mDecrementVirtualButtonPressed = true;
this._NumberPicker_this.invalidate(0, 0, this._NumberPicker_this.mRight, this._NumberPicker_this.mTopSelectionDividerTop);
}
}
}
break;
case this.MODE_TAPPED:
{
switch(this.mManagedButton) {
case PressedStateHelper.BUTTON_INCREMENT:
{
if (!this._NumberPicker_this.mIncrementVirtualButtonPressed) {
this._NumberPicker_this.postDelayed(this, ViewConfiguration.getPressedStateDuration());
}
this._NumberPicker_this.mIncrementVirtualButtonPressed = !this._NumberPicker_this.mIncrementVirtualButtonPressed;
this._NumberPicker_this.invalidate(0, this._NumberPicker_this.mBottomSelectionDividerBottom, this._NumberPicker_this.mRight, this._NumberPicker_this.mBottom);
}
break;
case PressedStateHelper.BUTTON_DECREMENT:
{
if (!this._NumberPicker_this.mDecrementVirtualButtonPressed) {
this._NumberPicker_this.postDelayed(this, ViewConfiguration.getPressedStateDuration());
}
this._NumberPicker_this.mDecrementVirtualButtonPressed = !this._NumberPicker_this.mDecrementVirtualButtonPressed;
this._NumberPicker_this.invalidate(0, 0, this._NumberPicker_this.mRight, this._NumberPicker_this.mTopSelectionDividerTop);
}
}
}
break;
}
}
}
/**
* Command for setting the input text selection.
*/
export class SetSelectionCommand implements Runnable {
_NumberPicker_this:NumberPicker;
constructor(arg:NumberPicker){
this._NumberPicker_this = arg;
}
private mSelectionStart:number = 0;
private mSelectionEnd:number = 0;
run():void {
//this._NumberPicker_this.mInputText.setSelection(this.mSelectionStart, this.mSelectionEnd);
}
}
/**
* Command for changing the current value from a long press by one.
*/
export class ChangeCurrentByOneFromLongPressCommand implements Runnable {
_NumberPicker_this:NumberPicker;
constructor(arg:NumberPicker){
this._NumberPicker_this = arg;
}
private mIncrement:boolean;
setStep(increment:boolean):void {
this.mIncrement = increment;
}
run():void {
this._NumberPicker_this.changeValueByOne(this.mIncrement);
this._NumberPicker_this.postDelayed(this, this._NumberPicker_this.mLongPressUpdateInterval);
}
}
/**
* @hide
*/
//export class CustomEditText extends EditText {
//
// constructor( context:Context, attrs:AttributeSet) {
// super(context, attrs);
// }
//
// onEditorAction(actionCode:number):void {
// super.onEditorAction(actionCode);
// if (actionCode == EditorInfo.IME_ACTION_DONE) {
// this.clearFocus();
// }
// }
//}
/**
* Command for beginning soft input on long press.
*/
export class BeginSoftInputOnLongPressCommand implements Runnable {
_NumberPicker_this:NumberPicker;
constructor(arg:NumberPicker){
this._NumberPicker_this = arg;
}
run():void {
this._NumberPicker_this.showSoftInput();
this._NumberPicker_this.mIngonreMoveEvents = true;
}
}
}
} | the_stack |
import { IdentityTypes, RequestLogicTypes, SignatureTypes } from '@requestnetwork/types';
import Utils from '@requestnetwork/utils';
import CancelAction from '../../../src/actions/cancel';
import Version from '../../../src/version';
const CURRENT_VERSION = Version.currentVersion;
import * as TestData from '../utils/test-data-generator';
/* eslint-disable @typescript-eslint/no-unused-expressions */
describe('actions/cancel', () => {
describe('format', () => {
it('can cancel without extensionsData', async () => {
const actionCancel = await CancelAction.format(
{
requestId: TestData.requestIdMock,
},
TestData.payerRaw.identity,
TestData.fakeSignatureProvider,
);
// 'action is wrong'
expect(actionCancel.data.name).toBe(RequestLogicTypes.ACTION_NAME.CANCEL);
// 'requestId is wrong'
expect(actionCancel.data.parameters.requestId).toBe(TestData.requestIdMock);
// 'extensionsData is wrong'
expect(actionCancel.data.parameters.extensionsData).toBeUndefined();
});
it('can cancel with extensionsData', async () => {
const actionCancel = await CancelAction.format(
{
extensionsData: TestData.oneExtension,
requestId: TestData.requestIdMock,
},
TestData.payerRaw.identity,
TestData.fakeSignatureProvider,
);
// 'action is wrong'
expect(actionCancel.data.name).toBe(RequestLogicTypes.ACTION_NAME.CANCEL);
// 'requestId is wrong'
expect(actionCancel.data.parameters.requestId).toBe(TestData.requestIdMock);
// 'extensionsData is wrong'
expect(actionCancel.data.parameters.extensionsData).toEqual(TestData.oneExtension);
});
});
describe('applyActionToRequest', () => {
it('can cancel by payer with state === created', async () => {
const actionCancel = await CancelAction.format(
{
requestId: TestData.requestIdMock,
},
TestData.payerRaw.identity,
TestData.fakeSignatureProvider,
);
const request = CancelAction.applyActionToRequest(
actionCancel,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
// 'requestId is wrong'
expect(request.requestId).toBe(TestData.requestIdMock);
// 'currency is wrong'
expect(request.currency).toEqual({
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
});
// 'state is wrong'
expect(request.state).toBe(RequestLogicTypes.STATE.CANCELED);
// 'expectedAmount is wrong'
expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount);
// 'extensions is wrong'
expect(request.extensions).toEqual({});
// 'request should have property creator'
expect(request).toHaveProperty('creator');
// 'request.creator.type is wrong'
expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.creator.value is wrong'
expect(request.creator.value).toBe(TestData.payeeRaw.address);
// 'request should have property payee'
expect(request).toHaveProperty('payee');
if (request.payee) {
// 'request.payee.type is wrong'
expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payee.value is wrong'
expect(request.payee.value).toBe(TestData.payeeRaw.address);
}
// 'request should have property payer'
expect(request).toHaveProperty('payer');
if (request.payer) {
// 'request.payer.type is wrong'
expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payer.value is wrong'
expect(request.payer.value).toBe(TestData.payerRaw.address);
}
// 'request.events is wrong'
expect(request.events[1]).toEqual({
actionSigner: TestData.payerRaw.identity,
name: RequestLogicTypes.ACTION_NAME.CANCEL,
parameters: { extensionsDataLength: 0 },
timestamp: 2,
});
});
it('cannot cancel by payer with state === accepted', async () => {
const actionCancel = await CancelAction.format(
{
requestId: TestData.requestIdMock,
},
TestData.payerRaw.identity,
TestData.fakeSignatureProvider,
);
expect(() =>
CancelAction.applyActionToRequest(
actionCancel,
2,
Utils.deepCopy(TestData.requestAcceptedNoExtension),
),
).toThrowError('A payer cancel need to be done on a request with the state created');
});
it('cannot cancel by payer with state === canceled', async () => {
const actionCancel = await CancelAction.format(
{
requestId: TestData.requestIdMock,
},
TestData.payerRaw.identity,
TestData.fakeSignatureProvider,
);
expect(() =>
CancelAction.applyActionToRequest(
actionCancel,
2,
Utils.deepCopy(TestData.requestCanceledNoExtension),
),
).toThrowError('A payer cancel need to be done on a request with the state created');
});
it('can cancel by payee with state === created', async () => {
const actionCancel = await CancelAction.format(
{
requestId: TestData.requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
const request = CancelAction.applyActionToRequest(
actionCancel,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
// 'requestId is wrong'
expect(request.requestId).toBe(TestData.requestIdMock);
// 'currency is wrong'
expect(request.currency).toEqual({
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
});
// 'state is wrong'
expect(request.state).toBe(RequestLogicTypes.STATE.CANCELED);
// 'expectedAmount is wrong'
expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount);
// 'extensions is wrong'
expect(request.extensions).toEqual({});
// 'request should have property creator'
expect(request).toHaveProperty('creator');
// 'request.creator.type is wrong'
expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.creator.value is wrong'
expect(request.creator.value).toBe(TestData.payeeRaw.address);
// 'request should have property payee'
expect(request).toHaveProperty('payee');
if (request.payee) {
// 'request.payee.type is wrong'
expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payee.value is wrong'
expect(request.payee.value).toBe(TestData.payeeRaw.address);
}
// 'request should have property payer'
expect(request).toHaveProperty('payer');
if (request.payer) {
// 'request.payer.type is wrong'
expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payer.value is wrong'
expect(request.payer.value).toBe(TestData.payerRaw.address);
}
// 'request.events is wrong'
expect(request.events[1]).toEqual({
actionSigner: TestData.payeeRaw.identity,
name: RequestLogicTypes.ACTION_NAME.CANCEL,
parameters: { extensionsDataLength: 0 },
timestamp: 2,
});
});
it('can cancel by payee with state === accepted', async () => {
const actionCancel = await CancelAction.format(
{
requestId: TestData.requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
const request = CancelAction.applyActionToRequest(
actionCancel,
2,
Utils.deepCopy(TestData.requestAcceptedNoExtension),
);
// 'requestId is wrong'
expect(request.requestId).toBe(TestData.requestIdMock);
// 'currency is wrong'
expect(request.currency).toEqual({
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
});
// 'state is wrong'
expect(request.state).toBe(RequestLogicTypes.STATE.CANCELED);
// 'expectedAmount is wrong'
expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount);
// 'extensions is wrong'
expect(request.extensions).toEqual({});
// 'request should have property creator'
expect(request).toHaveProperty('creator');
// 'request.creator.type is wrong'
expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.creator.value is wrong'
expect(request.creator.value).toBe(TestData.payeeRaw.address);
// 'request should have property payee'
expect(request).toHaveProperty('payee');
if (request.payee) {
// 'request.payee.type is wrong'
expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payee.value is wrong'
expect(request.payee.value).toBe(TestData.payeeRaw.address);
}
// 'request should have property payer'
expect(request).toHaveProperty('payer');
if (request.payer) {
// 'request.payer.type is wrong'
expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payer.value is wrong'
expect(request.payer.value).toBe(TestData.payerRaw.address);
}
// 'request.events is wrong'
expect(request.events[2]).toEqual({
actionSigner: TestData.payeeRaw.identity,
name: RequestLogicTypes.ACTION_NAME.CANCEL,
parameters: { extensionsDataLength: 0 },
timestamp: 2,
});
});
it('cannot cancel by payee with state === canceled', async () => {
const actionCancel = await CancelAction.format(
{
requestId: TestData.requestIdMock,
},
TestData.payeeRaw.identity,
TestData.fakeSignatureProvider,
);
expect(() =>
CancelAction.applyActionToRequest(
actionCancel,
2,
Utils.deepCopy(TestData.requestCanceledNoExtension),
),
).toThrowError('Cannot cancel an already canceled request');
});
it('cannot cancel by third party', async () => {
const actionCancel = await CancelAction.format(
{
requestId: TestData.requestIdMock,
},
TestData.otherIdRaw.identity,
TestData.fakeSignatureProvider,
);
expect(() =>
CancelAction.applyActionToRequest(
actionCancel,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
),
).toThrowError('Signer must be the payer or the payee');
});
it('cannot cancel if no requestId', () => {
const action = {
data: {
name: RequestLogicTypes.ACTION_NAME.CANCEL,
parameters: {},
version: CURRENT_VERSION,
},
signature: {
method: SignatureTypes.METHOD.ECDSA,
value:
'0xdd44c2d34cba689921c60043a78e189b4aa35d5940723bf98b9bb9083385de316333204ce3bbeced32afe2ea203b76153d523d924c4dca4a1d9fc466e0160f071c',
},
};
expect(() =>
CancelAction.applyActionToRequest(
action,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
),
).toThrowError('requestId must be given');
});
it('cannot cancel by payer if no payer in state', () => {
const requestContextNoPayer = {
creator: {
type: IdentityTypes.TYPE.ETHEREUM_ADDRESS,
value: TestData.payeeRaw.address,
},
currency: {
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
},
events: [
{
actionSigner: {
type: IdentityTypes.TYPE.ETHEREUM_ADDRESS,
value: TestData.payeeRaw.address,
},
name: RequestLogicTypes.ACTION_NAME.CREATE,
parameters: {
expectedAmount: '123400000000000000',
extensionsDataLength: 0,
isSignedRequest: false,
},
timestamp: 1,
},
],
expectedAmount: TestData.arbitraryExpectedAmount,
extensions: {},
extensionsData: [],
payee: {
type: IdentityTypes.TYPE.ETHEREUM_ADDRESS,
value: TestData.payeeRaw.address,
},
requestId: TestData.requestIdMock,
state: RequestLogicTypes.STATE.CREATED,
timestamp: 1544426030,
version: CURRENT_VERSION,
};
const action = {
data: {
name: RequestLogicTypes.ACTION_NAME.CANCEL,
parameters: {
requestId: TestData.requestIdMock,
},
version: CURRENT_VERSION,
},
signature: {
method: SignatureTypes.METHOD.ECDSA,
value:
'0xdd44c2d34cba689921c60043a78e189b4aa35d5940723bf98b9bb9083385de316333204ce3bbeced32afe2ea203b76153d523d924c4dca4a1d9fc466e0160f071c',
},
};
expect(() =>
CancelAction.applyActionToRequest(action, 2, requestContextNoPayer),
).toThrowError('Signer must be the payer or the payee');
});
it('cannot cancel by payee if no payee in state', () => {
const requestContextNoPayee = {
creator: {
type: IdentityTypes.TYPE.ETHEREUM_ADDRESS,
value: TestData.payeeRaw.address,
},
currency: {
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
},
events: [
{
actionSigner: {
type: IdentityTypes.TYPE.ETHEREUM_ADDRESS,
value: TestData.payeeRaw.address,
},
name: RequestLogicTypes.ACTION_NAME.CREATE,
parameters: {
expectedAmount: '123400000000000000',
extensionsDataLength: 0,
isSignedRequest: false,
},
timestamp: 1,
},
],
expectedAmount: TestData.arbitraryExpectedAmount,
extensions: {},
extensionsData: [],
payer: {
type: IdentityTypes.TYPE.ETHEREUM_ADDRESS,
value: TestData.payerRaw.address,
},
requestId: TestData.requestIdMock,
state: RequestLogicTypes.STATE.CREATED,
timestamp: 1544426030,
version: CURRENT_VERSION,
};
const action = {
data: {
name: RequestLogicTypes.ACTION_NAME.CANCEL,
parameters: {
requestId: TestData.requestIdMock,
},
version: CURRENT_VERSION,
},
signature: {
method: SignatureTypes.METHOD.ECDSA,
value:
'0xdd44c2d34cba689921c60043a78e189b4aa35d5940723bf98b9bb9083385de316333204ce3bbeced32afe2ea203b76153d523d924c4dca4a1d9fc466e0160f071c',
},
};
expect(() =>
CancelAction.applyActionToRequest(action, 2, requestContextNoPayee),
).toThrowError('Signer must be the payer or the payee');
});
it('can cancel with extensionsData and no extensionsData before', async () => {
const newExtensionsData = [{ id: 'extension1', value: 'whatever' }];
const actionCancel = await CancelAction.format(
{
extensionsData: newExtensionsData,
requestId: TestData.requestIdMock,
},
TestData.payerRaw.identity,
TestData.fakeSignatureProvider,
);
const request = CancelAction.applyActionToRequest(
actionCancel,
2,
Utils.deepCopy(TestData.requestCreatedNoExtension),
);
// 'requestId is wrong'
expect(request.requestId).toBe(TestData.requestIdMock);
// 'currency is wrong'
expect(request.currency).toEqual({
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
});
// 'state is wrong'
expect(request.state).toBe(RequestLogicTypes.STATE.CANCELED);
// 'expectedAmount is wrong'
expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount);
// 'request.extensionsData is wrong'
expect(request.extensionsData).toEqual(newExtensionsData);
// 'request should have property creator'
expect(request).toHaveProperty('creator');
// 'request.creator.type is wrong'
expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.creator.value is wrong'
expect(request.creator.value).toBe(TestData.payeeRaw.address);
// 'request should have property payee'
expect(request).toHaveProperty('payee');
if (request.payee) {
// 'request.payee.type is wrong'
expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payee.value is wrong'
expect(request.payee.value).toBe(TestData.payeeRaw.address);
}
// 'request should have property payer'
expect(request).toHaveProperty('payer');
if (request.payer) {
// 'request.payer.type is wrong'
expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payer.value is wrong'
expect(request.payer.value).toBe(TestData.payerRaw.address);
}
// 'request.events is wrong'
expect(request.events[1]).toEqual({
actionSigner: TestData.payerRaw.identity,
name: RequestLogicTypes.ACTION_NAME.CANCEL,
parameters: { extensionsDataLength: 1 },
timestamp: 2,
});
});
it('can cancel with extensionsData and extensionsData before', async () => {
const newExtensionsData = [{ id: 'extension1', value: 'whatever' }];
const actionCancel = await CancelAction.format(
{
extensionsData: newExtensionsData,
requestId: TestData.requestIdMock,
},
TestData.payerRaw.identity,
TestData.fakeSignatureProvider,
);
const request = CancelAction.applyActionToRequest(
actionCancel,
2,
Utils.deepCopy(TestData.requestCreatedWithExtensions),
);
// 'requestId is wrong'
expect(request.requestId).toBe(TestData.requestIdMock);
// 'currency is wrong'
expect(request.currency).toEqual({
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
});
// 'state is wrong'
expect(request.state).toBe(RequestLogicTypes.STATE.CANCELED);
// 'expectedAmount is wrong'
expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount);
// 'request.extensionsData is wrong'
expect(request.extensionsData).toEqual(TestData.oneExtension.concat(newExtensionsData));
// 'request should have property creator'
expect(request).toHaveProperty('creator');
// 'request.creator.type is wrong'
expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.creator.value is wrong'
expect(request.creator.value).toBe(TestData.payeeRaw.address);
// 'request should have property payee'
expect(request).toHaveProperty('payee');
if (request.payee) {
// 'request.payee.type is wrong'
expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payee.value is wrong'
expect(request.payee.value).toBe(TestData.payeeRaw.address);
}
// 'request should have property payer'
expect(request).toHaveProperty('payer');
if (request.payer) {
// 'request.payer.type is wrong'
expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payer.value is wrong'
expect(request.payer.value).toBe(TestData.payerRaw.address);
}
// 'request.events is wrong'
expect(request.events[1]).toEqual({
actionSigner: TestData.payerRaw.identity,
name: RequestLogicTypes.ACTION_NAME.CANCEL,
parameters: { extensionsDataLength: 1 },
timestamp: 2,
});
});
it('can cancel without extensionsData and extensionsData before', async () => {
const actionCancel = await CancelAction.format(
{
requestId: TestData.requestIdMock,
},
TestData.payerRaw.identity,
TestData.fakeSignatureProvider,
);
const request = CancelAction.applyActionToRequest(
actionCancel,
2,
Utils.deepCopy(TestData.requestCreatedWithExtensions),
);
// 'requestId is wrong'
expect(request.requestId).toBe(TestData.requestIdMock);
// 'currency is wrong'
expect(request.currency).toEqual({
type: RequestLogicTypes.CURRENCY.ETH,
value: 'ETH',
});
// 'state is wrong'
expect(request.state).toBe(RequestLogicTypes.STATE.CANCELED);
// 'expectedAmount is wrong'
expect(request.expectedAmount).toBe(TestData.arbitraryExpectedAmount);
// 'request.extensionsData is wrong'
expect(request.extensionsData).toEqual(TestData.oneExtension);
// 'request should have property creator'
expect(request).toHaveProperty('creator');
// 'request.creator.type is wrong'
expect(request.creator.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.creator.value is wrong'
expect(request.creator.value).toBe(TestData.payeeRaw.address);
// 'request should have property payee'
expect(request).toHaveProperty('payee');
if (request.payee) {
// 'request.payee.type is wrong'
expect(request.payee.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payee.value is wrong'
expect(request.payee.value).toBe(TestData.payeeRaw.address);
}
// 'request should have property payer'
expect(request).toHaveProperty('payer');
if (request.payer) {
// 'request.payer.type is wrong'
expect(request.payer.type).toBe(IdentityTypes.TYPE.ETHEREUM_ADDRESS);
// 'request.payer.value is wrong'
expect(request.payer.value).toBe(TestData.payerRaw.address);
}
// 'request.events is wrong'
expect(request.events[1]).toEqual({
actionSigner: TestData.payerRaw.identity,
name: RequestLogicTypes.ACTION_NAME.CANCEL,
parameters: { extensionsDataLength: 0 },
timestamp: 2,
});
});
});
}); | the_stack |
import * as React from 'react';
import * as ReactDOM from "react-dom";
import JqxButton from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxbuttons';
import JqxInput from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxinput';
import JqxTreeGrid, { jqx } from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxtreegrid';
// import JqxTreeGrid, { ITreeGridProps, jqx } from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxtreegrid';
//
class App extends React.PureComponent<{}, any> {
private myTreeGrid = React.createRef<JqxTreeGrid>();
private input = React.createRef<JqxInput>();
private inputs: any[] = [];
private inputsRefs: any = {};
private references: any[] = [];
constructor(props: {}) {
super(props);
/* tslint:disable:no-console */
this.setRef = this.setRef.bind(this);
this.click = this.click.bind(this);
this.cellValueChanged = this.cellValueChanged.bind(this);
const data: any[] = [
{ "property": "Name", "type": "string", "value": "jqxTreeGrid" },
{
"children": [
{ "property": "X", "value": "0", "type": "number" },
{ "property": "Y", "value": "0", "type": "number" }
],
"property": "Location",
"type": "string", "value": "0, 0"
},
{
"children": [
{ "property": "Width", "value": "200", "type": "number" },
{ "property": "Height", "value": "200", "type": "number" }
],
"property": "Size", "type": "string", "value": "200, 200"
},
{ "property": "Background", "type": "color", "value": "#4621BC" },
{ "property": "Color", "type": "color", "value": "#B1B11B" },
{ "property": "Alignment", "type": "align", "value": "Left" },
{ "property": "Enabled", "type": "bool", "value": "true" }
];
const source: any = {
dataFields: [
{ name: 'property', type: 'string' },
{ name: 'value', type: 'string' },
{ name: 'type', type: 'string' },
{ name: 'children', type: 'array' }
],
dataType: 'json',
hierarchy:
{
root: 'children'
},
localData: data
};
const dataAdapter: any = new jqx.dataAdapter(source);
this.state = {
columns: [
{ editable: false, dataField: 'property', text: 'Property Name', width: 200 },
{
columnType: 'custom',
// creates an editor depending on the 'type' value.
createEditor: (rowKey: any, cellvalue: any, editor: any, cellText: any, width: any, height: any): void => {
const row = this.myTreeGrid.current!.getRow(rowKey);
const type = row.type;
console.log('createEditor');
switch (type) {
case 'string':
case 'number':
// let inputContainer = document.createElement('input');
// inputContainer.id = 'myInput';
// inputContainer.style.cssText = 'height: 100%; border: none';
// editor[0].appendChild(inputContainer);
// this.myInput = jqwidgets.createInstance('#myInput', 'jqxInput', { width: '100%', height: '100%' });
console.log('%cnumber', 'color: yellow;');
// VUE approach
// let inputContainer = document.createElement('input');
// inputContainer.id = 'myInput';
// inputContainer.style.cssText = 'height: 100%; border: none';
// editor[0].appendChild(inputContainer);
// this['inputRow' + rowKey] = jqwidgets.createInstance('#myInput', 'jqxInput', { width: '100%', height: '100%' });
// break;
const inputDom = document.createElement('div');
inputDom.style.cssText = 'overflow: hidden; position: relative; height: 100%; width: 100%;';
editor[0].appendChild(inputDom);
const inputComponent = <JqxInput theme={'material-purple'} ref={this.input} key={rowKey} width={'100%'} height={'100%'} source={['Item 1', 'Item 2', 'Item 3', 'Item 4']} />;
// const inputComponent = <JqxInput theme={'material-purple'} ref={this.input[rowKey]} key={rowKey} width={'100%'} height={'100%'} source={['Item 1', 'Item 2', 'Item 3', 'Item 4']} />;
const inputReference = ReactDOM.render(inputComponent, inputDom);
const inputObject: any = {};
inputObject[rowKey] = inputReference;
this.inputs.push(inputObject);
// console.log(1001, inputComponent, rowKey, 2002, inputReference, 5555, this.inputs);
this.inputsRefs[rowKey] = inputReference;
break;
case 'align':
console.log('align');
// let dropDownListContainer = document.createElement('div');
// dropDownListContainer.id = 'myDropDownList';
// dropDownListContainer.style.cssText = 'height: 100%; border: none';
// editor[0].appendChild(dropDownListContainer);
// let options =
// {
// width: '100%', height: '100%', autoDropDownHeight: true, source: ['Left', 'Center', 'Right']
// };
// this.myDropDownList = jqwidgets.createInstance('#myDropDownList', 'jqxDropDownList', options);
break;
case 'color':
// if (rowKey === '3') {
// let dropDownButtonContainer = document.createElement('div');
// dropDownButtonContainer.id = 'myDropDownButton1';
// dropDownButtonContainer.style.cssText = 'height: 100%; border: none';
// dropDownButtonContainer.innerHTML = '<div style="padding: 5px;"><div class="myColorPicker1"></div></div>';
// editor[0].appendChild(dropDownButtonContainer);
// let myDropDownButton1 = jqwidgets.createInstance('#myDropDownButton1', 'jqxDropDownButton', { width: '100%', height: '100%' });
// this.myColorPicker1 = jqwidgets.createInstance(`.myColorPicker1`, 'jqxColorPicker', { width: 220, height: 220 });
// this.myColorPicker1.addEventHandler('colorchange', (event: any): void => {
// myDropDownButton1.setContent(this.getTextElementByColor(event.args.color));
// });
// } else {
// let dropDownButtonContainer = document.createElement('div');
// dropDownButtonContainer.id = 'myDropDownButton2';
// dropDownButtonContainer.style.cssText = 'height: 100%; border: none';
// dropDownButtonContainer.innerHTML = '<div style="padding: 5px;"><div class="myColorPicker2"></div></div>';
// editor[0].appendChild(dropDownButtonContainer);
// let myDropDownButton2 = jqwidgets.createInstance('#myDropDownButton2', 'jqxDropDownButton', { width: '100%', height: '100%' });
// this.myColorPicker2 = jqwidgets.createInstance(`.myColorPicker2`, 'jqxColorPicker', { width: 220, height: 220 });
// this.myColorPicker2.addEventHandler('colorchange', (event: any): void => {
// myDropDownButton2.setContent(this.getTextElementByColor(event.args.color));
// });
// }
console.log('color');
break;
case 'bool':
console.log('bool');
// let checkBoxContainer = document.createElement('div');
// checkBoxContainer.id = 'myCheckBox';
// checkBoxContainer.style.cssText = 'margin-top: 6px; margin-left: -8px; left: 50%; position: relative';
// editor[0].appendChild(checkBoxContainer);
// this.myCheckBox = jqwidgets.createInstance('#myCheckBox', 'jqxCheckBox', { checked: cellvalue });
break;
}
},
dataField: 'value',
// returns the value of the custom editor.
getEditorValue: (rowKey: any, cellvalue: any, editor: any): any => {
console.log('%cgetEditorValue', 'color: greenyellow;');
const row = this.myTreeGrid.current!.getRow(rowKey);
// const inputItem = React.createRef<JqxInput>();
// inputItem = this.inputsRefs[rowKey];
const item = this.inputsRefs[rowKey];
// const querySelector = document.querySelector(item._id);
// console.log('getEditorValue', rowKey, item, this.references, 'cellvalue', cellvalue, editor, this.input);
// console.log(item!.getOptions('value'), editor[0]!.children[0]!.children[0].value, this.input.current!);
console.log(item!.getOptions('value'), editor[0]!.children[0]!.children[0].value);
// console.log('getEditorValue', rowKey, item, this.references[0]!.getOptions('value'));
// console.log('getEditorValue', rowKey, item, item._id, 7557, editor, querySelector);
// console.log('getEditorValue', row, rowKey, this.inputs, 7777, this.inputsRefs);
switch (row.type) {
case 'string':
// return this.myInput.val(1);
case 'number':
// let number = parseFloat(this.myInput.val());
// if (isNaN(number)) {
// return 0;
// }
// else return number;
// return "Item X";
case 'align':
// return this.myDropDownList.val(1);
case 'color':
// if (rowKey === '3') {
// let color = this.myColorPicker1.getColor();
// return '#' + color.hex;
// } else {
// let color = this.myColorPicker2.getColor();
// return '#' + color.hex;
// }
case 'bool':
// return this.myCheckBox.val();
}
return '';
},
// updates the editor's value.
initEditor: (rowKey: any, cellvalue: any, editor: any, cellText: any, width: any, height: any) => {
const row = this.myTreeGrid.current!.getRow(rowKey);
console.log('%cinitEditor', 'color: orange;');
console.log(this, editor, row);
// let row = this.$refs.myTreeGrid.getRow(rowKey);
// switch (row.type) {
// case 'string':
// case 'number':
// this['inputRow' + rowKey].val(cellvalue);
// break;
// case 'align':
// this.myDropDownList.val(cellvalue);
// break;
// case 'color':
// if (rowKey === '3') {
// this.myColorPicker1.setColor(cellvalue);
// } else {
// this.myColorPicker2.setColor(cellvalue);
// }
// break;
// case 'bool':
// this.myCheckBox.val(cellvalue);
// break;
// }
},
text: 'Value',
width: 230,
}
],
inRefs: [],
source: dataAdapter
}
}
public render() {
return (
<div>
<JqxButton theme={'material-purple'} onClick={this.click}>Check</JqxButton>
<JqxTreeGrid theme={'material-purple'} ref={this.myTreeGrid}
onCellValueChanged={this.cellValueChanged}
source={this.state.source}
altRows={true}
autoRowHeight={true}
editable={true}
columns={this.state.columns}
/>
</div>
);
}
private setRef = (ref: any) => {
this.references.push(ref);
// // console.log(7007, ref, this.state.inRefs);
// console.log(7007, ref);
/* tslint:disable:no-string-literal */
console.log(ref)
ref = React.createRef<JqxInput>();
console.log(ref);
// this.state.inRefs.push(this['ref']);
return ref;
}
// Event handling
private cellValueChanged(event: any): void {
// const args = event.args;
// this.rowKey = args.key;
// this.updateButtons('Select');
// console.log(1001, event, this.state.inRefs);
console.log(1001, this.state.inRefs);
}
private click(event: any): void {
console.log(this.input.current!, this.input.current!.val());
}
}
export default App; | the_stack |
import React, { useRef, Key } from "react"
import cn from "classnames"
import { useListBox, useListBoxSection, useOption } from "@react-aria/listbox"
import { Node } from "@react-types/shared"
import { SelectState } from "@react-stately/select"
import { ComboBoxState } from "@react-stately/combobox"
import { FocusScope } from "@react-aria/focus"
import {
DismissButton,
OverlayContainer,
useOverlay,
useOverlayPosition,
} from "@react-aria/overlays"
import { mergeProps } from "@react-aria/utils"
import { PressResponder, useHover } from "@react-aria/interactions"
import { Loader } from "../loader/Loader"
import { Icon } from "../icon/Icon"
import { Separator } from "../separator/Separator"
/**
* A ListBox is an abstraction over components that render a list of options that are individually selectable.
*
* Currently, `Select` & `ComboBox` are `ListBox`es
*/
/** Value for a single Option inside this Select */
export type ListBoxOption<OptionKey extends Key> = {
/** A string that uniquely identifies this option */
key: OptionKey
/** The main text to display within this option */
title: string
/** An icon to show before the title */
leadingIcon?: string
/** An icon to show after the title */
trailingIcon?: string
/** An image to show before the title */
leadingImageSrc?: string
/** The secondary text to display within this option */
description?: string
}
type ListBoxOverlayProps<OptionKey extends Key> = {
/** An HTML ID attribute that will be attached to the the rendered component. Useful for targeting it from tests */
id?: string
/** A string describing what this ListBox represents */
label: string
/** Ref of the ListBox container. This is used to position the overlay */
containerRef: React.RefObject<HTMLElement>
/** A ref object that will be attached to the Options container */
listBoxRef?: React.RefObject<HTMLUListElement>
/** A ref object that will be attached to the overlay element */
overlayRef?: React.RefObject<HTMLDivElement>
/** The ListBox's global state */
state:
| SelectState<ListBoxOption<OptionKey>>
| ComboBoxState<ListBoxOption<OptionKey>> // TODO:: Find a more generic type for this
/** An optional footer to render within the Overlay, after the Body */
footer?: React.ReactElement
loading?: boolean
/** Additional props that will be spread over the overlay component */
listBoxProps?: React.HTMLAttributes<Element>
}
/** An overlay that renders individual ListBox Options */
export function ListBoxOverlay<OptionKey extends Key = string>({
id,
label,
containerRef,
listBoxRef: _listBoxRef,
overlayRef: _overlayRef,
state,
footer,
loading,
listBoxProps: otherProps = {},
}: ListBoxOverlayProps<OptionKey>) {
// The following hook calls are conditional, but they should not be a problem because they'll be called the same number of times across renders
// listBoxRef & overlayRef values do (should) not change across renders
const listBoxRef = _listBoxRef || useRef<HTMLUListElement>(null)
const overlayRef = _overlayRef || useRef<HTMLDivElement>(null)
const { listBoxProps } = useListBox(
{
id,
label,
disallowEmptySelection: true,
autoFocus: state.focusStrategy,
...otherProps,
},
state,
listBoxRef
)
const { overlayProps } = useOverlay(
{
onClose: state.close,
isDismissable: true,
shouldCloseOnBlur: true,
},
overlayRef
)
const { overlayProps: positionProps, placement } = useOverlayPosition({
overlayRef,
targetRef: containerRef,
offset: 4,
containerPadding: 0,
shouldFlip: true,
onClose: state.close,
})
// Figure out button dimensions so we can size the overlay
const containerDimensions = containerRef.current?.getBoundingClientRect()
return (
<OverlayContainer>
<FocusScope restoreFocus>
<div
id="listbox-overlay"
{...mergeProps(overlayProps, positionProps)}
ref={overlayRef}
style={{
...positionProps.style,
left: containerDimensions?.left,
width: containerDimensions?.width,
}}
>
<DismissButton onDismiss={state.close} />
<ul
ref={listBoxRef}
{...listBoxProps}
className={cn("menu", {
"animate-slide-bottom": placement === "top",
"animate-slide-top": placement === "bottom",
})}
>
<div
className="relative overflow-y-auto"
style={{ maxHeight: "350px" }}
>
{state.collection.size === 0 && !loading && (
<ListBoxEmptyOption />
)}
{[...state.collection].map((option) => {
if (option.type === "section") {
return (
<ListBoxSection
key={option.key}
title={option.rendered as string}
state={state}
section={option}
/>
)
} else if (option.type === "item") {
return (
<ListBoxOption
key={option.key}
option={option}
state={state}
/>
)
} else {
return null
}
})}
{loading && <ListBoxLoadingOption />}
</div>
<div className="static">{footer}</div>
</ul>
</div>
<DismissButton onDismiss={state.close} />
</FocusScope>
</OverlayContainer>
)
}
type ListBoxSectionProps<OptionKey extends Key> = {
/** Title for this Section */
title: string
/** A group of similar options, only visual */
section: Node<ListBoxOption<OptionKey>>
/** The global Select state */
state:
| SelectState<ListBoxOption<OptionKey>>
| ComboBoxState<ListBoxOption<OptionKey>> // TODO:: Find a more generic type for this
}
/** A single ListBox Section. This is usually used to (visually) group similar `ListBoxOption`s together */
export function ListBoxSection<OptionKey extends Key = string>({
title,
section,
state,
}: ListBoxSectionProps<OptionKey>) {
const {
groupProps,
headingProps,
itemProps: optionProps,
} = useListBoxSection({
heading: title,
})
return (
<section lens-role="listbox-section" {...groupProps} className={cn("p-2")}>
<div
{...headingProps}
className={cn(
"mb-2",
"text-xs uppercase text-gray-500 dark:text-gray-400",
"select-none"
)}
>
{title}
</div>
<li {...optionProps}>
<ul>
{[...section.childNodes].map((i) => (
<ListBoxOption key={i.key} option={i} state={state} />
))}
</ul>
</li>
</section>
)
}
type ListBoxOptionProps<OptionKey extends Key> = {
/** The option to render */
option: Node<ListBoxOption<OptionKey>>
/** The global Select state */
state:
| SelectState<ListBoxOption<OptionKey>>
| ComboBoxState<ListBoxOption<Key>> // TODO:: Find a more generic type for this
}
/** A single `ListBox` Option */
export function ListBoxOption<OptionKey extends Key = string>({
option,
state,
}: ListBoxOptionProps<OptionKey>) {
const ref = useRef<HTMLLIElement>(null)
const isDisabled = state.disabledKeys.has(option.key)
const isFocused = state.selectionManager.focusedKey === option.key
const { hoverProps, isHovered } = useHover({ isDisabled })
const { optionProps: domProps } = useOption(
{
key: option.key,
isDisabled,
shouldSelectOnPressUp: true,
shouldFocusOnHover: true,
shouldUseVirtualFocus: true,
},
state,
ref
)
const { description, leadingIcon, trailingIcon, leadingImageSrc } =
option.props as ListBoxOption<OptionKey>
return (
<li
ref={ref}
lens-role="listbox-option"
{...hoverProps}
{...domProps}
className={cn("flex flex-col", "p-3", "cursor-pointer", {
"bg-gray-100 dark:bg-gray-800": isFocused || isHovered,
})}
>
<div className="flex items-center space-x-2">
{leadingIcon && (
<Icon name={leadingIcon} size="sm" className="text-gray-600" />
)}
{leadingImageSrc && (
<img src={leadingImageSrc} className="rounded-full w-6" />
)}
<div className="text-gray-800 dar:text-gray-100 font-medium">
{option.rendered}
</div>
{trailingIcon && (
<Icon name={trailingIcon} size="xs" className="text-gray-600" />
)}
</div>
{description && <div className="text-gray-500">{description}</div>}
</li>
)
}
/* A specialized Option that is to be used to represent the loading state for a ListBox */
export function ListBoxLoadingOption() {
return (
<li className={cn("flex flex-col justify-center items-center", "m-3")}>
<Loader size="md" />
</li>
)
}
type ListBoxErrorOptionProps = {
children?: string
}
/* A specialized Option that is to be used to represent the error state for a ListBox */
export function ListBoxErrorOption({
children = "An error occurred",
}: ListBoxErrorOptionProps) {
return (
<li className={cn("flex flex-col justify-center items-center", "m-2")}>
<Icon name="alert-circle" />
<span className="mt-2">{children}</span>
</li>
)
}
type ListBoxEmptyOptionProps = {
children?: string
}
export function ListBoxEmptyOption({
children = "No matches",
}: ListBoxEmptyOptionProps) {
return (
<li className={cn("flex flex-col justify-center items-center", "m-2")}>
<Icon name="slash" />
<span className="mt-2">{children}</span>
</li>
)
}
type ListBoxFooterProps = React.PropsWithChildren<{
onPress?: () => void
}>
/** A static footer */
export function ListBoxFooter({ children, onPress }: ListBoxFooterProps) {
return (
<PressResponder onPress={onPress}>
<Separator />
<div className="p-3 whitespace-nowrap">{children}</div>
</PressResponder>
)
} | the_stack |
import * as testUtils from "./helper/testUtils";
import { buyMarket, sellMarket, TOKEN_CODES } from "./helper/testUtils";
import { DarknodeRegistryContract } from "./bindings/darknode_registry";
import { OrderbookContract } from "./bindings/orderbook";
import { RenExBalancesContract } from "./bindings/ren_ex_balances";
import { RenExBrokerVerifierContract } from "./bindings/ren_ex_broker_verifier";
import { RenExSettlementContract } from "./bindings/ren_ex_settlement";
import { RenExTokensContract } from "./bindings/ren_ex_tokens";
const {
RepublicToken,
DGXToken,
DarknodeRegistry,
Orderbook,
RenExTokens,
RenExSettlement,
RenExBalances,
RenExBrokerVerifier,
} = testUtils.contracts;
contract("RenExSettlement", function (accounts: string[]) {
const darknode = accounts[2];
const broker = accounts[3];
let tokenAddresses: Map<number, testUtils.BasicERC20>;
let orderbook: OrderbookContract;
let renExSettlement: RenExSettlementContract;
let renExBalances: RenExBalancesContract;
let renExTokens: RenExTokensContract;
let buyID_1: string, sellID_1: string;
let buyID_2: string, sellID_2: string;
let buyID_3, sellID_3: string;
let buyID_4;
const BUY1 = [web3.utils.sha3("0"), 1, buyMarket("0x3", "0x7"), 10, 10000, 0];
const SELL1 = [web3.utils.sha3("1"), 1, sellMarket("0x3", "0x7"), 10, 1000, 0];
const BUY2 = [web3.utils.sha3("2"), 1, buyMarket(TOKEN_CODES.BTC, TOKEN_CODES.ETH), 12, 10000, 0];
const SELL2 = [web3.utils.sha3("3"), 1, sellMarket(TOKEN_CODES.BTC, TOKEN_CODES.ETH), 12, 1000, 0];
const BUY3 = [web3.utils.sha3("4"), 1, buyMarket(TOKEN_CODES.BTC, TOKEN_CODES.ETH), 15, 10000, 0];
const SELL3 = [web3.utils.sha3("5"), 1, sellMarket(TOKEN_CODES.BTC, TOKEN_CODES.ETH), 12, 10000, 0];
const BUY4 = [web3.utils.sha3("6"), 1, buyMarket(TOKEN_CODES.BTC, TOKEN_CODES.ETH), 17, 10000, 0];
const SELL4 = [web3.utils.sha3("7"), 1, sellMarket(TOKEN_CODES.BTC, TOKEN_CODES.ETH), 12, 1000, 0];
const SELL5 = [web3.utils.sha3("8"), 2, sellMarket(TOKEN_CODES.BTC, TOKEN_CODES.ETH), 10, 1000, 0];
const renexID = testUtils.Settlements.RenEx;
before(async function () {
const ren = await RepublicToken.deployed();
tokenAddresses = new Map()
.set(TOKEN_CODES.BTC, testUtils.MockBTC)
.set(TOKEN_CODES.ETH, testUtils.MockETH)
.set(TOKEN_CODES.DGX, await DGXToken.deployed())
.set(TOKEN_CODES.REN, ren);
let dnr: DarknodeRegistryContract = await DarknodeRegistry.deployed();
orderbook = await Orderbook.deployed();
renExTokens = await RenExTokens.deployed();
renExSettlement = await RenExSettlement.deployed();
renExBalances = await RenExBalances.deployed();
// Register darknode
await ren.transfer(darknode, testUtils.minimumBond);
await ren.approve(dnr.address, testUtils.minimumBond, { from: darknode });
await dnr.register(darknode, testUtils.PUBK("1"), { from: darknode });
await testUtils.waitForEpoch(dnr);
// Register broker
const renExBrokerVerifier: RenExBrokerVerifierContract =
await RenExBrokerVerifier.deployed();
await renExBrokerVerifier.registerBroker(broker);
buyID_1 = await renExSettlement.hashOrder.apply(this, [...BUY1]);
sellID_1 = await renExSettlement.hashOrder.apply(this, [...SELL1]);
buyID_2 = await renExSettlement.hashOrder.apply(this, [...BUY2]);
sellID_2 = await renExSettlement.hashOrder.apply(this, [...SELL2]);
buyID_3 = await renExSettlement.hashOrder.apply(this, [...BUY3]);
sellID_3 = await renExSettlement.hashOrder.apply(this, [...SELL3]);
buyID_4 = await renExSettlement.hashOrder.apply(this, [...BUY4]);
// Buys
await testUtils.openOrder(orderbook, renexID, broker, accounts[5], buyID_1);
await testUtils.openOrder(orderbook, renexID, broker, accounts[6], buyID_2);
await testUtils.openOrder(orderbook, renexID, broker, accounts[7], buyID_3);
await testUtils.openOrder(orderbook, renexID, broker, accounts[8], buyID_4);
// Sells
await testUtils.openOrder(orderbook, renexID, broker, accounts[6], sellID_1);
await testUtils.openOrder(orderbook, renexID, broker, accounts[5], sellID_2);
await testUtils.openOrder(orderbook, renexID, broker, accounts[8], sellID_3);
await orderbook.confirmOrder(buyID_1, sellID_1, { from: darknode });
await orderbook.confirmOrder(buyID_2, sellID_2, { from: darknode });
await orderbook.confirmOrder(buyID_3, sellID_3, { from: darknode });
});
it("can update orderbook", async () => {
const previousOrderbook = await renExSettlement.orderbookContract();
// [CHECK] The function validates the new orderbook
await renExSettlement.updateOrderbook(testUtils.NULL)
.should.be.rejectedWith(null, /revert/);
// [ACTION] Update the orderbook to another address
await renExSettlement.updateOrderbook(renExSettlement.address);
// [CHECK] Verify the orderbook address has been updated
(await renExSettlement.orderbookContract()).should.equal(renExSettlement.address);
// [CHECK] Only the owner can update the orderbook
await renExSettlement.updateOrderbook(previousOrderbook, { from: accounts[1] })
.should.be.rejectedWith(null, /revert/); // not owner
// [RESET] Reset the orderbook to the previous address
await renExSettlement.updateOrderbook(previousOrderbook);
(await renExSettlement.orderbookContract()).should.equal(previousOrderbook);
});
it("can update renex tokens", async () => {
const previousRenExTokens = await renExSettlement.renExTokensContract();
// [CHECK] The function validates the new renex tokens
await renExSettlement.updateRenExTokens(testUtils.NULL)
.should.be.rejectedWith(null, /revert/);
// [ACTION] Update the renex tokens to another address
await renExSettlement.updateRenExTokens(renExSettlement.address);
// [CHECK] Verify the renex tokens address has been updated
(await renExSettlement.renExTokensContract()).should.equal(renExSettlement.address);
// [CHECK] Only the owner can update the renex tokens
await renExSettlement.updateRenExTokens(previousRenExTokens, { from: accounts[1] })
.should.be.rejectedWith(null, /revert/); // not owner
// [RESET] Reset the renex tokens to the previous address
await renExSettlement.updateRenExTokens(previousRenExTokens);
(await renExSettlement.renExTokensContract()).should.equal(previousRenExTokens);
});
it("can update renex balances", async () => {
const previousRenExBalances = await renExSettlement.renExBalancesContract();
// [CHECK] The function validates the new renex balances
await renExSettlement.updateRenExBalances(testUtils.NULL)
.should.be.rejectedWith(null, /revert/);
// [ACTION] Update the renex balances to another address
await renExSettlement.updateRenExBalances(renExSettlement.address);
// [CHECK] Verify the renex balances address has been updated
(await renExSettlement.renExBalancesContract()).should.equal(renExSettlement.address);
// [CHECK] Only the owner can update the renex balances
await renExSettlement.updateRenExBalances(previousRenExBalances, { from: accounts[1] })
.should.be.rejectedWith(null, /revert/); // not owner
// [RESET] Reset the renex balances to the previous address
await renExSettlement.updateRenExBalances(previousRenExBalances);
(await renExSettlement.renExBalancesContract()).should.equal(previousRenExBalances);
});
it("can update submission gas price limit", async () => {
const previousGasPriceLimit = await renExSettlement.submissionGasPriceLimit();
// [ACTION] Update to 0.1 GWEI
await renExSettlement.updateSubmissionGasPriceLimit(0.1 * testUtils.GWEI);
// [CHECK] Should now be 0.1 GWEI
(await renExSettlement.submissionGasPriceLimit()).should.be.bignumber.equal(0.1 * testUtils.GWEI);
// [CHECK] Non-owner can't update
await renExSettlement.updateSubmissionGasPriceLimit(100 * testUtils.GWEI, { from: accounts[1] })
.should.be.rejectedWith(null, /revert/); // not owner
// [CHECK] Owner can't set to less than 0.1 GWEI
await renExSettlement.updateSubmissionGasPriceLimit(0.01 * testUtils.GWEI)
.should.be.rejectedWith(null, /invalid new submission gas price limit/);
// [SETUP] Reset
await renExSettlement.updateSubmissionGasPriceLimit(previousGasPriceLimit);
(await renExSettlement.submissionGasPriceLimit()).should.be.bignumber.equal(previousGasPriceLimit);
});
it("can update slasher address", async () => {
const previousSlasher = await renExSettlement.slasherAddress();
// [CHECK] The function validates the new settlement contract
await renExSettlement.updateSlasher(testUtils.NULL)
.should.be.rejectedWith(null, /revert/);
// [ACTION] Update the settlement contract to another address
await renExSettlement.updateSlasher(renExSettlement.address);
// [CHECK] Verify the settlement contract address has been updated
(await renExSettlement.slasherAddress()).should.equal(renExSettlement.address);
// [CHECK] Only the owner can update the settlement contract
await renExSettlement.updateSlasher(previousSlasher, { from: accounts[1] })
.should.be.rejectedWith(null, /revert/); // not owner
// [RESET] Reset the settlement contract to the previous address
await renExSettlement.updateSlasher(previousSlasher);
(await renExSettlement.slasherAddress()).should.equal(previousSlasher);
});
it("submitOrder", async () => {
// sellID_1?
await renExSettlement.submitOrder.apply(this, [...SELL1]);
// buyID_1?
await renExSettlement.submitOrder.apply(this, [...BUY1]);
// sellID_2?
await renExSettlement.submitOrder.apply(this, [...SELL2]);
// buyID_2?
await renExSettlement.submitOrder.apply(this, [...BUY2]);
// sellID_3?
await renExSettlement.submitOrder.apply(this, [...SELL3]);
// buyID_3?
await renExSettlement.submitOrder.apply(this, [...BUY3]);
});
it("submitOrder (rejected)", async () => {
// Can't submit order twice:
await renExSettlement.submitOrder.apply(this, [...SELL2])
.should.be.rejectedWith(null, /order already submitted/);
// Can't submit order that's not in orderbook (different order details):
await renExSettlement.submitOrder.apply(this, [...SELL4])
.should.be.rejectedWith(null, /unconfirmed order/);
// Can't submit order that's not confirmed
await renExSettlement.submitOrder.apply(this, [...BUY4])
.should.be.rejectedWith(null, /unconfirmed order/);
});
it("settle checks the buy order status", async () => {
await renExSettlement.settle(
testUtils.randomID(),
sellID_1,
).should.be.rejectedWith(null, /invalid buy status/);
});
it("settle checks the sell order status", async () => {
await renExSettlement.settle(
buyID_1,
testUtils.randomID(),
).should.be.rejectedWith(null, /invalid sell status/);
});
it("settle checks that the orders are compatible", async () => {
// Two buys
await renExSettlement.settle(
buyID_1,
buyID_1,
).should.be.rejectedWith(null, /incompatible orders/);
// Two sells
await renExSettlement.settle(
sellID_1,
sellID_1,
).should.be.rejectedWith(null, /incompatible orders/);
// Orders that aren't matched to one another
await renExSettlement.settle(
buyID_2,
sellID_3,
).should.be.rejectedWith(null, /unconfirmed orders/);
});
it("settle checks the token registration", async () => {
// Buy token that is not registered
await renExSettlement.settle(
buyID_1,
sellID_1,
).should.be.rejectedWith(null, /unregistered priority token/);
// Sell token that is not registered
await renExTokens.deregisterToken(TOKEN_CODES.ETH);
await renExSettlement.settle(
buyID_2,
sellID_2,
).should.be.rejectedWith(null, /unregistered secondary token/);
await renExTokens.registerToken(TOKEN_CODES.ETH, tokenAddresses.get(TOKEN_CODES.ETH).address, 18);
});
it("should fail for excessive gas price", async () => {
// [SETUP] Set gas price limit to 0.1 GWEI
const previousGasPriceLimit = await renExSettlement.submissionGasPriceLimit();
const LOW_GAS = 100000000;
await renExSettlement.updateSubmissionGasPriceLimit(LOW_GAS);
// [CHECK] Calling submitOrder with a higher gas will fail
await renExSettlement.submitOrder.apply(this, [...SELL5, { gasPrice: LOW_GAS + 1 }])
.should.be.rejectedWith(null, /gas price too high/);
// [SETUP] Reset gas price limit
await renExSettlement.updateSubmissionGasPriceLimit(previousGasPriceLimit);
});
}); | the_stack |
/*
* Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info.
*/
namespace LiteMol.Visualization.Surface {
"use strict";
import Data = Core.Geometry.Surface
import ChunkedArray = Core.Utils.ChunkedArray
interface Context {
data: Data,
computation: Core.Computation.Context,
geom: Geometry,
vertexCount: number,
triCount: number,
pickColorBuffer?: Float32Array;
pickTris?: ChunkedArray<number>;
pickPlatesVertices?: ChunkedArray<number>;
pickPlatesTris?: ChunkedArray<number>;
pickPlatesColors?: ChunkedArray<number>;
platesVertexCount?: number;
}
function sortAnnotation(ctx: Context) {
let indices = new Int32Array(ctx.data.annotation!.length);
let annotation = ctx.data.annotation!;
for (let i = 0, _b = indices.length; i < _b; i++) indices[i] = i;
Array.prototype.sort.call(indices, function (a: number, b: number) {
let ret = annotation[a] - annotation[b];
if (!ret) return a - b;
return ret;
});
return indices;
}
function splice(start: number, end: number, indices: Int32Array, map: Selection.VertexMapBuilder) {
let currentStart = start;
let currentEnd = start + 1;
while (currentStart < end) {
while (currentEnd < end && indices[currentEnd] - indices[currentEnd - 1] < 1.1) currentEnd++;
map.addVertexRange(indices[currentStart], indices[currentEnd - 1] + 1);
currentStart = currentEnd;
currentEnd = currentEnd + 1;
}
}
function createVertexMap(ctx: Context) {
let indices = sortAnnotation(ctx);
let annotation = ctx.data.annotation!;
let count = 1;
for (let i = 0, _b = indices.length - 1; i < _b; i++) {
if (annotation[indices[i]] !== annotation[indices[i + 1]]) count++;
}
let map = new Selection.VertexMapBuilder(count);
let xs = new Int32Array(indices.length);
for (let i = 0, _b = indices.length; i < _b; i++) {
xs[i] = annotation[indices[i]];
}
let currentAnnotation = annotation[indices[0]];
map.startElement(currentAnnotation);
for (let i = 0, _b = indices.length; i < _b; i++) {
let an = annotation[indices[i]];
if (an !== currentAnnotation) {
map.endElement();
map.startElement(an);
currentAnnotation = an;
}
let start = i;
i++;
while (an === annotation[indices[i]]) i++;
let end = i;
i--;
splice(start, end, indices, map);
}
map.endElement();
return map.getMap();
}
function createFullMap(ctx: Context) {
let map = new Selection.VertexMapBuilder(1);
map.startElement(0);
map.addVertexRange(0, ctx.vertexCount);
map.endElement();
return map.getMap();
}
async function computeVertexMap(ctx: Context) {
await ctx.computation.updateProgress('Computing selection map...');
if (ctx.data.annotation) {
ctx.geom.elementToVertexMap = createVertexMap(ctx);
} else {
ctx.geom.elementToVertexMap = createFullMap(ctx);
}
}
const chunkSize = 100000;
async function computePickPlatesChunk(start: number, ctx: Context) {
let tri = ctx.data.triangleIndices;
let ids = ctx.data.annotation!;
let pickPlatesVertices = ctx.pickPlatesVertices!;
let pickPlatesTris = ctx.pickPlatesTris!;
let pickPlatesColors = ctx.pickPlatesColors!;
let vs = ctx.data.vertices;
let color = { r: 0.45, g: 0.45, b: 0.45 };
let pickTris = ctx.pickTris!;
let platesVertexCount = 0;
for (let i = start, _b = Math.min(start + chunkSize, ctx.triCount); i < _b; i++) {
let a = tri[3 * i], b = tri[3 * i + 1], c = tri[3 * i + 2];
let aI = ids[a], bI = ids[b], cI = ids[c];
if (aI === bI && bI === cI) {
ChunkedArray.add3(pickTris, a, b, c);
continue;
}
let s = -1;
if (aI === bI || aI === cI) s = aI;
else if (bI === cI) s = bI;
ChunkedArray.add3(pickPlatesVertices, vs[3 * a], vs[3 * a + 1], vs[3 * a + 2]);
ChunkedArray.add3(pickPlatesVertices, vs[3 * b], vs[3 * b + 1], vs[3 * b + 2]);
ChunkedArray.add3(pickPlatesVertices, vs[3 * c], vs[3 * c + 1], vs[3 * c + 2]);
ChunkedArray.add3(pickPlatesTris, platesVertexCount++, platesVertexCount++, platesVertexCount++);
if (s < 0) {
color.r = 0; color.g = 0; color.b = 0;
} else {
Selection.Picking.assignPickColor(s, color);
}
ChunkedArray.add4(pickPlatesColors, color.r, color.g, color.b, 0.0);
ChunkedArray.add4(pickPlatesColors, color.r, color.g, color.b, 0.0);
ChunkedArray.add4(pickPlatesColors, color.r, color.g, color.b, 0.0);
}
ctx.platesVertexCount = ctx.platesVertexCount! + platesVertexCount;
}
async function computePickPlatesChunks(ctx: Context) {
let started = Core.Utils.PerformanceMonitor.currentTime();
for (let start = 0; start < ctx.triCount; start += chunkSize) {
let time = Core.Utils.PerformanceMonitor.currentTime();
if (time - started > Core.Computation.UpdateProgressDelta) {
started = time;
await ctx.computation.updateProgress('Creating selection geometry...', true, start, ctx.triCount);
}
computePickPlatesChunk(start, ctx);
}
}
function assignPickColors(ctx: Context) {
let color = { r: 0.45, g: 0.45, b: 0.45 },
ids = ctx.data.annotation!;
ctx.pickTris = ChunkedArray.forIndexBuffer(ctx.triCount);
let pickColorBuffer = ctx.pickColorBuffer!;
for (let i = 0, _b = ctx.vertexCount; i < _b; i++) {
let id = ids[i];
if (id >= 0) {
Selection.Picking.assignPickColor(id + 1, color);
pickColorBuffer[i * 4] = color.r;
pickColorBuffer[i * 4 + 1] = color.g;
pickColorBuffer[i * 4 + 2] = color.b;
}
}
}
function createFullPickGeometry(attr: BasicAttributes, ctx: Context) {
let pickGeometry = new THREE.BufferGeometry();
pickGeometry.addAttribute('position', attr.position);
pickGeometry.addAttribute('index', attr.index);
pickGeometry.addAttribute('pColor', new THREE.BufferAttribute(ctx.pickColorBuffer, 4));
ctx.geom.pickGeometry = pickGeometry;
pickGeometry = new THREE.BufferGeometry();
pickGeometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(0), 3));
pickGeometry.addAttribute('index', new THREE.BufferAttribute(new Uint32Array(0), 1));
pickGeometry.addAttribute('pColor', new THREE.BufferAttribute(new Float32Array(0), 4));
ctx.geom.pickPlatesGeometry = pickGeometry;
}
function createPickGeometry(attr: BasicAttributes, ctx: Context) {
let pickGeometry = new THREE.BufferGeometry();
pickGeometry.addAttribute('position', attr.position);
pickGeometry.addAttribute('index', attr.index);
pickGeometry.addAttribute('pColor', new THREE.BufferAttribute(ctx.pickColorBuffer, 4));
ctx.geom.pickGeometry = pickGeometry;
pickGeometry = new THREE.BufferGeometry();
pickGeometry.addAttribute('position', new THREE.BufferAttribute(ChunkedArray.compact(ctx.pickPlatesVertices!), 3));
pickGeometry.addAttribute('index', new THREE.BufferAttribute(ChunkedArray.compact(ctx.pickPlatesTris!), 1));
pickGeometry.addAttribute('pColor', new THREE.BufferAttribute(ChunkedArray.compact(ctx.pickPlatesColors!), 4));
ctx.geom.pickPlatesGeometry = pickGeometry;
}
function addWireframeEdge(edges: ChunkedArray<number>, included: Core.Utils.FastSet<number>, a: number, b: number) {
if (a > b) {
// swap
let t = a; a = b; b = t;
}
if (included.add((a + b) * (a + b + 1) / 2 + b /* cantor pairing function */)) {
ChunkedArray.add2(edges, a, b);
}
}
function buildWireframeIndices(ctx: Context) {
let tris = ctx.data.triangleIndices;
let edges = ChunkedArray.create<number>(size => new Uint32Array(size), (1.5 * ctx.triCount) | 0, 2);
let includedEdges = Core.Utils.FastSet.create<number>();
for (let i = 0, _b = tris.length; i < _b; i += 3) {
let a = tris[i], b = tris[i + 1], c = tris[i + 2];
addWireframeEdge(edges, includedEdges, a, b);
addWireframeEdge(edges, includedEdges, a, c);
addWireframeEdge(edges, includedEdges, b, c);
}
return new THREE.BufferAttribute(ChunkedArray.compact(edges), 1);
}
type BasicAttributes = { position: THREE.BufferAttribute, index: THREE.BufferAttribute }
function makeBasicAttributes(ctx: Context): BasicAttributes {
return {
position: new THREE.BufferAttribute(ctx.data.vertices, 3),
index: new THREE.BufferAttribute(ctx.data.triangleIndices, 1)
};
}
function createGeometry(attr: BasicAttributes, isWireframe: boolean, ctx: Context) {
let geometry = new THREE.BufferGeometry();
geometry.addAttribute('position', attr.position);
geometry.addAttribute('normal', new THREE.BufferAttribute(ctx.data.normals, 3));
geometry.addAttribute('color', new THREE.BufferAttribute(new Float32Array(ctx.data.vertices.length), 3));
if (isWireframe) {
geometry.addAttribute('index', buildWireframeIndices(ctx));
} else {
geometry.addAttribute('index', attr.index);
}
ctx.geom.geometry = geometry;
ctx.geom.vertexStateBuffer = new THREE.BufferAttribute(new Float32Array(ctx.data.vertices.length), 1);
geometry.addAttribute('vState', ctx.geom.vertexStateBuffer);
}
async function computePickGeometry(attr: BasicAttributes, ctx: Context) {
await ctx.computation.updateProgress('Creating selection geometry...');
ctx.pickColorBuffer = new Float32Array(ctx.vertexCount * 4);
if (!ctx.data.annotation) {
createFullPickGeometry(attr, ctx);
return;
} else {
assignPickColors(ctx);
ctx.pickPlatesVertices = ChunkedArray.forVertex3D(Math.max(ctx.vertexCount / 10, 10));
ctx.pickPlatesTris = ChunkedArray.forIndexBuffer(Math.max(ctx.triCount / 10, 10));
ctx.pickPlatesColors = ChunkedArray.create<number>(s => new Float32Array(s), Math.max(ctx.vertexCount / 10, 10), 4);
ctx.platesVertexCount = 0;
await computePickPlatesChunks(ctx)
createPickGeometry(attr, ctx);
}
}
export async function buildGeometry(data: Data, computation: Core.Computation.Context, isWireframe: boolean): Promise<Geometry> {
let ctx: Context = {
data,
computation,
geom: new Geometry(),
vertexCount: (data.vertices.length / 3) | 0,
triCount: (data.triangleIndices.length / 3) | 0
};
await computation.updateProgress('Creating geometry...');
await Core.Geometry.Surface.computeNormals(data).run(computation);
await Core.Geometry.Surface.computeBoundingSphere(data).run(computation);
const attr = makeBasicAttributes(ctx);
await computeVertexMap(ctx);
await computePickGeometry(attr, ctx);
createGeometry(attr, isWireframe, ctx);
ctx.geom.vertexToElementMap = ctx.data.annotation!;
return ctx.geom;
}
export class Geometry extends GeometryBase {
geometry: THREE.BufferGeometry = <any>void 0;
vertexToElementMap: number[] = <any>void 0;
elementToVertexMap: Selection.VertexMap = <any>void 0;
pickGeometry: THREE.BufferGeometry = <any>void 0;
pickPlatesGeometry: THREE.BufferGeometry = <any>void 0;
vertexStateBuffer: THREE.BufferAttribute = <any>void 0;
dispose() {
this.geometry.dispose();
if (this.pickGeometry) {
this.pickGeometry.dispose();
this.pickPlatesGeometry.dispose();
}
}
constructor() {
super();
}
}
} | the_stack |
import { colord, random, getFormat, Colord, AnyColor } from "../src/";
import { fixtures, lime, saturationLevels } from "./fixtures";
it("Converts between HEX, RGB, HSL and HSV color models properly", () => {
for (const fixture of fixtures) {
expect(colord(fixture.rgb).toHex()).toBe(fixture.hex);
expect(colord(fixture.hsl).toHex()).toBe(fixture.hex);
expect(colord(fixture.hsv).toHex()).toBe(fixture.hex);
expect(colord(fixture.hex).toRgb()).toMatchObject({ ...fixture.rgb, a: 1 });
expect(colord(fixture.hsl).toRgb()).toMatchObject({ ...fixture.rgb, a: 1 });
expect(colord(fixture.hsv).toRgb()).toMatchObject({ ...fixture.rgb, a: 1 });
expect(colord(fixture.hex).toHsl()).toMatchObject({ ...fixture.hsl, a: 1 });
expect(colord(fixture.rgb).toHsl()).toMatchObject({ ...fixture.hsl, a: 1 });
expect(colord(fixture.hsv).toHsl()).toMatchObject({ ...fixture.hsl, a: 1 });
expect(colord(fixture.hex).toHsv()).toMatchObject({ ...fixture.hsv, a: 1 });
expect(colord(fixture.rgb).toHsv()).toMatchObject({ ...fixture.hsv, a: 1 });
expect(colord(fixture.hsl).toHsv()).toMatchObject({ ...fixture.hsv, a: 1 });
}
});
it("Parses and converts a color", () => {
for (const format in lime) {
const instance = colord(lime[format] as AnyColor);
expect(instance.toHex()).toBe(lime.hex);
expect(instance.toRgb()).toMatchObject(lime.rgba);
expect(instance.toRgbString()).toBe(lime.rgbString);
expect(instance.toHsl()).toMatchObject(lime.hsla);
expect(instance.toHslString()).toBe(lime.hslString);
expect(instance.toHsv()).toMatchObject(lime.hsva);
}
});
it("Adds alpha number to RGB and HSL strings only if the color has an opacity", () => {
expect(colord("rgb(0, 0, 0)").toRgbString()).toBe("rgb(0, 0, 0)");
expect(colord("hsl(0, 0%, 0%)").toHslString()).toBe("hsl(0, 0%, 0%)");
expect(colord("rgb(0, 0, 0)").alpha(0.5).toRgbString()).toBe("rgba(0, 0, 0, 0.5)");
expect(colord("hsl(0, 0%, 0%)").alpha(0.5).toHslString()).toBe("hsla(0, 0%, 0%, 0.5)");
});
it("Parses modern RGB functional notations", () => {
expect(colord("rgb(0% 50% 100%)").toRgb()).toMatchObject({ r: 0, g: 128, b: 255, a: 1 });
expect(colord("rgb(10% 20% 30% / 33%)").toRgb()).toMatchObject({ r: 26, g: 51, b: 77, a: 0.33 });
expect(colord("rgba(10% 20% 30% / 0.5)").toRgb()).toMatchObject({ r: 26, g: 51, b: 77, a: 0.5 });
});
it("Parses modern HSL functional notations", () => {
expect(colord("hsl(120deg 100% 50%)").toHsl()).toMatchObject({ h: 120, s: 100, l: 50, a: 1 });
expect(colord("hsl(10deg 20% 30% / 0.1)").toHsl()).toMatchObject({ h: 10, s: 20, l: 30, a: 0.1 });
expect(colord("hsl(10deg 20% 30% / 90%)").toHsl()).toMatchObject({ h: 10, s: 20, l: 30, a: 0.9 });
expect(colord("hsl(90deg 50% 50%/50%)").toHsl()).toMatchObject({ h: 90, s: 50, l: 50, a: 0.5 });
});
it("Supports HEX4 and HEX8 color models", () => {
expect(colord("#ffffffff").toRgb()).toMatchObject({ r: 255, g: 255, b: 255, a: 1 });
expect(colord("#80808080").toRgb()).toMatchObject({ r: 128, g: 128, b: 128, a: 0.5 });
expect(colord("#AAAF").toRgb()).toMatchObject({ r: 170, g: 170, b: 170, a: 1 });
expect(colord("#5550").toRgb()).toMatchObject({ r: 85, g: 85, b: 85, a: 0 });
expect(colord({ r: 255, g: 255, b: 255, a: 1 }).toHex()).toBe("#ffffff");
expect(colord({ r: 170, g: 170, b: 170, a: 0.5 }).toHex()).toBe("#aaaaaa80");
expect(colord({ r: 128, g: 128, b: 128, a: 0 }).toHex()).toBe("#80808000");
});
it("Ignores a case and extra whitespace", () => {
expect(colord(" #0a0a0a ").toRgb()).toMatchObject({ r: 10, g: 10, b: 10, a: 1 });
expect(colord("RGB( 10, 10, 10 )").toRgb()).toMatchObject({ r: 10, g: 10, b: 10, a: 1 });
expect(colord(" rGb(10,10,10 )").toRgb()).toMatchObject({ r: 10, g: 10, b: 10, a: 1 });
expect(colord(" Rgb(10, 10, 10) ").toRgb()).toMatchObject({ r: 10, g: 10, b: 10, a: 1 });
expect(colord(" hSl(10,20%,30%,0.1)").toHsl()).toMatchObject({ h: 10, s: 20, l: 30, a: 0.1 });
expect(colord("HsLa( 10, 20%, 30%, 1) ").toHsl()).toMatchObject({ h: 10, s: 20, l: 30, a: 1 });
});
it("Parses shorthand alpha values", () => {
expect(colord("rgba(0, 0, 0, .5)").alpha()).toBe(0.5);
expect(colord("rgba(50% 50% 50% / .999%)").alpha()).toBe(0.01);
expect(colord("hsla(0, 0%, 0%, .25)").alpha()).toBe(0.25);
});
it("Ignores invalid color formats", () => {
// mixing prefix
expect(colord("AbC").isValid()).toBe(false);
expect(colord("111").isValid()).toBe(false);
expect(colord("999999").isValid()).toBe(false);
// no bracket
expect(colord("rgb 10 10 10)").isValid()).toBe(false);
expect(colord("rgb(10 10 10").isValid()).toBe(false);
// missing commas
expect(colord("rgb( 10 10 10 0.1 )").isValid()).toBe(false);
expect(colord("hsl(10, 20 30)").isValid()).toBe(false);
// mixing numbers and percentage
expect(colord("rgb(100, 100%, 20)").isValid()).toBe(false);
// mixing commas and slash
expect(colord("rgba(10, 50, 30 / .5").isValid()).toBe(false);
expect(colord("hsla(10, 20, 30/50%)").isValid()).toBe(false);
// missing percent
expect(colord("hsl(10deg, 50, 50)").isValid()).toBe(false);
// wrong content
expect(colord("rgb(10, 10, 10, var(--alpha))").isValid()).toBe(false);
expect(colord("hsl(var(--h) 10% 10%)").isValid()).toBe(false);
});
it("Clamps input numbers", () => {
expect(colord("rgba(256, 999, -200, 2)").toRgb()).toMatchObject({ r: 255, g: 255, b: 0, a: 1 });
expect(
colord({
r: NaN,
g: -Infinity,
b: +Infinity,
a: 100500,
}).toRgb()
).toMatchObject({ r: 0, g: 0, b: 255, a: 1 });
expect(
colord({
h: NaN,
s: -Infinity,
l: +Infinity,
a: 100500,
}).toHsl()
).toMatchObject({ h: 0, s: 0, l: 100, a: 1 });
});
it("Clamps hue (angle) value properly", () => {
expect(colord("hsl(361, 50%, 50%)").toHsl().h).toBe(1);
expect(colord("hsl(-1, 50%, 50%)").toHsl().h).toBe(359);
expect(colord({ h: 999, s: 50, l: 50 }).toHsl().h).toBe(279);
expect(colord({ h: -999, s: 50, l: 50 }).toHsl().h).toBe(81);
expect(colord({ h: 400, s: 50, v: 50 }).toHsv().h).toBe(40);
expect(colord({ h: -400, s: 50, v: 50 }).toHsv().h).toBe(320);
});
it("Supports all valid CSS angle units", () => {
// https://developer.mozilla.org/en-US/docs/Web/CSS/angle#examples
expect(colord("hsl(90deg, 50%, 50%)").toHsl().h).toBe(90);
expect(colord("hsl(100grad, 50%, 50%)").toHsl().h).toBe(90);
expect(colord("hsl(.25turn, 50%, 50%)").toHsl().h).toBe(90);
expect(colord("hsl(1.5708rad, 50%, 50%)").toHsl().h).toBe(90);
expect(colord("hsl(-180deg, 50%, 50%)").toHsl().h).toBe(180);
expect(colord("hsl(-200grad, 50%, 50%)").toHsl().h).toBe(180);
expect(colord("hsl(-.5turn, 50%, 50%)").toHsl().h).toBe(180);
expect(colord("hsl(-3.1416rad, 50%, 50%)").toHsl().h).toBe(180);
});
it("Accepts a colord instance as an input", () => {
const instance = colord(lime.hex as string);
expect(colord(instance).toRgb()).toMatchObject(lime.rgba);
expect(colord(colord(instance)).toHsl()).toMatchObject(lime.hsla);
});
it("Does not crash when input has an invalid type", () => {
const fallbackRgba = { r: 0, g: 0, b: 0, a: 1 };
// @ts-ignore
expect(colord().toRgb()).toMatchObject(fallbackRgba);
// @ts-ignore
expect(colord(null).toRgb()).toMatchObject(fallbackRgba);
// @ts-ignore
expect(colord(undefined).toRgb()).toMatchObject(fallbackRgba);
// @ts-ignore
expect(colord([1, 2, 3]).toRgb()).toMatchObject(fallbackRgba);
});
it("Does not crash when input has an invalid format", () => {
const fallbackRgba = { r: 0, g: 0, b: 0, a: 1 };
// @ts-ignore
expect(colord({ w: 1, u: 2, t: 3 }).toRgb()).toMatchObject(fallbackRgba);
expect(colord("WUT?").toRgb()).toMatchObject(fallbackRgba);
});
it("Validates an input value", () => {
expect(colord("#ffffff").isValid()).toBe(true);
expect(colord("#0011gg").isValid()).toBe(false);
expect(colord("#12345").isValid()).toBe(false);
expect(colord("#1234567").isValid()).toBe(false);
expect(colord("abracadabra").isValid()).toBe(false);
expect(colord("rgba(0,0,0,1)").isValid()).toBe(true);
expect(colord("hsla(100,50%,50%,1)").isValid()).toBe(true);
expect(colord({ r: 255, g: 255, b: 255 }).isValid()).toBe(true);
// @ts-ignore
expect(colord({ r: 255, g: 255, v: 255 }).isValid()).toBe(false);
// @ts-ignore
expect(colord({ h: 0, w: 0, l: 0 }).isValid()).toBe(false);
// @ts-ignore
expect(colord({ w: 1, u: 2, t: 3 }).isValid()).toBe(false);
});
it("Saturates and desaturates a color", () => {
const instance = colord(saturationLevels[5]);
expect(instance.saturate(0.2).toHex()).toBe(saturationLevels[7]);
expect(instance.desaturate(0.2).toHex()).toBe(saturationLevels[3]);
expect(instance.saturate(0.5).toHex()).toBe(saturationLevels[10]);
expect(instance.desaturate(0.5).toHex()).toBe(saturationLevels[0]);
expect(instance.saturate(1).toHex()).toBe(saturationLevels[10]);
expect(instance.desaturate(1).toHex()).toBe(saturationLevels[0]);
expect(instance.grayscale().toHex()).toBe(saturationLevels[0]);
});
it("Makes a color lighter and darker", () => {
expect(colord("hsl(100, 50%, 50%)").lighten().toHslString()).toBe("hsl(100, 50%, 60%)");
expect(colord("hsl(100, 50%, 50%)").lighten(0.25).toHsl().l).toBe(75);
expect(colord("hsl(100, 50%, 50%)").darken().toHslString()).toBe("hsl(100, 50%, 40%)");
expect(colord("hsl(100, 50%, 50%)").darken(0.25).toHsl().l).toBe(25);
expect(colord("#000").lighten(1).toHex()).toBe("#ffffff");
expect(colord("#000").lighten(0.5).toHex()).toBe("#808080");
expect(colord("#FFF").darken(1).toHex()).toBe("#000000");
expect(colord("#FFF").darken(0.5).toHex()).toBe("#808080");
});
it("Inverts a color", () => {
expect(colord("#000").invert().toHex()).toBe("#ffffff");
expect(colord("#FFF").invert().toHex()).toBe("#000000");
expect(colord("#123").invert().toHex()).toBe("#eeddcc");
});
it("Gets color brightness", () => {
expect(colord("#000").brightness()).toBe(0);
expect(colord("#808080").brightness()).toBe(0.5);
expect(colord("#FFF").brightness()).toBe(1);
expect(colord("#000").isDark()).toBe(true);
expect(colord("#665544").isDark()).toBe(true);
expect(colord("#888").isDark()).toBe(false);
expect(colord("#777").isLight()).toBe(false);
expect(colord("#aabbcc").isLight()).toBe(true);
expect(colord("#FFF").isLight()).toBe(true);
});
it("Gets an alpha channel value", () => {
expect(colord("#000").alpha()).toBe(1);
expect(colord("rgba(50, 100, 150, 0.5)").alpha()).toBe(0.5);
});
it("Changes an alpha channel value", () => {
expect(colord("#000").alpha(0.25).alpha()).toBe(0.25);
expect(colord("#FFF").alpha(0).toRgb().a).toBe(0);
});
it("Produces alpha values with up to 3 digits after the decimal point", () => {
expect(colord("#000").alpha(0.9).alpha()).toBe(0.9);
expect(colord("#000").alpha(0.01).alpha()).toBe(0.01);
expect(colord("#000").alpha(0.33333333).alpha()).toBe(0.333);
expect(colord("rgba(0, 0, 0, 0.075)").toRgbString()).toBe("rgba(0, 0, 0, 0.075)");
expect(colord("hsla(0, 0%, 0%, 0.789)").toHslString()).toBe("hsla(0, 0%, 0%, 0.789)");
expect(colord("hsla(0, 0%, 0%, 0.999)").toRgbString()).toBe("rgba(0, 0, 0, 0.999)");
});
it("Gets a hue value", () => {
expect(colord("#000").hue()).toBe(0);
expect(colord("hsl(90, 50%, 50%)").hue()).toBe(90);
expect(colord("hsl(-10, 50%, 50%)").hue()).toBe(350);
});
it("Changes a hue value", () => {
expect(colord("hsl(90, 50%, 50%)").hue(0).toHslString()).toBe("hsl(0, 50%, 50%)");
expect(colord("hsl(90, 50%, 50%)").hue(180).toHslString()).toBe("hsl(180, 50%, 50%)");
expect(colord("hsl(90, 50%, 50%)").hue(370).toHslString()).toBe("hsl(10, 50%, 50%)");
});
it("Rotates a hue circle", () => {
expect(colord("hsl(90, 50%, 50%)").rotate(0).toHslString()).toBe("hsl(90, 50%, 50%)");
expect(colord("hsl(90, 50%, 50%)").rotate(360).toHslString()).toBe("hsl(90, 50%, 50%)");
expect(colord("hsl(90, 50%, 50%)").rotate(90).toHslString()).toBe("hsl(180, 50%, 50%)");
expect(colord("hsl(90, 50%, 50%)").rotate(-180).toHslString()).toBe("hsl(270, 50%, 50%)");
});
it("Checks colors for equality", () => {
const otherColor = "#1ab2c3";
const otherInstance = colord(otherColor);
for (const format in lime) {
const instance = colord(lime[format] as AnyColor);
expect(instance.isEqual(colord(lime["hex"] as AnyColor))).toBe(true);
expect(instance.isEqual(colord(lime["rgb"] as AnyColor))).toBe(true);
expect(instance.isEqual(colord(lime["rgbString"] as AnyColor))).toBe(true);
expect(instance.isEqual(colord(lime["hsl"] as AnyColor))).toBe(true);
expect(instance.isEqual(colord(lime["hslString"] as AnyColor))).toBe(true);
expect(instance.isEqual(colord(lime["hsv"] as AnyColor))).toBe(true);
expect(instance.isEqual(otherInstance)).toBe(false);
expect(instance.isEqual(lime["hex"] as AnyColor)).toBe(true);
expect(instance.isEqual(lime["rgb"] as AnyColor)).toBe(true);
expect(instance.isEqual(lime["rgbString"] as AnyColor)).toBe(true);
expect(instance.isEqual(lime["hsl"] as AnyColor)).toBe(true);
expect(instance.isEqual(lime["hslString"] as AnyColor)).toBe(true);
expect(instance.isEqual(lime["hsv"] as AnyColor)).toBe(true);
expect(instance.isEqual(otherColor)).toBe(false);
}
});
it("Generates a random color", () => {
expect(random()).toBeInstanceOf(Colord);
expect(random().toHex()).not.toBe(random().toHex());
});
it("Gets an input color format", () => {
expect(getFormat("#000")).toBe("hex");
expect(getFormat("rgb(128, 128, 128)")).toBe("rgb");
expect(getFormat("rgba(50% 50% 50% / 50%)")).toBe("rgb");
expect(getFormat("hsl(180, 50%, 50%)")).toBe("hsl");
expect(getFormat({ r: 128, g: 128, b: 128, a: 0.5 })).toBe("rgb");
expect(getFormat({ h: 180, s: 50, l: 50, a: 0.5 })).toBe("hsl");
expect(getFormat({ h: 180, s: 50, v: 50, a: 0.5 })).toBe("hsv");
expect(getFormat("disco-dancing")).toBeUndefined();
// @ts-ignore
expect(getFormat({ w: 1, u: 2, t: 3 })).toBeUndefined();
}); | the_stack |
import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { Events, Inputs, RefKey } from "../src/constants";
import run from "../src/restore";
import * as actionUtils from "../src/utils/actionUtils";
import * as testUtils from "../src/utils/testUtils";
jest.mock("../src/utils/actionUtils");
beforeAll(() => {
jest.spyOn(actionUtils, "isExactKeyMatch").mockImplementation(
(key, cacheResult) => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.isExactKeyMatch(key, cacheResult);
}
);
jest.spyOn(actionUtils, "isValidEvent").mockImplementation(() => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.isValidEvent();
});
jest.spyOn(actionUtils, "getInputAsArray").mockImplementation(
(name, options) => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.getInputAsArray(name, options);
}
);
});
beforeEach(() => {
process.env[Events.Key] = Events.Push;
process.env[RefKey] = "refs/heads/feature-branch";
jest.spyOn(actionUtils, "isGhes").mockImplementation(() => false);
});
afterEach(() => {
testUtils.clearInputs();
delete process.env[Events.Key];
delete process.env[RefKey];
});
test("restore with invalid event outputs warning", async () => {
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const failedMock = jest.spyOn(core, "setFailed");
const invalidEvent = "commit_comment";
process.env[Events.Key] = invalidEvent;
delete process.env[RefKey];
await run();
expect(logWarningMock).toHaveBeenCalledWith(
`Event Validation Error: The event type ${invalidEvent} is not supported because it's not tied to a branch or tag ref.`
);
expect(failedMock).toHaveBeenCalledTimes(0);
});
test("restore on GHES should no-op", async () => {
jest.spyOn(actionUtils, "isGhes").mockImplementation(() => true);
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
const setCacheHitOutputMock = jest.spyOn(actionUtils, "setCacheHitOutput");
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(0);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(setCacheHitOutputMock).toHaveBeenCalledWith(false);
expect(logWarningMock).toHaveBeenCalledWith(
"Cache action is not supported on GHES. See https://github.com/actions/cache/issues/505 for more details"
);
});
test("restore with no path should fail", async () => {
const failedMock = jest.spyOn(core, "setFailed");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(0);
// this input isn't necessary for restore b/c tarball contains entries relative to workspace
expect(failedMock).not.toHaveBeenCalledWith(
"Input required and not supplied: path"
);
});
test("restore with no key", async () => {
testUtils.setInput(Inputs.Path, "node_modules");
const failedMock = jest.spyOn(core, "setFailed");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(0);
expect(failedMock).toHaveBeenCalledWith(
"Input required and not supplied: key"
);
});
test("restore with too many keys should fail", async () => {
const path = "node_modules";
const key = "node-test";
const restoreKeys = [...Array(20).keys()].map(x => x.toString());
testUtils.setInputs({
path: path,
key,
restoreKeys
});
const failedMock = jest.spyOn(core, "setFailed");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, restoreKeys);
expect(failedMock).toHaveBeenCalledWith(
`Key Validation Error: Keys are limited to a maximum of 10.`
);
});
test("restore with large key should fail", async () => {
const path = "node_modules";
const key = "foo".repeat(512); // Over the 512 character limit
testUtils.setInputs({
path: path,
key
});
const failedMock = jest.spyOn(core, "setFailed");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(failedMock).toHaveBeenCalledWith(
`Key Validation Error: ${key} cannot be larger than 512 characters.`
);
});
test("restore with invalid key should fail", async () => {
const path = "node_modules";
const key = "comma,comma";
testUtils.setInputs({
path: path,
key
});
const failedMock = jest.spyOn(core, "setFailed");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(failedMock).toHaveBeenCalledWith(
`Key Validation Error: ${key} cannot contain commas.`
);
});
test("restore with no cache found", async () => {
const path = "node_modules";
const key = "node-test";
testUtils.setInputs({
path: path,
key
});
const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(undefined);
});
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(failedMock).toHaveBeenCalledTimes(0);
expect(infoMock).toHaveBeenCalledWith(
`Cache not found for input keys: ${key}`
);
});
test("restore with server error should fail", async () => {
const path = "node_modules";
const key = "node-test";
testUtils.setInputs({
path: path,
key
});
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
throw new Error("HTTP Error Occurred");
});
const setCacheHitOutputMock = jest.spyOn(actionUtils, "setCacheHitOutput");
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(logWarningMock).toHaveBeenCalledTimes(1);
expect(logWarningMock).toHaveBeenCalledWith("HTTP Error Occurred");
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(setCacheHitOutputMock).toHaveBeenCalledWith(false);
expect(failedMock).toHaveBeenCalledTimes(0);
});
test("restore with restore keys and no cache found", async () => {
const path = "node_modules";
const key = "node-test";
const restoreKey = "node-";
testUtils.setInputs({
path: path,
key,
restoreKeys: [restoreKey]
});
const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(undefined);
});
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, [restoreKey]);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(failedMock).toHaveBeenCalledTimes(0);
expect(infoMock).toHaveBeenCalledWith(
`Cache not found for input keys: ${key}, ${restoreKey}`
);
});
test("restore with cache found for key", async () => {
const path = "node_modules";
const key = "node-test";
testUtils.setInputs({
path: path,
key
});
const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(actionUtils, "setCacheHitOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(key);
});
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, []);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(setCacheHitOutputMock).toHaveBeenCalledWith(true);
expect(infoMock).toHaveBeenCalledWith(`Cache restored from key: ${key}`);
expect(failedMock).toHaveBeenCalledTimes(0);
});
test("restore with cache found for restore key", async () => {
const path = "node_modules";
const key = "node-test";
const restoreKey = "node-";
testUtils.setInputs({
path: path,
key,
restoreKeys: [restoreKey]
});
const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(actionUtils, "setCacheHitOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(restoreKey);
});
await run();
expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(restoreCacheMock).toHaveBeenCalledWith([path], key, [restoreKey]);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(setCacheHitOutputMock).toHaveBeenCalledWith(false);
expect(infoMock).toHaveBeenCalledWith(
`Cache restored from key: ${restoreKey}`
);
expect(failedMock).toHaveBeenCalledTimes(0);
}); | the_stack |
namespace ts.tscWatch {
describe("unittests:: tsc-watch:: watchAPI:: tsc-watch with custom module resolution", () => {
const configFileJson: any = {
compilerOptions: { module: "commonjs", resolveJsonModule: true },
files: ["index.ts"]
};
const mainFile: File = {
path: `${projectRoot}/index.ts`,
content: "import settings from './settings.json';"
};
const config: File = {
path: `${projectRoot}/tsconfig.json`,
content: JSON.stringify(configFileJson)
};
const settingsJson: File = {
path: `${projectRoot}/settings.json`,
content: JSON.stringify({ content: "Print this" })
};
it("verify that module resolution with json extension works when returned without extension", () => {
const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem(
[libFile, mainFile, config, settingsJson],
{ currentDirectory: projectRoot }),
);
const host = createWatchCompilerHostOfConfigFileForBaseline({
configFileName: config.path,
system: sys,
cb,
});
const parsedCommandResult = parseJsonConfigFileContent(configFileJson, sys, config.path);
host.resolveModuleNames = (moduleNames, containingFile) => moduleNames.map(m => {
const result = resolveModuleName(m, containingFile, parsedCommandResult.options, host);
const resolvedModule = result.resolvedModule!;
return {
resolvedFileName: resolvedModule.resolvedFileName,
isExternalLibraryImport: resolvedModule.isExternalLibraryImport,
originalFileName: resolvedModule.originalPath,
};
});
const watch = createWatchProgram(host);
runWatchBaseline({
scenario: "watchApi",
subScenario: "verify that module resolution with json extension works when returned without extension",
commandLineArgs: ["--w", "--p", config.path],
sys,
baseline,
oldSnap,
getPrograms,
changes: emptyArray,
watchOrSolution: watch
});
});
});
describe("unittests:: tsc-watch:: watchAPI:: tsc-watch expose error count to watch status reporter", () => {
it("verify that the error count is correctly passed down to the watch status reporter", () => {
const config: File = {
path: `${projectRoot}/tsconfig.json`,
content: JSON.stringify({
compilerOptions: { module: "commonjs" },
files: ["index.ts"]
})
};
const mainFile: File = {
path: `${projectRoot}/index.ts`,
content: "let compiler = new Compiler(); for (let i = 0; j < 5; i++) {}"
};
const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem(
[libFile, mainFile, config],
{ currentDirectory: projectRoot }),
);
const host = createWatchCompilerHostOfConfigFileForBaseline({
configFileName: config.path,
system: sys,
cb,
});
const existing = host.onWatchStatusChange!;
let watchedErrorCount;
host.onWatchStatusChange = (diagnostic, newLine, options, errorCount) => {
existing.call(host, diagnostic, newLine, options, errorCount);
watchedErrorCount = errorCount;
};
const watch = createWatchProgram(host);
assert.equal(watchedErrorCount, 2, "The error count was expected to be 2 for the file change");
runWatchBaseline({
scenario: "watchApi",
subScenario: "verify that the error count is correctly passed down to the watch status reporter",
commandLineArgs: ["--w", "--p", config.path],
sys,
baseline,
oldSnap,
getPrograms,
changes: emptyArray,
watchOrSolution: watch
});
});
});
describe("unittests:: tsc-watch:: watchAPI:: when watchHost does not implement setTimeout or clearTimeout", () => {
it("verifies that getProgram gets updated program if new file is added to the program", () => {
const config: File = {
path: `${projectRoot}/tsconfig.json`,
content: "{}"
};
const mainFile: File = {
path: `${projectRoot}/main.ts`,
content: "const x = 10;"
};
const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(createWatchedSystem([config, mainFile, libFile]));
const host = createWatchCompilerHostOfConfigFileForBaseline({
configFileName: config.path,
system: sys,
cb,
});
host.setTimeout = undefined;
host.clearTimeout = undefined;
const watch = createWatchProgram(host);
runWatchBaseline({
scenario: "watchApi",
subScenario: "without timesouts on host program gets updated",
commandLineArgs: ["--w", "--p", config.path],
sys,
baseline,
oldSnap,
getPrograms,
changes: [{
caption: "Write a file",
change: sys => sys.writeFile(`${projectRoot}/bar.ts`, "const y =10;"),
timeouts: sys => {
sys.checkTimeoutQueueLength(0);
watch.getProgram();
}
}],
watchOrSolution: watch
});
});
});
describe("unittests:: tsc-watch:: watchAPI:: when watchHost can add extraFileExtensions to process", () => {
it("verifies that extraFileExtensions are supported to get the program with other extensions", () => {
const config: File = {
path: `${projectRoot}/tsconfig.json`,
content: "{}"
};
const mainFile: File = {
path: `${projectRoot}/main.ts`,
content: "const x = 10;"
};
const otherFile: File = {
path: `${projectRoot}/other.vue`,
content: ""
};
const { sys, baseline, oldSnap, cb, getPrograms } = createBaseline(
createWatchedSystem([config, mainFile, otherFile, libFile])
);
const host = createWatchCompilerHostOfConfigFileForBaseline({
configFileName: config.path,
optionsToExtend: { allowNonTsExtensions: true },
extraFileExtensions: [{ extension: ".vue", isMixedContent: true, scriptKind: ScriptKind.Deferred }],
system: sys,
cb,
});
const watch = createWatchProgram(host);
runWatchBaseline({
scenario: "watchApi",
subScenario: "extraFileExtensions are supported",
commandLineArgs: ["--w", "--p", config.path],
sys,
baseline,
oldSnap,
getPrograms,
changes: [{
caption: "Write a file",
change: sys => sys.writeFile(`${projectRoot}/other2.vue`, otherFile.content),
timeouts: checkSingleTimeoutQueueLengthAndRun,
}],
watchOrSolution: watch
});
});
});
describe("unittests:: tsc-watch:: watchAPI:: when watchHost uses createSemanticDiagnosticsBuilderProgram", () => {
function createSystem(configText: string, mainText: string) {
const config: File = {
path: `${projectRoot}/tsconfig.json`,
content: configText
};
const mainFile: File = {
path: `${projectRoot}/main.ts`,
content: mainText
};
const otherFile: File = {
path: `${projectRoot}/other.ts`,
content: "export const y = 10;"
};
return {
...createBaseline(createWatchedSystem([config, mainFile, otherFile, libFile])),
config,
mainFile,
otherFile,
};
}
function createWatch<T extends BuilderProgram>(
baseline: string[],
config: File,
sys: TestFSWithWatch.TestServerHostTrackingWrittenFiles,
createProgram: CreateProgram<T>,
optionsToExtend?: CompilerOptions,
) {
const { cb, getPrograms } = commandLineCallbacks(sys);
baseline.push(`tsc --w${optionsToExtend?.noEmit ? " --noEmit" : ""}`);
const oldSnap = sys.snap();
const host = createWatchCompilerHostOfConfigFileForBaseline<T>({
configFileName: config.path,
optionsToExtend,
createProgram,
system: sys,
cb,
});
const watch = createWatchProgram(host);
watchBaseline({
baseline,
getPrograms,
oldPrograms: emptyArray,
sys,
oldSnap,
});
watch.close();
}
function verifyOutputs(baseline: string[], sys: System, emitSys: System) {
baseline.push("Checking if output is same as EmitAndSemanticDiagnosticsBuilderProgram::");
for (const output of [`${projectRoot}/main.js`, `${projectRoot}/main.d.ts`, `${projectRoot}/other.js`, `${projectRoot}/other.d.ts`, `${projectRoot}/tsconfig.tsbuildinfo`]) {
baseline.push(`Output file text for ${output} is same:: ${sys.readFile(output) === emitSys.readFile(output)}`);
}
baseline.push("");
}
function createSystemForBuilderTest(configText: string, mainText: string) {
const result = createSystem(configText, mainText);
const { sys: emitSys, baseline: emitBaseline } = createSystem(configText, mainText);
return { ...result, emitSys, emitBaseline };
}
function applyChangeForBuilderTest(
baseline: string[],
emitBaseline: string[],
sys: TestFSWithWatch.TestServerHostTrackingWrittenFiles,
emitSys: TestFSWithWatch.TestServerHostTrackingWrittenFiles,
change: (sys: TestFSWithWatch.TestServerHostTrackingWrittenFiles) => void,
caption: string
) {
// Change file
applyChange(sys, baseline, change, caption);
applyChange(emitSys, emitBaseline, change, caption);
}
function verifyBuilder<T extends BuilderProgram>(
baseline: string[],
emitBaseline: string[],
config: File,
sys: TestFSWithWatch.TestServerHostTrackingWrittenFiles,
emitSys: TestFSWithWatch.TestServerHostTrackingWrittenFiles,
createProgram: CreateProgram<T>,
optionsToExtend?: CompilerOptions) {
createWatch(baseline, config, sys, createProgram, optionsToExtend);
createWatch(emitBaseline, config, emitSys, createEmitAndSemanticDiagnosticsBuilderProgram, optionsToExtend);
verifyOutputs(baseline, sys, emitSys);
}
it("verifies that noEmit is handled on createSemanticDiagnosticsBuilderProgram and typechecking happens only on affected files", () => {
const { sys, baseline, oldSnap, cb, getPrograms, config, mainFile } = createSystem("{}", "export const x = 10;");
const host = createWatchCompilerHostOfConfigFileForBaseline({
configFileName: config.path,
optionsToExtend: { noEmit: true },
createProgram: createSemanticDiagnosticsBuilderProgram,
system: sys,
cb,
});
const watch = createWatchProgram(host);
runWatchBaseline({
scenario: "watchApi",
subScenario: "verifies that noEmit is handled on createSemanticDiagnosticsBuilderProgram",
commandLineArgs: ["--w", "--p", config.path],
sys,
baseline,
oldSnap,
getPrograms,
changes: [{
caption: "Modify a file",
change: sys => sys.appendFile(mainFile.path, "\n// SomeComment"),
timeouts: runQueuedTimeoutCallbacks,
}],
watchOrSolution: watch
});
});
describe("noEmit with composite writes the tsbuildinfo with pending affected files correctly", () => {
let baseline: string[];
let emitBaseline: string[];
before(() => {
const configText = JSON.stringify({ compilerOptions: { composite: true } });
const mainText = "export const x = 10;";
const result = createSystemForBuilderTest(configText, mainText);
baseline = result.baseline;
emitBaseline = result.emitBaseline;
const { sys, config, mainFile, emitSys } = result;
// No Emit
verifyBuilder(baseline, emitBaseline, config, sys, emitSys, createEmitAndSemanticDiagnosticsBuilderProgram, { noEmit: true });
// Emit on both sys should result in same output
verifyBuilder(baseline, emitBaseline, config, sys, emitSys, createEmitAndSemanticDiagnosticsBuilderProgram);
// Change file
applyChangeForBuilderTest(baseline, emitBaseline, sys, emitSys, sys => sys.appendFile(mainFile.path, "\n// SomeComment"), "Add comment");
// Verify noEmit results in same output
verifyBuilder(baseline, emitBaseline, config, sys, emitSys, createSemanticDiagnosticsBuilderProgram, { noEmit: true });
// Emit on both sys should result in same output
verifyBuilder(baseline, emitBaseline, config, sys, emitSys, createEmitAndSemanticDiagnosticsBuilderProgram);
// Change file
applyChangeForBuilderTest(baseline, emitBaseline, sys, emitSys, sys => sys.appendFile(mainFile.path, "\n// SomeComment"), "Add comment");
// Emit on both the builders should result in same files
verifyBuilder(baseline, emitBaseline, config, sys, emitSys, createSemanticDiagnosticsBuilderProgram);
});
after(() => {
baseline = undefined!;
emitBaseline = undefined!;
});
it("noEmit with composite writes the tsbuildinfo with pending affected files correctly", () => {
Harness.Baseline.runBaseline(`tscWatch/watchApi/noEmit-with-composite-with-semantic-builder.js`, baseline.join("\r\n"));
});
it("baseline in createEmitAndSemanticDiagnosticsBuilderProgram:: noEmit with composite writes the tsbuildinfo with pending affected files correctly", () => {
Harness.Baseline.runBaseline(`tscWatch/watchApi/noEmit-with-composite-with-emit-builder.js`, emitBaseline.join("\r\n"));
});
});
describe("noEmitOnError with composite writes the tsbuildinfo with pending affected files correctly", () => {
let baseline: string[];
let emitBaseline: string[];
before(() => {
const configText = JSON.stringify({ compilerOptions: { composite: true, noEmitOnError: true } });
const mainText = "export const x: string = 10;";
const result = createSystemForBuilderTest(configText, mainText);
baseline = result.baseline;
emitBaseline = result.emitBaseline;
const { sys, config, mainFile, emitSys } = result;
// Verify noEmit results in same output
verifyBuilder(baseline, emitBaseline, config, sys, emitSys, createSemanticDiagnosticsBuilderProgram);
// Change file
applyChangeForBuilderTest(baseline, emitBaseline, sys, emitSys, sys => sys.appendFile(mainFile.path, "\n// SomeComment"), "Add comment");
// Verify noEmit results in same output
verifyBuilder(baseline, emitBaseline, config, sys, emitSys, createSemanticDiagnosticsBuilderProgram);
// Fix error
const fixed = "export const x = 10;";
applyChangeForBuilderTest(baseline, emitBaseline, sys, emitSys, sys => sys.writeFile(mainFile.path, fixed), "Fix error");
// Emit on both the builders should result in same files
verifyBuilder(baseline, emitBaseline, config, sys, emitSys, createSemanticDiagnosticsBuilderProgram);
});
it("noEmitOnError with composite writes the tsbuildinfo with pending affected files correctly", () => {
Harness.Baseline.runBaseline(`tscWatch/watchApi/noEmitOnError-with-composite-with-semantic-builder.js`, baseline.join("\r\n"));
});
it("baseline in createEmitAndSemanticDiagnosticsBuilderProgram:: noEmitOnError with composite writes the tsbuildinfo with pending affected files correctly", () => {
Harness.Baseline.runBaseline(`tscWatch/watchApi/noEmitOnError-with-composite-with-emit-builder.js`, emitBaseline.join("\r\n"));
});
});
it("SemanticDiagnosticsBuilderProgram emitDtsOnly does not update affected files pending emit", () => {
// Initial
const { sys, baseline, config, mainFile } = createSystem(JSON.stringify({ compilerOptions: { composite: true, noEmitOnError: true } }), "export const x: string = 10;");
createWatch(baseline, config, sys, createSemanticDiagnosticsBuilderProgram);
// Fix error and emit
applyChange(sys, baseline, sys => sys.writeFile(mainFile.path, "export const x = 10;"), "Fix error");
const { cb, getPrograms } = commandLineCallbacks(sys);
const oldSnap = sys.snap();
const reportDiagnostic = createDiagnosticReporter(sys, /*pretty*/ true);
const reportWatchStatus = createWatchStatusReporter(sys, /*pretty*/ true);
const host = createWatchCompilerHostOfConfigFile({
configFileName: config.path,
createProgram: createSemanticDiagnosticsBuilderProgram,
system: sys,
reportDiagnostic,
reportWatchStatus,
});
host.afterProgramCreate = program => {
const diagnostics = sortAndDeduplicateDiagnostics(program.getSemanticDiagnostics());
diagnostics.forEach(reportDiagnostic);
// Buildinfo should still have affectedFilesPendingEmit since we are only emitting dts files
program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDts*/ true);
reportWatchStatus(
createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(diagnostics.length), diagnostics.length),
sys.newLine,
program.getCompilerOptions(),
diagnostics.length
);
cb(program);
};
createWatchProgram(host);
watchBaseline({
baseline,
getPrograms,
oldPrograms: emptyArray,
sys,
oldSnap,
});
Harness.Baseline.runBaseline(`tscWatch/watchApi/semantic-builder-emitOnlyDts.js`, baseline.join("\r\n"));
});
});
describe("unittests:: tsc-watch:: watchAPI:: when getParsedCommandLine is implemented", () => {
function setup(useSourceOfProjectReferenceRedirect?: () => boolean) {
const config1: File = {
path: `${projectRoot}/projects/project1/tsconfig.json`,
content: JSON.stringify({
compilerOptions: {
module: "none",
composite: true
},
exclude: ["temp"]
})
};
const class1: File = {
path: `${projectRoot}/projects/project1/class1.ts`,
content: `class class1 {}`
};
const class1Dts: File = {
path: `${projectRoot}/projects/project1/class1.d.ts`,
content: `declare class class1 {}`
};
const config2: File = {
path: `${projectRoot}/projects/project2/tsconfig.json`,
content: JSON.stringify({
compilerOptions: {
module: "none",
composite: true
},
references: [
{ path: "../project1" }
]
})
};
const class2: File = {
path: `${projectRoot}/projects/project2/class2.ts`,
content: `class class2 {}`
};
const system = createWatchedSystem([config1, class1, class1Dts, config2, class2, libFile]);
const baseline = createBaseline(system);
const compilerHost = createWatchCompilerHostOfConfigFileForBaseline({
cb: baseline.cb,
system,
configFileName: config2.path,
optionsToExtend: { extendedDiagnostics: true }
});
compilerHost.useSourceOfProjectReferenceRedirect = useSourceOfProjectReferenceRedirect;
const calledGetParsedCommandLine = new Set<string>();
compilerHost.getParsedCommandLine = fileName => {
assert.isFalse(calledGetParsedCommandLine.has(fileName), `Already called on ${fileName}`);
calledGetParsedCommandLine.add(fileName);
return getParsedCommandLineOfConfigFile(fileName, /*optionsToExtend*/ undefined, {
useCaseSensitiveFileNames: true,
fileExists: path => system.fileExists(path),
readFile: path => system.readFile(path),
getCurrentDirectory: () => system.getCurrentDirectory(),
readDirectory: (path, extensions, excludes, includes, depth) => system.readDirectory(path, extensions, excludes, includes, depth),
onUnRecoverableConfigFileDiagnostic: noop,
});
};
const watch = createWatchProgram(compilerHost);
return { watch, baseline, config2, calledGetParsedCommandLine };
}
it("when new file is added to the referenced project with host implementing getParsedCommandLine", () => {
const { watch, baseline, config2, calledGetParsedCommandLine } = setup(returnTrue);
runWatchBaseline({
scenario: "watchApi",
subScenario: "when new file is added to the referenced project with host implementing getParsedCommandLine",
commandLineArgs: ["--w", "-p", config2.path, "--extendedDiagnostics"],
...baseline,
changes: [
{
caption: "Add class3 to project1",
change: sys => {
calledGetParsedCommandLine.clear();
sys.writeFile(`${projectRoot}/projects/project1/class3.ts`, `class class3 {}`);
},
timeouts: checkSingleTimeoutQueueLengthAndRun,
},
{
caption: "Add excluded file to project1",
change: sys => sys.ensureFileOrFolder({ path: `${projectRoot}/projects/project1/temp/file.d.ts`, content: `declare class file {}` }),
timeouts: sys => sys.checkTimeoutQueueLength(0),
},
{
caption: "Add output of class3",
change: sys => sys.writeFile(`${projectRoot}/projects/project1/class3.d.ts`, `declare class class3 {}`),
timeouts: sys => sys.checkTimeoutQueueLength(0),
},
],
watchOrSolution: watch
});
});
it("when new file is added to the referenced project with host implementing getParsedCommandLine without implementing useSourceOfProjectReferenceRedirect", () => {
const { watch, baseline, config2, calledGetParsedCommandLine } = setup();
runWatchBaseline({
scenario: "watchApi",
subScenario: "when new file is added to the referenced project with host implementing getParsedCommandLine without implementing useSourceOfProjectReferenceRedirect",
commandLineArgs: ["--w", "-p", config2.path, "--extendedDiagnostics"],
...baseline,
changes: [
{
caption: "Add class3 to project1",
change: sys => {
calledGetParsedCommandLine.clear();
sys.writeFile(`${projectRoot}/projects/project1/class3.ts`, `class class3 {}`);
},
timeouts: checkSingleTimeoutQueueLengthAndRun,
},
{
caption: "Add class3 output to project1",
change: sys => sys.writeFile(`${projectRoot}/projects/project1/class3.d.ts`, `declare class class3 {}`),
timeouts: checkSingleTimeoutQueueLengthAndRun,
},
{
caption: "Add excluded file to project1",
change: sys => sys.ensureFileOrFolder({ path: `${projectRoot}/projects/project1/temp/file.d.ts`, content: `declare class file {}` }),
timeouts: sys => sys.checkTimeoutQueueLength(0),
},
{
caption: "Delete output of class3",
change: sys => sys.deleteFile(`${projectRoot}/projects/project1/class3.d.ts`),
timeouts: checkSingleTimeoutQueueLengthAndRun,
},
{
caption: "Add output of class3",
change: sys => sys.writeFile(`${projectRoot}/projects/project1/class3.d.ts`, `declare class class3 {}`),
timeouts: checkSingleTimeoutQueueLengthAndRun,
},
],
watchOrSolution: watch
});
});
});
} | the_stack |
import eris, { Emoji, PossiblyUncachedMessage } from "eris";
import { createEmptyNewSession, movePlayersToSilenceChannel, movePlayersToTalkingChannel } from "./actions";
import {
BOT_INVITE_LINK,
COLOR_EMOTE_IDS,
GROUPING_TOGGLE_EMOJI,
LEAVE_EMOJI,
LobbyRegion,
SessionState,
} from "./constants";
import { orm } from "./database";
import AmongUsSession from "./database/among-us-session";
import SessionChannel, { SILENCE_CHANNELS, TALKING_CHANNELS } from "./database/session-channel";
import startSession, { getRunnerForSession } from "./session-runner";
const COMMAND_PREFIX = "!amongus";
const VOICE_CHANNEL_USERS = new Map<string, string[]>();
const ADMIN_USERS = new Set<string>();
/**
* Helper function that ensures that ADMIN_USERS is updated based on
* whether or not the specified member is an administrator or server owner.
*/
function updateAdminUserState(member: eris.Member) {
const isAdmin =
member.roles.some(x => member.guild.roles.get(x)!.permissions.has("administrator")) ||
member.guild.ownerID === member.id;
if (isAdmin) {
ADMIN_USERS.add(member.id);
} else {
ADMIN_USERS.delete(member.id);
}
}
/**
* Invoked when the specified member joins the specified new voice channel.
* Responsible for tracking voice channel membership, as well as ensuring
* that anyone joining the current talking voice channel while the game is
* in progress will automatically be redirected to the silence channel.
*/
export async function onVoiceJoin(member: eris.Member, newChannel: eris.VoiceChannel) {
updateAdminUserState(member);
VOICE_CHANNEL_USERS.set(newChannel.id, [...(VOICE_CHANNEL_USERS.get(newChannel.id) || []), member.id]);
// Check if this is a game voice channel and we're in game right now.
const relevantChannel = await orm.em.findOne(
SessionChannel,
{
channelId: newChannel.id,
},
["session"]
);
if (!relevantChannel) return;
// If this is a talking channel and we're playing, move them to the playing channel.
if (TALKING_CHANNELS.includes(relevantChannel.type) && relevantChannel.session.state === SessionState.PLAYING) {
await movePlayersToSilenceChannel(member.guild.shard.client, relevantChannel.session);
}
// If this is a playing channel and we're talking, move them to the talking channel.
if (SILENCE_CHANNELS.includes(relevantChannel.type) && relevantChannel.session.state !== SessionState.PLAYING) {
await movePlayersToTalkingChannel(member.guild.shard.client, relevantChannel.session);
}
}
/**
* Invoked when the specified member leaves the specified channel.
*/
export async function onVoiceLeave(member: eris.Member, oldChannel: eris.VoiceChannel) {
updateAdminUserState(member);
const users = VOICE_CHANNEL_USERS.get(oldChannel.id);
if (!users) return;
const idx = users.indexOf(member.id);
if (idx === -1) return;
users.splice(idx, 1);
}
/**
* Invoked when the specified member moves from the oldChannel to the
* newChannel. Simply invokes onVoiceLeave and onVoiceJoin.
*/
export async function onVoiceChange(member: eris.Member, newChannel: eris.VoiceChannel, oldChannel: eris.VoiceChannel) {
await onVoiceLeave(member, oldChannel);
await onVoiceJoin(member, newChannel);
}
/**
* Helper function that returns the list of user ids currently in the
* specified voice channel, or an empty list if there are none.
*/
export function getMembersInChannel(channel: string): string[] {
return VOICE_CHANNEL_USERS.get(channel) || [];
}
/**
* Returns whether or not the specified user ID is an administrator.
*/
export function isMemberAdmin(id: string): boolean {
return ADMIN_USERS.has(id);
}
/**
* Invoked when a reaction is added to any message. We will use it to process
* player links.
*/
export async function onReactionAdded(
bot: eris.Client,
message: PossiblyUncachedMessage,
emoji: Emoji,
userID: string
) {
if (
!COLOR_EMOTE_IDS.includes(emoji.id) &&
GROUPING_TOGGLE_EMOJI.split(":")[1] !== emoji.id &&
LEAVE_EMOJI.split(":")[1] !== emoji.id
)
return;
if (userID === bot.user.id) return;
const session = await orm.em.findOne(AmongUsSession, {
message: message.id,
});
if (!session) return;
// Remove the reaction.
await bot
.removeMessageReaction(message.channel.id, message.id, emoji.name + ":" + emoji.id, userID)
.catch(() => {});
// Attempt to forward it to the session runner.
const runner = getRunnerForSession(session);
if (runner) {
await runner.handleEmojiSelection(emoji.id, userID);
}
}
/**
* Invoked when a new message is created in a channel shared by the bot.
* Will attempt to parse the message as a command, and handle appropriately.
*/
export async function onMessageCreated(bot: eris.Client, msg: eris.Message) {
if (!msg.content.startsWith(COMMAND_PREFIX) || msg.author.bot) return;
if (!(msg.channel instanceof eris.TextChannel)) return;
console.log(`[+] Command: ${msg.content}`);
if (msg.content === COMMAND_PREFIX || msg.content === COMMAND_PREFIX + " help") {
return await sendHelp(bot, msg);
}
if (msg.content === COMMAND_PREFIX + " invite") {
return await sendInvite(bot, msg);
}
try {
const { region, code } = parseCommandInvocation(msg.content);
const session = await createEmptyNewSession(msg, region, code);
await startSession(bot, session);
} catch (e) {
await msg.channel.createMessage(`<@!${msg.author.id}>, sorry but something went wrong: ${e}`).catch(() => {});
}
}
/**
* Sends a message with help and other information as a reply to the specified message.
*/
async function sendHelp(bot: eris.Client, msg: eris.Message) {
await msg.channel.createMessage({
embed: {
color: 0x0a96de,
title: "📖 Impostor - Help",
thumbnail: { url: bot.user.avatarURL.replace("jpg", "png") },
description: `Impostor is a Discord bot for Among Us that manages voice channels for you! Automatically muting everyone when gameplay resumes, ensuring dead players can't talk, and even allowing multiple impostors to talk to each other has never been so easy. No client installs needed!`,
fields: [
{
name: "How does it work?",
value:
`First, create a lobby in Among Us as usual. After creating one, use \`!amongus [region] [invite code]\` (for example: \`!amongus na ABCDEF\`) to set up the bot. The bot will create a new set of voice channels specifically for your lobby. Simply join the Discussion channel, and the bot will do the rest!` +
`\n\nWant to be automatically muted when you die? You can react to the bot message with the color of your crewmate to link your Discord account with your crewmate. Once they die, you will automatically be muted.`,
},
{
name: "How does the bot know when to mute?",
value: `The bot will join your lobby as a fake Among Us player, then despawn itself. This will make sure that the bot does not become a player when the game starts, but still allows it to see everything that's going on! Unfortunately, the bot will still take up a spot in your lobby, so you will only be able to play with 9 players max.`,
},
{
name: "Why are you moving channels instead of server mutes?",
value:
"Server mutes are notoriously hard to get right. If players leave voice channels halfway through a game, they may end up staying stuck server-muted when they rejoin a voice channel days or even weeks later. Using various different voice channels resolves this issue.",
},
{
name: "Help! I'm having an issue!",
value:
"If Impostor is not working, join the [Discord server](https://discord.gg/fQk7CHx) and let me know!",
},
{
name: "I want to add Impostor to my own server!",
value: `Sure thing! Click [here](${BOT_INVITE_LINK}) to invite Impostor.`,
},
],
},
});
}
/**
* Sends a message that contains information about how to invite Impostor to
* a new Discord server.
*/
async function sendInvite(bot: eris.Client, msg: eris.Message) {
await msg.channel.createMessage({
embed: {
color: 0x0a96de,
title: "🧑🤝🧑 Impostor - Invite",
thumbnail: { url: bot.user.avatarURL.replace("jpg", "png") },
description: `Want to add Impostor to your own Discord server? Sure thing! Simply click [here](${BOT_INVITE_LINK}) to add the bot.\n\nHaving issues? Join the [support Discord server](https://discord.gg/fQk7CHx) and let me know!`,
},
});
}
/**
* Attempts to parse the region from the specified command invocation,
* including the command prefix. Returns the parsed region and the code,
* or throws an error if it could not be parsed.
*/
function parseCommandInvocation(msg: string): { region: LobbyRegion; code: string } {
msg = msg.slice(COMMAND_PREFIX.length + 1);
let region: LobbyRegion | null = null;
const nextWord = msg.slice(0, msg.indexOf(" ")).toLowerCase();
if (nextWord === "asia" || nextWord === "as") {
region = LobbyRegion.ASIA;
msg = msg.slice(nextWord.length);
}
if (nextWord === "eu" || nextWord === "europe") {
region = LobbyRegion.EUROPE;
msg = msg.slice(nextWord.length);
}
if (
nextWord === "us" ||
nextWord === "usa" ||
nextWord === "na" ||
nextWord === "america" ||
nextWord === "northamerica"
) {
region = LobbyRegion.NORTH_AMERICA;
msg = msg.slice(nextWord.length);
}
if (nextWord === "north") {
msg = msg.slice(nextWord.length).trim().toLowerCase();
const nextNextWord = msg.slice(0, msg.indexOf(" "));
if (nextNextWord === "america") {
region = LobbyRegion.NORTH_AMERICA;
msg = msg.slice(nextNextWord.length);
}
}
if (!region) {
throw `Could not determine the region of the lobby. Try doing \`${COMMAND_PREFIX} na ABCDEF\` or \`${COMMAND_PREFIX} europe GHIJKL\`.`;
}
return {
region,
code: validateLobbyCode(msg),
};
}
// Valid chars in a V2 (6-character) Among Us lobby code.
const V2 = "QWXRTYLPESDFGHUJKZOCVBINMA";
/**
* Verifies the specified string as a lobby code. If it is valid, returns
* the code. Else, throws an error.
*/
function validateLobbyCode(code: string) {
code = code.trim().toUpperCase();
if (code.length !== 6) {
throw "Invalid lobby code. The lobby code must be exactly 6 letters.";
}
if ([...code].some(x => !V2.includes(x))) {
throw "Invalid lobby code. The lobby code contains invalid characters.";
}
return code;
} | the_stack |
import {PolymerElement, html} from '@polymer/polymer';
import {computed, customElement, observe, property} from '@polymer/decorators';
import {Canceller} from '../../../components/tf_backend/canceller';
import {RequestManager} from '../../../components/tf_backend/requestManager';
import {getRouter} from '../../../components/tf_backend/router';
import {
Category,
CategoryType,
} from '../../../components/tf_categorization_utils/categorizationUtils';
import '../../../components/tf_dashboard_common/dashboard-style';
import '../../../components/tf_dashboard_common/tf-dashboard-layout';
import '../../../components/tf_dashboard_common/tf-option-selector';
import '../../../components/tf_paginated_view/tf-category-paginated-view';
import '../../../components/tf_runs_selector/tf-runs-selector';
import {
getBooleanInitializer,
getBooleanObserver,
getNumberInitializer,
getNumberObserver,
} from '../../../components/tf_storage/storage';
import '../../../components/tf_utils/utils';
import '../../scalar/tf_scalar_dashboard/tf-smoothing-input';
import {Layout} from './tf-custom-scalar-helpers';
import './tf-custom-scalar-margin-chart-card';
import {TfCustomScalarMarginChartCard} from './tf-custom-scalar-margin-chart-card';
import './tf-custom-scalar-multi-line-chart-card';
import {TfCustomScalarMultiLineChartCard} from './tf-custom-scalar-multi-line-chart-card';
@customElement('tf-custom-scalar-dashboard')
class TfCustomScalarDashboard extends PolymerElement {
static readonly template = html`
<tf-dashboard-layout>
<div class="sidebar" slot="sidebar">
<div class="settings">
<div class="sidebar-section">
<div class="line-item">
<paper-checkbox checked="{{_showDownloadLinks}}"
>Show data download links</paper-checkbox
>
</div>
<div class="line-item">
<paper-checkbox checked="{{_ignoreYOutliers}}"
>Ignore outliers in chart scaling</paper-checkbox
>
</div>
<div id="tooltip-sorting">
<div id="tooltip-sorting-label">Tooltip sorting method:</div>
<paper-dropdown-menu
no-label-float=""
selected-item-label="{{_tooltipSortingMethod}}"
>
<paper-listbox
class="dropdown-content"
selected="0"
slot="dropdown-content"
>
<paper-item>default</paper-item>
<paper-item>descending</paper-item>
<paper-item>ascending</paper-item>
<paper-item>nearest</paper-item>
</paper-listbox>
</paper-dropdown-menu>
</div>
</div>
<div class="sidebar-section">
<tf-smoothing-input
weight="{{_smoothingWeight}}"
step="0.001"
min="0"
max="1"
></tf-smoothing-input>
</div>
<div class="sidebar-section">
<tf-option-selector
id="x-type-selector"
name="Horizontal Axis"
selected-id="{{_xType}}"
>
<paper-button id="step">step</paper-button
><!--
--><paper-button id="relative">relative</paper-button
><!--
--><paper-button id="wall_time">wall</paper-button>
</tf-option-selector>
</div>
</div>
<div class="sidebar-section runs-selector">
<tf-runs-selector selected-runs="{{_selectedRuns}}">
</tf-runs-selector>
</div>
</div>
<div class="center" slot="center" id="categories-container">
<template is="dom-if" if="[[_dataNotFound]]">
<div class="no-data-warning">
<h3>The custom scalars dashboard is inactive.</h3>
<p>Probable causes:</p>
<ol>
<li>You haven't laid out the dashboard.</li>
<li>You haven’t written any scalar data to your event files.</li>
</ol>
<p>
To lay out the dashboard, pass a <code>Layout</code> protobuffer
to the <code>set_layout</code> method. For example,
</p>
<pre>
from tensorboard import summary
from tensorboard.plugins.custom_scalar import layout_pb2
...
# This action does not have to be performed at every step, so the action is not
# taken care of by an op in the graph. We only need to specify the layout once
# (instead of per step).
layout_summary = summary_lib.custom_scalar_pb(layout_pb2.Layout(
category=[
layout_pb2.Category(
title='losses',
chart=[
layout_pb2.Chart(
title='losses',
multiline=layout_pb2.MultilineChartContent(
tag=[r'loss.*'],
)),
layout_pb2.Chart(
title='baz',
margin=layout_pb2.MarginChartContent(
series=[
layout_pb2.MarginChartContent.Series(
value='loss/baz/scalar_summary',
lower='baz_lower/baz/scalar_summary',
upper='baz_upper/baz/scalar_summary'),
],
)),
]),
layout_pb2.Category(
title='trig functions',
chart=[
layout_pb2.Chart(
title='wave trig functions',
multiline=layout_pb2.MultilineChartContent(
tag=[r'trigFunctions/cosine', r'trigFunctions/sine'],
)),
# The range of tangent is different. Let's give it its own chart.
layout_pb2.Chart(
title='tan',
multiline=layout_pb2.MultilineChartContent(
tag=[r'trigFunctions/tangent'],
)),
],
# This category we care less about. Let's make it initially closed.
closed=True),
]))
writer.add_summary(layout_summary)
</pre
>
<p>
If you’re new to using TensorBoard, and want to find out how to
add data and set up your event files, check out the
<a
href="https://github.com/tensorflow/tensorboard/blob/master/README.md"
>README</a
>
and perhaps the
<a
href="https://www.tensorflow.org/get_started/summaries_and_tensorboard"
>TensorBoard tutorial</a
>.
</p>
</div>
</template>
<template is="dom-if" if="[[!_dataNotFound]]">
<template is="dom-repeat" items="[[_categories]]" as="category">
<tf-category-paginated-view
as="chart"
category="[[category]]"
disable-pagination
initial-opened="[[category.metadata.opened]]"
>
<template>
<template is="dom-if" if="[[chart.multiline]]">
<tf-custom-scalar-multi-line-chart-card
active="[[active]]"
request-manager="[[_requestManager]]"
runs="[[_selectedRuns]]"
title="[[chart.title]]"
x-type="[[_xType]]"
smoothing-enabled="[[_smoothingEnabled]]"
smoothing-weight="[[_smoothingWeight]]"
tooltip-sorting-method="[[tooltipSortingMethod]]"
ignore-y-outliers="[[_ignoreYOutliers]]"
show-download-links="[[_showDownloadLinks]]"
tag-regexes="[[chart.multiline.tag]]"
></tf-custom-scalar-multi-line-chart-card>
</template>
<template is="dom-if" if="[[chart.margin]]">
<tf-custom-scalar-margin-chart-card
active="[[active]]"
request-manager="[[_requestManager]]"
runs="[[_selectedRuns]]"
title="[[chart.title]]"
x-type="[[_xType]]"
tooltip-sorting-method="[[tooltipSortingMethod]]"
ignore-y-outliers="[[_ignoreYOutliers]]"
show-download-links="[[_showDownloadLinks]]"
margin-chart-series="[[chart.margin.series]]"
></tf-custom-scalar-margin-chart-card>
</template>
</template>
</tf-category-paginated-view>
</template>
</template>
</div>
</tf-dashboard-layout>
<style include="dashboard-style"></style>
<style>
#tooltip-sorting {
align-items: center;
display: flex;
font-size: 14px;
margin-top: 15px;
}
#tooltip-sorting paper-dropdown-menu {
margin-left: 10px;
--paper-input-container-focus-color: var(--tb-orange-strong);
width: 105px;
}
.line-item {
display: block;
padding-top: 5px;
}
.no-data-warning {
max-width: 540px;
margin: 80px auto 0 auto;
}
</style>
`;
@property({type: Object})
_requestManager: RequestManager = new RequestManager(50);
@property({type: Object})
_canceller: Canceller = new Canceller();
@property({type: Array})
_selectedRuns: unknown[];
@property({
type: Boolean,
notify: true,
observer: '_showDownloadLinksObserver',
})
_showDownloadLinks: boolean = getBooleanInitializer('_showDownloadLinks', {
defaultValue: false,
useLocalStorage: true,
}).call(this);
@property({
type: Number,
notify: true,
observer: '_smoothingWeightObserver',
})
_smoothingWeight: number = getNumberInitializer('_smoothingWeight', {
defaultValue: 0.6,
}).call(this);
@property({
type: Boolean,
observer: '_ignoreYOutliersObserver',
})
_ignoreYOutliers: boolean = getBooleanInitializer('_ignoreYOutliers', {
defaultValue: true,
useLocalStorage: true,
}).call(this);
@property({type: String})
_xType: string = 'step';
@property({type: Object})
_layout: Layout;
@property({type: Boolean})
_dataNotFound: boolean;
@property({type: Object})
_openedCategories: object;
@property({type: Boolean})
_active: boolean = true;
@property({type: Boolean})
reloadOnReady: boolean = true;
ready() {
super.ready();
if (this.reloadOnReady) this.reload();
}
reload() {
const url = getRouter().pluginsListing();
const handlePluginsListingResponse = this._canceller.cancellable(
(result) => {
if (result.cancelled) {
return;
}
this.set('_dataNotFound', !result.value['custom_scalars']);
if (this._dataNotFound) {
return;
}
this._retrieveLayoutAndData();
}
);
this._requestManager.request(url).then(handlePluginsListingResponse);
}
_reloadCharts() {
const charts = this.root.querySelectorAll(
'tf-custom-scalar-margin-chart-card, ' +
'tf-custom-scalar-multi-line-chart-card'
);
charts.forEach(
(
chart: TfCustomScalarMarginChartCard | TfCustomScalarMultiLineChartCard
) => {
chart.reload();
}
);
}
_retrieveLayoutAndData() {
const url = getRouter().pluginRoute('custom_scalars', '/layout');
const update = this._canceller.cancellable((result) => {
if (result.cancelled) {
return;
}
// This plugin is only active if data is available.
this.set('_layout', result.value);
if (!this._dataNotFound) {
this._reloadCharts();
}
});
this._requestManager.request(url).then(update);
}
_showDownloadLinksObserver = getBooleanObserver('_showDownloadLinks', {
defaultValue: false,
useLocalStorage: true,
});
_smoothingWeightObserver = getNumberObserver('_smoothingWeight', {
defaultValue: 0.6,
});
_ignoreYOutliersObserver = getBooleanObserver('_ignoreYOutliers', {
defaultValue: true,
useLocalStorage: true,
});
@computed('_smoothingWeight')
get _smoothingEnabled(): boolean {
var _smoothingWeight = this._smoothingWeight;
return _smoothingWeight > 0;
}
@computed('_layout')
get _categories(): Category<unknown>[] {
var layout = this._layout;
if (!layout.category) {
return [];
}
let firstTimeLoad = false;
if (!this._openedCategories) {
// This is the first time the user loads the categories. Start storing
// which categories are open.
firstTimeLoad = true;
this._openedCategories = {};
}
const categories = layout.category.map((category) => {
if (firstTimeLoad && !(category as any) /* ??? */.closed) {
// Remember whether this category is currently open.
this._openedCategories[category.title] = true;
}
return {
name: category.title,
items: category.chart,
metadata: {
type: CategoryType.PREFIX_GROUP,
opened: !!this._openedCategories[category.title],
},
};
});
return categories;
}
_categoryOpenedToggled(event) {
const pane = event.target;
if (pane.opened) {
this._openedCategories[pane.category.name] = true;
} else {
delete this._openedCategories[pane.category.name];
}
}
} | the_stack |
import {
ChangeDetectionStrategy,
Component,
ElementRef,
HostBinding,
HostListener,
Input,
Renderer2,
ViewChild
} from '@angular/core';
import {
IgxListPanState,
IListChild,
IgxListBaseDirective
} from './list.common';
import { HammerGesturesManager } from '../core/touch';
/**
* The Ignite UI List Item component is a container intended for row items in the Ignite UI for Angular List component.
*
* Example:
* ```html
* <igx-list>
* <igx-list-item isHeader="true">Contacts</igx-list-item>
* <igx-list-item *ngFor="let contact of contacts">
* <span class="name">{{ contact.name }}</span>
* <span class="phone">{{ contact.phone }}</span>
* </igx-list-item>
* </igx-list>
* ```
*/
@Component({
providers: [HammerGesturesManager],
selector: 'igx-list-item',
templateUrl: 'list-item.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class IgxListItemComponent implements IListChild {
/**
* Provides a reference to the template's base element shown when left panning a list item.
* ```typescript
* const leftPanTmpl = this.listItem.leftPanningTemplateElement;
* ```
*/
@ViewChild('leftPanningTmpl')
public leftPanningTemplateElement;
/**
* Provides a reference to the template's base element shown when right panning a list item.
* ```typescript
* const rightPanTmpl = this.listItem.rightPanningTemplateElement;
* ```
*/
@ViewChild('rightPanningTmpl')
public rightPanningTemplateElement;
/**
* Sets/gets whether the `list item` is a header.
* ```html
* <igx-list-item [isHeader] = "true">Header</igx-list-item>
* ```
* ```typescript
* let isHeader = this.listItem.isHeader;
* ```
*
* @memberof IgxListItemComponent
*/
@Input()
public isHeader: boolean;
/**
* Sets/gets whether the `list item` is hidden.
* By default the `hidden` value is `false`.
* ```html
* <igx-list-item [hidden] = "true">Hidden Item</igx-list-item>
* ```
* ```typescript
* let isHidden = this.listItem.hidden;
* ```
*
* @memberof IgxListItemComponent
*/
@Input()
public hidden = false;
/**
* Sets/gets the `aria-label` attribute of the `list item`.
* ```typescript
* this.listItem.ariaLabel = "Item1";
* ```
* ```typescript
* let itemAriaLabel = this.listItem.ariaLabel;
* ```
*
* @memberof IgxListItemComponent
*/
@HostBinding('attr.aria-label')
public ariaLabel: string;
/**
* Gets the `touch-action` style of the `list item`.
* ```typescript
* let touchAction = this.listItem.touchAction;
* ```
*/
@HostBinding('style.touch-action')
public touchAction = 'pan-y';
/**
* @hidden
*/
private _panState: IgxListPanState = IgxListPanState.NONE;
/**
* @hidden
*/
private panOffset = 0;
/**
* @hidden
*/
private _index: number = null;
/**
* @hidden
*/
private lastPanDir = IgxListPanState.NONE;
/**
* Gets the `panState` of a `list item`.
* ```typescript
* let itemPanState = this.listItem.panState;
* ```
*
* @memberof IgxListItemComponent
*/
public get panState(): IgxListPanState {
return this._panState;
}
/**
* Gets the `index` of a `list item`.
* ```typescript
* let itemIndex = this.listItem.index;
* ```
*
* @memberof IgxListItemComponent
*/
@Input()
public get index(): number {
return this._index !== null ? this._index : this.list.children.toArray().indexOf(this);
}
/**
* Sets the `index` of the `list item`.
* ```typescript
* this.listItem.index = index;
* ```
*
* @memberof IgxListItemComponent
*/
public set index(value: number) {
this._index = value;
}
/**
* Returns an element reference to the list item.
* ```typescript
* let listItemElement = this.listItem.element.
* ```
*
* @memberof IgxListItemComponent
*/
public get element() {
return this.elementRef.nativeElement;
}
/**
* Returns a reference container which contains the list item's content.
* ```typescript
* let listItemContainer = this.listItem.contentElement.
* ```
*
* @memberof IgxListItemComponent
*/
public get contentElement() {
const candidates = this.element.getElementsByClassName('igx-list__item-content');
return (candidates && candidates.length > 0) ? candidates[0] : null;
}
/**
* Returns the `context` object which represents the `template context` binding into the `list item container`
* by providing the `$implicit` declaration which is the `IgxListItemComponent` itself.
* ```typescript
* let listItemComponent = this.listItem.context;
* ```
*/
public get context(): any {
return {
$implicit: this
};
}
/**
* Gets the width of a `list item`.
* ```typescript
* let itemWidth = this.listItem.width;
* ```
*
* @memberof IgxListItemComponent
*/
public get width() {
if (this.element) {
return this.element.offsetWidth;
}
}
/**
* Gets the maximum left position of the `list item`.
* ```typescript
* let maxLeft = this.listItem.maxLeft;
* ```
*
* @memberof IgxListItemComponent
*/
public get maxLeft() {
return -this.width;
}
/**
* Gets the maximum right position of the `list item`.
* ```typescript
* let maxRight = this.listItem.maxRight;
* ```
*
* @memberof IgxListItemComponent
*/
public get maxRight() {
return this.width;
}
constructor(
public list: IgxListBaseDirective,
private elementRef: ElementRef,
private _renderer: Renderer2) {
}
/**
* Gets the `role` attribute of the `list item`.
* ```typescript
* let itemRole = this.listItem.role;
* ```
*
* @memberof IgxListItemComponent
*/
@HostBinding('attr.role')
public get role() {
return this.isHeader ? 'separator' : 'listitem';
}
/**
* Indicates whether `list item` should have header style.
* ```typescript
* let headerStyle = this.listItem.headerStyle;
* ```
*
* @memberof IgxListItemComponent
*/
@HostBinding('class.igx-list__header')
public get headerStyle(): boolean {
return this.isHeader;
}
/**
* Applies the inner style of the `list item` if the item is not counted as header.
* ```typescript
* let innerStyle = this.listItem.innerStyle;
* ```
*
* @memberof IgxListItemComponent
*/
@HostBinding('class.igx-list__item-base')
public get innerStyle(): boolean {
return !this.isHeader;
}
/**
* Returns string value which describes the display mode of the `list item`.
* ```typescript
* let isHidden = this.listItem.display;
* ```
*
* @memberof IgxListItemComponent
*/
@HostBinding('style.display')
public get display(): string {
return this.hidden ? 'none' : '';
}
/**
* @hidden
*/
@HostListener('click', ['$event'])
public clicked(evt) {
this.list.itemClicked.emit({ item: this, event: evt, direction: this.lastPanDir });
this.lastPanDir = IgxListPanState.NONE;
}
/**
* @hidden
*/
@HostListener('panstart')
public panStart() {
if (this.isTrue(this.isHeader)) {
return;
}
if (!this.isTrue(this.list.allowLeftPanning) && !this.isTrue(this.list.allowRightPanning)) {
return;
}
this.list.startPan.emit({ item: this, direction: this.lastPanDir, keepitem: false });
}
/**
* @hidden
*/
@HostListener('pancancel')
public panCancel() {
this.resetPanPosition();
this.list.endPan.emit({item: this, direction: this.lastPanDir, keepItem: false});
}
/**
* @hidden
*/
@HostListener('panmove', ['$event'])
public panMove(ev) {
if (this.isTrue(this.isHeader)) {
return;
}
if (!this.isTrue(this.list.allowLeftPanning) && !this.isTrue(this.list.allowRightPanning)) {
return;
}
const isPanningToLeft = ev.deltaX < 0;
if (isPanningToLeft && this.isTrue(this.list.allowLeftPanning)) {
this.showLeftPanTemplate();
this.setContentElementLeft(Math.max(this.maxLeft, ev.deltaX));
} else if (!isPanningToLeft && this.isTrue(this.list.allowRightPanning)) {
this.showRightPanTemplate();
this.setContentElementLeft(Math.min(this.maxRight, ev.deltaX));
}
}
/**
* @hidden
*/
@HostListener('panend')
public panEnd() {
if (this.isTrue(this.isHeader)) {
return;
}
if (!this.isTrue(this.list.allowLeftPanning) && !this.isTrue(this.list.allowRightPanning)) {
return;
}
// the translation offset of the current list item content
const relativeOffset = this.panOffset;
const widthTriggeringGrip = this.width * this.list.panEndTriggeringThreshold;
if (relativeOffset === 0) {
return; // no panning has occured
}
const dir = relativeOffset > 0 ? IgxListPanState.RIGHT : IgxListPanState.LEFT;
this.lastPanDir = dir;
const args = { item: this, direction: dir, keepItem: false};
this.list.endPan.emit(args);
const oldPanState = this._panState;
if (Math.abs(relativeOffset) < widthTriggeringGrip) {
this.resetPanPosition();
this.list.resetPan.emit(this);
return;
}
if (dir === IgxListPanState.LEFT) {
this.list.leftPan.emit(args);
} else {
this.list.rightPan.emit(args);
}
if (args.keepItem === true) {
this.setContentElementLeft(0);
this._panState = IgxListPanState.NONE;
} else {
if (dir === IgxListPanState.LEFT) {
this.setContentElementLeft(this.maxLeft);
this._panState = IgxListPanState.LEFT;
} else {
this.setContentElementLeft(this.maxRight);
this._panState = IgxListPanState.RIGHT;
}
}
if (oldPanState !== this._panState) {
const args2 = { oldState: oldPanState, newState: this._panState, item: this };
this.list.panStateChange.emit(args2);
}
this.hideLeftAndRightPanTemplates();
}
/**
* @hidden
*/
private showLeftPanTemplate() {
this.setLeftAndRightTemplatesVisibility('visible', 'hidden');
}
/**
* @hidden
*/
private showRightPanTemplate() {
this.setLeftAndRightTemplatesVisibility('hidden', 'visible');
}
/**
* @hidden
*/
private hideLeftAndRightPanTemplates() {
setTimeout(() => {
this.setLeftAndRightTemplatesVisibility('hidden', 'hidden');
}, 500);
}
/**
* @hidden
*/
private setLeftAndRightTemplatesVisibility(leftVisibility, rightVisibility) {
if (this.leftPanningTemplateElement && this.leftPanningTemplateElement.nativeElement) {
this.leftPanningTemplateElement.nativeElement.style.visibility = leftVisibility;
}
if (this.rightPanningTemplateElement && this.rightPanningTemplateElement.nativeElement) {
this.rightPanningTemplateElement.nativeElement.style.visibility = rightVisibility;
}
}
/**
* @hidden
*/
private setContentElementLeft(value: number) {
this.panOffset = value;
this.contentElement.style.transform = 'translateX(' + value + 'px)';
}
/**
* @hidden
*/
private isTrue(value: boolean): boolean {
if (typeof (value) === 'boolean') {
return value;
} else {
return value === 'true';
}
}
/**
* @hidden
*/
private resetPanPosition() {
this.setContentElementLeft(0);
this._panState = IgxListPanState.NONE;
this.hideLeftAndRightPanTemplates();
}
} | the_stack |
import { KubernetesObject } from 'kpt-functions';
import * as apisMetaV1 from './io.k8s.apimachinery.pkg.apis.meta.v1';
// MutatingWebhook describes an admission webhook and the resources and operations it applies to.
export class MutatingWebhook {
// AdmissionReviewVersions is an ordered list of preferred `AdmissionReview` versions the Webhook expects. API server will try to use first version in the list which it supports. If none of the versions specified in this list supported by API server, validation will fail for this object. If a persisted webhook configuration specifies allowed versions and does not include any versions known to the API Server, calls to the webhook will fail and be subject to the failure policy. Default to `['v1beta1']`.
public admissionReviewVersions?: string[];
// ClientConfig defines how to communicate with the hook. Required
public clientConfig: WebhookClientConfig;
// FailurePolicy defines how unrecognized errors from the admission endpoint are handled - allowed values are Ignore or Fail. Defaults to Ignore.
public failurePolicy?: string;
// matchPolicy defines how the "rules" list is used to match incoming requests. Allowed values are "Exact" or "Equivalent".
//
// - Exact: match a request only if it exactly matches a specified rule. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, but "rules" only included `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]`, a request to apps/v1beta1 or extensions/v1beta1 would not be sent to the webhook.
//
// - Equivalent: match a request if modifies a resource listed in rules, even via another API group or version. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, and "rules" only included `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]`, a request to apps/v1beta1 or extensions/v1beta1 would be converted to apps/v1 and sent to the webhook.
//
// Defaults to "Exact"
public matchPolicy?: string;
// The name of the admission webhook. Name should be fully qualified, e.g., imagepolicy.kubernetes.io, where "imagepolicy" is the name of the webhook, and kubernetes.io is the name of the organization. Required.
public name: string;
// NamespaceSelector decides whether to run the webhook on an object based on whether the namespace for that object matches the selector. If the object itself is a namespace, the matching is performed on object.metadata.labels. If the object is another cluster scoped resource, it never skips the webhook.
//
// For example, to run the webhook on any objects whose namespace is not associated with "runlevel" of "0" or "1"; you will set the selector as follows: "namespaceSelector": {
// "matchExpressions": [
// {
// "key": "runlevel",
// "operator": "NotIn",
// "values": [
// "0",
// "1"
// ]
// }
// ]
// }
//
// If instead you want to only run the webhook on any objects whose namespace is associated with the "environment" of "prod" or "staging"; you will set the selector as follows: "namespaceSelector": {
// "matchExpressions": [
// {
// "key": "environment",
// "operator": "In",
// "values": [
// "prod",
// "staging"
// ]
// }
// ]
// }
//
// See https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ for more examples of label selectors.
//
// Default to the empty LabelSelector, which matches everything.
public namespaceSelector?: apisMetaV1.LabelSelector;
// ObjectSelector decides whether to run the webhook based on if the object has matching labels. objectSelector is evaluated against both the oldObject and newObject that would be sent to the webhook, and is considered to match if either object matches the selector. A null object (oldObject in the case of create, or newObject in the case of delete) or an object that cannot have labels (like a DeploymentRollback or a PodProxyOptions object) is not considered to match. Use the object selector only if the webhook is opt-in, because end users may skip the admission webhook by setting the labels. Default to the empty LabelSelector, which matches everything.
public objectSelector?: apisMetaV1.LabelSelector;
// reinvocationPolicy indicates whether this webhook should be called multiple times as part of a single admission evaluation. Allowed values are "Never" and "IfNeeded".
//
// Never: the webhook will not be called more than once in a single admission evaluation.
//
// IfNeeded: the webhook will be called at least one additional time as part of the admission evaluation if the object being admitted is modified by other admission plugins after the initial webhook call. Webhooks that specify this option *must* be idempotent, able to process objects they previously admitted. Note: * the number of additional invocations is not guaranteed to be exactly one. * if additional invocations result in further modifications to the object, webhooks are not guaranteed to be invoked again. * webhooks that use this option may be reordered to minimize the number of additional invocations. * to validate an object after all mutations are guaranteed complete, use a validating admission webhook instead.
//
// Defaults to "Never".
public reinvocationPolicy?: string;
// Rules describes what operations on what resources/subresources the webhook cares about. The webhook cares about an operation if it matches _any_ Rule. However, in order to prevent ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks from putting the cluster in a state which cannot be recovered from without completely disabling the plugin, ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks are never called on admission requests for ValidatingWebhookConfiguration and MutatingWebhookConfiguration objects.
public rules?: RuleWithOperations[];
// SideEffects states whether this webhookk has side effects. Acceptable values are: Unknown, None, Some, NoneOnDryRun Webhooks with side effects MUST implement a reconciliation system, since a request may be rejected by a future step in the admission change and the side effects therefore need to be undone. Requests with the dryRun attribute will be auto-rejected if they match a webhook with sideEffects == Unknown or Some. Defaults to Unknown.
public sideEffects?: string;
// TimeoutSeconds specifies the timeout for this webhook. After the timeout passes, the webhook call will be ignored or the API call will fail based on the failure policy. The timeout value must be between 1 and 30 seconds. Default to 30 seconds.
public timeoutSeconds?: number;
constructor(desc: MutatingWebhook) {
this.admissionReviewVersions = desc.admissionReviewVersions;
this.clientConfig = desc.clientConfig;
this.failurePolicy = desc.failurePolicy;
this.matchPolicy = desc.matchPolicy;
this.name = desc.name;
this.namespaceSelector = desc.namespaceSelector;
this.objectSelector = desc.objectSelector;
this.reinvocationPolicy = desc.reinvocationPolicy;
this.rules = desc.rules;
this.sideEffects = desc.sideEffects;
this.timeoutSeconds = desc.timeoutSeconds;
}
}
// MutatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and may change the object.
export class MutatingWebhookConfiguration implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata.
public metadata: apisMetaV1.ObjectMeta;
// Webhooks is a list of webhooks and the affected resources and operations.
public webhooks?: MutatingWebhook[];
constructor(desc: MutatingWebhookConfiguration.Interface) {
this.apiVersion = MutatingWebhookConfiguration.apiVersion;
this.kind = MutatingWebhookConfiguration.kind;
this.metadata = desc.metadata;
this.webhooks = desc.webhooks;
}
}
export function isMutatingWebhookConfiguration(
o: any
): o is MutatingWebhookConfiguration {
return (
o &&
o.apiVersion === MutatingWebhookConfiguration.apiVersion &&
o.kind === MutatingWebhookConfiguration.kind
);
}
export namespace MutatingWebhookConfiguration {
export const apiVersion = 'admissionregistration.k8s.io/v1beta1';
export const group = 'admissionregistration.k8s.io';
export const version = 'v1beta1';
export const kind = 'MutatingWebhookConfiguration';
// named constructs a MutatingWebhookConfiguration with metadata.name set to name.
export function named(name: string): MutatingWebhookConfiguration {
return new MutatingWebhookConfiguration({ metadata: { name } });
}
// MutatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and may change the object.
export interface Interface {
// Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata.
metadata: apisMetaV1.ObjectMeta;
// Webhooks is a list of webhooks and the affected resources and operations.
webhooks?: MutatingWebhook[];
}
}
// MutatingWebhookConfigurationList is a list of MutatingWebhookConfiguration.
export class MutatingWebhookConfigurationList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// List of MutatingWebhookConfiguration.
public items: MutatingWebhookConfiguration[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public metadata?: apisMetaV1.ListMeta;
constructor(desc: MutatingWebhookConfigurationList) {
this.apiVersion = MutatingWebhookConfigurationList.apiVersion;
this.items = desc.items.map((i) => new MutatingWebhookConfiguration(i));
this.kind = MutatingWebhookConfigurationList.kind;
this.metadata = desc.metadata;
}
}
export function isMutatingWebhookConfigurationList(
o: any
): o is MutatingWebhookConfigurationList {
return (
o &&
o.apiVersion === MutatingWebhookConfigurationList.apiVersion &&
o.kind === MutatingWebhookConfigurationList.kind
);
}
export namespace MutatingWebhookConfigurationList {
export const apiVersion = 'admissionregistration.k8s.io/v1beta1';
export const group = 'admissionregistration.k8s.io';
export const version = 'v1beta1';
export const kind = 'MutatingWebhookConfigurationList';
// MutatingWebhookConfigurationList is a list of MutatingWebhookConfiguration.
export interface Interface {
// List of MutatingWebhookConfiguration.
items: MutatingWebhookConfiguration[];
// Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
metadata?: apisMetaV1.ListMeta;
}
}
// RuleWithOperations is a tuple of Operations and Resources. It is recommended to make sure that all the tuple expansions are valid.
export class RuleWithOperations {
// APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required.
public apiGroups?: string[];
// APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length of the slice must be one. Required.
public apiVersions?: string[];
// Operations is the operations the admission hook cares about - CREATE, UPDATE, or * for all operations. If '*' is present, the length of the slice must be one. Required.
public operations?: string[];
// Resources is a list of resources this rule applies to.
//
// For example: 'pods' means pods. 'pods/log' means the log subresource of pods. '*' means all resources, but not subresources. 'pods/*' means all subresources of pods. '*/scale' means all scale subresources. '*/*' means all resources and their subresources.
//
// If wildcard is present, the validation rule will ensure resources do not overlap with each other.
//
// Depending on the enclosing object, subresources might not be allowed. Required.
public resources?: string[];
// scope specifies the scope of this rule. Valid values are "Cluster", "Namespaced", and "*" "Cluster" means that only cluster-scoped resources will match this rule. Namespace API objects are cluster-scoped. "Namespaced" means that only namespaced resources will match this rule. "*" means that there are no scope restrictions. Subresources match the scope of their parent resource. Default is "*".
public scope?: string;
}
// ServiceReference holds a reference to Service.legacy.k8s.io
export class ServiceReference {
// `name` is the name of the service. Required
public name: string;
// `namespace` is the namespace of the service. Required
public namespace: string;
// `path` is an optional URL path which will be sent in any request to this service.
public path?: string;
// If specified, the port on the service that hosting webhook. Default to 443 for backward compatibility. `port` should be a valid port number (1-65535, inclusive).
public port?: number;
constructor(desc: ServiceReference) {
this.name = desc.name;
this.namespace = desc.namespace;
this.path = desc.path;
this.port = desc.port;
}
}
// ValidatingWebhook describes an admission webhook and the resources and operations it applies to.
export class ValidatingWebhook {
// AdmissionReviewVersions is an ordered list of preferred `AdmissionReview` versions the Webhook expects. API server will try to use first version in the list which it supports. If none of the versions specified in this list supported by API server, validation will fail for this object. If a persisted webhook configuration specifies allowed versions and does not include any versions known to the API Server, calls to the webhook will fail and be subject to the failure policy. Default to `['v1beta1']`.
public admissionReviewVersions?: string[];
// ClientConfig defines how to communicate with the hook. Required
public clientConfig: WebhookClientConfig;
// FailurePolicy defines how unrecognized errors from the admission endpoint are handled - allowed values are Ignore or Fail. Defaults to Ignore.
public failurePolicy?: string;
// matchPolicy defines how the "rules" list is used to match incoming requests. Allowed values are "Exact" or "Equivalent".
//
// - Exact: match a request only if it exactly matches a specified rule. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, but "rules" only included `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]`, a request to apps/v1beta1 or extensions/v1beta1 would not be sent to the webhook.
//
// - Equivalent: match a request if modifies a resource listed in rules, even via another API group or version. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, and "rules" only included `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]`, a request to apps/v1beta1 or extensions/v1beta1 would be converted to apps/v1 and sent to the webhook.
//
// Defaults to "Exact"
public matchPolicy?: string;
// The name of the admission webhook. Name should be fully qualified, e.g., imagepolicy.kubernetes.io, where "imagepolicy" is the name of the webhook, and kubernetes.io is the name of the organization. Required.
public name: string;
// NamespaceSelector decides whether to run the webhook on an object based on whether the namespace for that object matches the selector. If the object itself is a namespace, the matching is performed on object.metadata.labels. If the object is another cluster scoped resource, it never skips the webhook.
//
// For example, to run the webhook on any objects whose namespace is not associated with "runlevel" of "0" or "1"; you will set the selector as follows: "namespaceSelector": {
// "matchExpressions": [
// {
// "key": "runlevel",
// "operator": "NotIn",
// "values": [
// "0",
// "1"
// ]
// }
// ]
// }
//
// If instead you want to only run the webhook on any objects whose namespace is associated with the "environment" of "prod" or "staging"; you will set the selector as follows: "namespaceSelector": {
// "matchExpressions": [
// {
// "key": "environment",
// "operator": "In",
// "values": [
// "prod",
// "staging"
// ]
// }
// ]
// }
//
// See https://kubernetes.io/docs/concepts/overview/working-with-objects/labels for more examples of label selectors.
//
// Default to the empty LabelSelector, which matches everything.
public namespaceSelector?: apisMetaV1.LabelSelector;
// ObjectSelector decides whether to run the webhook based on if the object has matching labels. objectSelector is evaluated against both the oldObject and newObject that would be sent to the webhook, and is considered to match if either object matches the selector. A null object (oldObject in the case of create, or newObject in the case of delete) or an object that cannot have labels (like a DeploymentRollback or a PodProxyOptions object) is not considered to match. Use the object selector only if the webhook is opt-in, because end users may skip the admission webhook by setting the labels. Default to the empty LabelSelector, which matches everything.
public objectSelector?: apisMetaV1.LabelSelector;
// Rules describes what operations on what resources/subresources the webhook cares about. The webhook cares about an operation if it matches _any_ Rule. However, in order to prevent ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks from putting the cluster in a state which cannot be recovered from without completely disabling the plugin, ValidatingAdmissionWebhooks and MutatingAdmissionWebhooks are never called on admission requests for ValidatingWebhookConfiguration and MutatingWebhookConfiguration objects.
public rules?: RuleWithOperations[];
// SideEffects states whether this webhookk has side effects. Acceptable values are: Unknown, None, Some, NoneOnDryRun Webhooks with side effects MUST implement a reconciliation system, since a request may be rejected by a future step in the admission change and the side effects therefore need to be undone. Requests with the dryRun attribute will be auto-rejected if they match a webhook with sideEffects == Unknown or Some. Defaults to Unknown.
public sideEffects?: string;
// TimeoutSeconds specifies the timeout for this webhook. After the timeout passes, the webhook call will be ignored or the API call will fail based on the failure policy. The timeout value must be between 1 and 30 seconds. Default to 30 seconds.
public timeoutSeconds?: number;
constructor(desc: ValidatingWebhook) {
this.admissionReviewVersions = desc.admissionReviewVersions;
this.clientConfig = desc.clientConfig;
this.failurePolicy = desc.failurePolicy;
this.matchPolicy = desc.matchPolicy;
this.name = desc.name;
this.namespaceSelector = desc.namespaceSelector;
this.objectSelector = desc.objectSelector;
this.rules = desc.rules;
this.sideEffects = desc.sideEffects;
this.timeoutSeconds = desc.timeoutSeconds;
}
}
// ValidatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and object without changing it.
export class ValidatingWebhookConfiguration implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata.
public metadata: apisMetaV1.ObjectMeta;
// Webhooks is a list of webhooks and the affected resources and operations.
public webhooks?: ValidatingWebhook[];
constructor(desc: ValidatingWebhookConfiguration.Interface) {
this.apiVersion = ValidatingWebhookConfiguration.apiVersion;
this.kind = ValidatingWebhookConfiguration.kind;
this.metadata = desc.metadata;
this.webhooks = desc.webhooks;
}
}
export function isValidatingWebhookConfiguration(
o: any
): o is ValidatingWebhookConfiguration {
return (
o &&
o.apiVersion === ValidatingWebhookConfiguration.apiVersion &&
o.kind === ValidatingWebhookConfiguration.kind
);
}
export namespace ValidatingWebhookConfiguration {
export const apiVersion = 'admissionregistration.k8s.io/v1beta1';
export const group = 'admissionregistration.k8s.io';
export const version = 'v1beta1';
export const kind = 'ValidatingWebhookConfiguration';
// named constructs a ValidatingWebhookConfiguration with metadata.name set to name.
export function named(name: string): ValidatingWebhookConfiguration {
return new ValidatingWebhookConfiguration({ metadata: { name } });
}
// ValidatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and object without changing it.
export interface Interface {
// Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata.
metadata: apisMetaV1.ObjectMeta;
// Webhooks is a list of webhooks and the affected resources and operations.
webhooks?: ValidatingWebhook[];
}
}
// ValidatingWebhookConfigurationList is a list of ValidatingWebhookConfiguration.
export class ValidatingWebhookConfigurationList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// List of ValidatingWebhookConfiguration.
public items: ValidatingWebhookConfiguration[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public metadata?: apisMetaV1.ListMeta;
constructor(desc: ValidatingWebhookConfigurationList) {
this.apiVersion = ValidatingWebhookConfigurationList.apiVersion;
this.items = desc.items.map((i) => new ValidatingWebhookConfiguration(i));
this.kind = ValidatingWebhookConfigurationList.kind;
this.metadata = desc.metadata;
}
}
export function isValidatingWebhookConfigurationList(
o: any
): o is ValidatingWebhookConfigurationList {
return (
o &&
o.apiVersion === ValidatingWebhookConfigurationList.apiVersion &&
o.kind === ValidatingWebhookConfigurationList.kind
);
}
export namespace ValidatingWebhookConfigurationList {
export const apiVersion = 'admissionregistration.k8s.io/v1beta1';
export const group = 'admissionregistration.k8s.io';
export const version = 'v1beta1';
export const kind = 'ValidatingWebhookConfigurationList';
// ValidatingWebhookConfigurationList is a list of ValidatingWebhookConfiguration.
export interface Interface {
// List of ValidatingWebhookConfiguration.
items: ValidatingWebhookConfiguration[];
// Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
metadata?: apisMetaV1.ListMeta;
}
}
// WebhookClientConfig contains the information to make a TLS connection with the webhook
export class WebhookClientConfig {
// `caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. If unspecified, system trust roots on the apiserver are used.
public caBundle?: string;
// `service` is a reference to the service for this webhook. Either `service` or `url` must be specified.
//
// If the webhook is running within the cluster, then you should use `service`.
public service?: ServiceReference;
// `url` gives the location of the webhook, in standard URL form (`scheme://host:port/path`). Exactly one of `url` or `service` must be specified.
//
// The `host` should not refer to a service running in the cluster; use the `service` field instead. The host might be resolved via external DNS in some apiservers (e.g., `kube-apiserver` cannot resolve in-cluster DNS as that would be a layering violation). `host` may also be an IP address.
//
// Please note that using `localhost` or `127.0.0.1` as a `host` is risky unless you take great care to run this webhook on all hosts which run an apiserver which might need to make calls to this webhook. Such installs are likely to be non-portable, i.e., not easy to turn up in a new cluster.
//
// The scheme must be "https"; the URL must begin with "https://".
//
// A path is optional, and if present may be any string permissible in a URL. You may use the path to pass an arbitrary string to the webhook, for example, a cluster identifier.
//
// Attempting to use a user or basic auth e.g. "user:password@" is not allowed. Fragments ("#...") and query parameters ("?...") are not allowed, either.
public url?: string;
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
AppServiceCertificateOrder,
AppServiceCertificateOrdersListOptionalParams,
AppServiceCertificateOrdersListByResourceGroupOptionalParams,
AppServiceCertificateResource,
AppServiceCertificateOrdersListCertificatesOptionalParams,
AppServiceCertificateOrdersValidatePurchaseInformationOptionalParams,
AppServiceCertificateOrdersGetOptionalParams,
AppServiceCertificateOrdersGetResponse,
AppServiceCertificateOrdersCreateOrUpdateOptionalParams,
AppServiceCertificateOrdersCreateOrUpdateResponse,
AppServiceCertificateOrdersDeleteOptionalParams,
AppServiceCertificateOrderPatchResource,
AppServiceCertificateOrdersUpdateOptionalParams,
AppServiceCertificateOrdersUpdateResponse,
AppServiceCertificateOrdersGetCertificateOptionalParams,
AppServiceCertificateOrdersGetCertificateResponse,
AppServiceCertificateOrdersCreateOrUpdateCertificateOptionalParams,
AppServiceCertificateOrdersCreateOrUpdateCertificateResponse,
AppServiceCertificateOrdersDeleteCertificateOptionalParams,
AppServiceCertificatePatchResource,
AppServiceCertificateOrdersUpdateCertificateOptionalParams,
AppServiceCertificateOrdersUpdateCertificateResponse,
ReissueCertificateOrderRequest,
AppServiceCertificateOrdersReissueOptionalParams,
RenewCertificateOrderRequest,
AppServiceCertificateOrdersRenewOptionalParams,
AppServiceCertificateOrdersResendEmailOptionalParams,
NameIdentifier,
AppServiceCertificateOrdersResendRequestEmailsOptionalParams,
SiteSealRequest,
AppServiceCertificateOrdersRetrieveSiteSealOptionalParams,
AppServiceCertificateOrdersRetrieveSiteSealResponse,
AppServiceCertificateOrdersVerifyDomainOwnershipOptionalParams,
AppServiceCertificateOrdersRetrieveCertificateActionsOptionalParams,
AppServiceCertificateOrdersRetrieveCertificateActionsResponse,
AppServiceCertificateOrdersRetrieveCertificateEmailHistoryOptionalParams,
AppServiceCertificateOrdersRetrieveCertificateEmailHistoryResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a AppServiceCertificateOrders. */
export interface AppServiceCertificateOrders {
/**
* Description for List all certificate orders in a subscription.
* @param options The options parameters.
*/
list(
options?: AppServiceCertificateOrdersListOptionalParams
): PagedAsyncIterableIterator<AppServiceCertificateOrder>;
/**
* Description for Get certificate orders in a resource group.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param options The options parameters.
*/
listByResourceGroup(
resourceGroupName: string,
options?: AppServiceCertificateOrdersListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<AppServiceCertificateOrder>;
/**
* Description for List all certificates associated with a certificate order.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param options The options parameters.
*/
listCertificates(
resourceGroupName: string,
certificateOrderName: string,
options?: AppServiceCertificateOrdersListCertificatesOptionalParams
): PagedAsyncIterableIterator<AppServiceCertificateResource>;
/**
* Description for Validate information for a certificate order.
* @param appServiceCertificateOrder Information for a certificate order.
* @param options The options parameters.
*/
validatePurchaseInformation(
appServiceCertificateOrder: AppServiceCertificateOrder,
options?: AppServiceCertificateOrdersValidatePurchaseInformationOptionalParams
): Promise<void>;
/**
* Description for Get a certificate order.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order..
* @param options The options parameters.
*/
get(
resourceGroupName: string,
certificateOrderName: string,
options?: AppServiceCertificateOrdersGetOptionalParams
): Promise<AppServiceCertificateOrdersGetResponse>;
/**
* Description for Create or update a certificate purchase order.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param certificateDistinguishedName Distinguished name to use for the certificate order.
* @param options The options parameters.
*/
beginCreateOrUpdate(
resourceGroupName: string,
certificateOrderName: string,
certificateDistinguishedName: AppServiceCertificateOrder,
options?: AppServiceCertificateOrdersCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<AppServiceCertificateOrdersCreateOrUpdateResponse>,
AppServiceCertificateOrdersCreateOrUpdateResponse
>
>;
/**
* Description for Create or update a certificate purchase order.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param certificateDistinguishedName Distinguished name to use for the certificate order.
* @param options The options parameters.
*/
beginCreateOrUpdateAndWait(
resourceGroupName: string,
certificateOrderName: string,
certificateDistinguishedName: AppServiceCertificateOrder,
options?: AppServiceCertificateOrdersCreateOrUpdateOptionalParams
): Promise<AppServiceCertificateOrdersCreateOrUpdateResponse>;
/**
* Description for Delete an existing certificate order.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
certificateOrderName: string,
options?: AppServiceCertificateOrdersDeleteOptionalParams
): Promise<void>;
/**
* Description for Create or update a certificate purchase order.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param certificateDistinguishedName Distinguished name to use for the certificate order.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
certificateOrderName: string,
certificateDistinguishedName: AppServiceCertificateOrderPatchResource,
options?: AppServiceCertificateOrdersUpdateOptionalParams
): Promise<AppServiceCertificateOrdersUpdateResponse>;
/**
* Description for Get the certificate associated with a certificate order.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param name Name of the certificate.
* @param options The options parameters.
*/
getCertificate(
resourceGroupName: string,
certificateOrderName: string,
name: string,
options?: AppServiceCertificateOrdersGetCertificateOptionalParams
): Promise<AppServiceCertificateOrdersGetCertificateResponse>;
/**
* Description for Creates or updates a certificate and associates with key vault secret.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param name Name of the certificate.
* @param keyVaultCertificate Key vault certificate resource Id.
* @param options The options parameters.
*/
beginCreateOrUpdateCertificate(
resourceGroupName: string,
certificateOrderName: string,
name: string,
keyVaultCertificate: AppServiceCertificateResource,
options?: AppServiceCertificateOrdersCreateOrUpdateCertificateOptionalParams
): Promise<
PollerLike<
PollOperationState<
AppServiceCertificateOrdersCreateOrUpdateCertificateResponse
>,
AppServiceCertificateOrdersCreateOrUpdateCertificateResponse
>
>;
/**
* Description for Creates or updates a certificate and associates with key vault secret.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param name Name of the certificate.
* @param keyVaultCertificate Key vault certificate resource Id.
* @param options The options parameters.
*/
beginCreateOrUpdateCertificateAndWait(
resourceGroupName: string,
certificateOrderName: string,
name: string,
keyVaultCertificate: AppServiceCertificateResource,
options?: AppServiceCertificateOrdersCreateOrUpdateCertificateOptionalParams
): Promise<AppServiceCertificateOrdersCreateOrUpdateCertificateResponse>;
/**
* Description for Delete the certificate associated with a certificate order.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param name Name of the certificate.
* @param options The options parameters.
*/
deleteCertificate(
resourceGroupName: string,
certificateOrderName: string,
name: string,
options?: AppServiceCertificateOrdersDeleteCertificateOptionalParams
): Promise<void>;
/**
* Description for Creates or updates a certificate and associates with key vault secret.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param name Name of the certificate.
* @param keyVaultCertificate Key vault certificate resource Id.
* @param options The options parameters.
*/
updateCertificate(
resourceGroupName: string,
certificateOrderName: string,
name: string,
keyVaultCertificate: AppServiceCertificatePatchResource,
options?: AppServiceCertificateOrdersUpdateCertificateOptionalParams
): Promise<AppServiceCertificateOrdersUpdateCertificateResponse>;
/**
* Description for Reissue an existing certificate order.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param reissueCertificateOrderRequest Parameters for the reissue.
* @param options The options parameters.
*/
reissue(
resourceGroupName: string,
certificateOrderName: string,
reissueCertificateOrderRequest: ReissueCertificateOrderRequest,
options?: AppServiceCertificateOrdersReissueOptionalParams
): Promise<void>;
/**
* Description for Renew an existing certificate order.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param renewCertificateOrderRequest Renew parameters
* @param options The options parameters.
*/
renew(
resourceGroupName: string,
certificateOrderName: string,
renewCertificateOrderRequest: RenewCertificateOrderRequest,
options?: AppServiceCertificateOrdersRenewOptionalParams
): Promise<void>;
/**
* Description for Resend certificate email.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param options The options parameters.
*/
resendEmail(
resourceGroupName: string,
certificateOrderName: string,
options?: AppServiceCertificateOrdersResendEmailOptionalParams
): Promise<void>;
/**
* Description for Verify domain ownership for this certificate order.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param nameIdentifier Email address
* @param options The options parameters.
*/
resendRequestEmails(
resourceGroupName: string,
certificateOrderName: string,
nameIdentifier: NameIdentifier,
options?: AppServiceCertificateOrdersResendRequestEmailsOptionalParams
): Promise<void>;
/**
* Description for Verify domain ownership for this certificate order.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param siteSealRequest Site seal request.
* @param options The options parameters.
*/
retrieveSiteSeal(
resourceGroupName: string,
certificateOrderName: string,
siteSealRequest: SiteSealRequest,
options?: AppServiceCertificateOrdersRetrieveSiteSealOptionalParams
): Promise<AppServiceCertificateOrdersRetrieveSiteSealResponse>;
/**
* Description for Verify domain ownership for this certificate order.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param certificateOrderName Name of the certificate order.
* @param options The options parameters.
*/
verifyDomainOwnership(
resourceGroupName: string,
certificateOrderName: string,
options?: AppServiceCertificateOrdersVerifyDomainOwnershipOptionalParams
): Promise<void>;
/**
* Description for Retrieve the list of certificate actions.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param name Name of the certificate order.
* @param options The options parameters.
*/
retrieveCertificateActions(
resourceGroupName: string,
name: string,
options?: AppServiceCertificateOrdersRetrieveCertificateActionsOptionalParams
): Promise<AppServiceCertificateOrdersRetrieveCertificateActionsResponse>;
/**
* Description for Retrieve email history.
* @param resourceGroupName Name of the resource group to which the resource belongs.
* @param name Name of the certificate order.
* @param options The options parameters.
*/
retrieveCertificateEmailHistory(
resourceGroupName: string,
name: string,
options?: AppServiceCertificateOrdersRetrieveCertificateEmailHistoryOptionalParams
): Promise<
AppServiceCertificateOrdersRetrieveCertificateEmailHistoryResponse
>;
} | the_stack |
import { module, test } from 'qunit';
import { click, visit, findAll } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
//@ts-ignore
import { setupAnimationTest, animationsSettled } from 'ember-animated/test-support';
//@ts-ignore
import { clickTrigger } from 'ember-basic-dropdown/test-support/helpers';
//@ts-ignore
import { setupMirage } from 'ember-cli-mirage/test-support';
//@ts-ignore
import { selectChoose } from 'ember-power-select/test-support';
import { clickItem } from 'navi-reports/test-support/report-builder';
import { capitalize } from '@ember/string';
async function newReport() {
await visit('/reports/new');
await click('.report-builder-source-selector__source-button[data-source-name="Bard One"]');
await click('.report-builder-source-selector__source-button[data-source-name="Network"]');
await animationsSettled();
}
module('Acceptance | fili datasource', function (hooks) {
setupApplicationTest(hooks);
setupAnimationTest(hooks);
setupMirage(hooks);
test('verify the different time grains work as expected - fili', async function (assert) {
assert.expect(78);
await visit('/reports/13/view');
const timeGrains = ['Hour', 'Day', 'Week', 'Month', 'Quarter', 'Year'];
await click('.navi-column-config-item__trigger');
for (const grain of timeGrains) {
await selectChoose('.navi-column-config-item__parameter', grain);
const grainId = grain === 'Week' ? 'isoWeek' : grain.toLowerCase();
assert
.dom('.navi-column-config-item__name')
.hasText(`Date Time (${grain})`, 'The column config grain parameter is updated');
assert
.dom('.filter-builder__subject')
.hasText(`Date Time ${grain}`, `The filter is updated to the ${grainId} grain`);
await selectChoose('.filter-builder__operator-trigger', 'Between');
assert
.dom('.filter-builder__operator-trigger')
.hasText('Between', 'Between is the selected filter builder operator');
await clickTrigger('.filter-values--date-range-input__low-value.ember-basic-dropdown-trigger');
assert.dom('.ember-power-calendar').exists('Low value calendar opened');
await clickTrigger('.filter-values--date-range-input__high-value.ember-basic-dropdown-trigger');
assert.dom('.ember-power-calendar').exists('High value calendar opened');
await selectChoose('.filter-builder__operator-trigger', 'Current');
assert
.dom('.filter-builder__operator-trigger')
.hasText(`Current ${capitalize(grainId)}`, 'Current is the selected filter builder operator');
assert.dom('.filter-values--current-period').containsText(`The current ${grainId}`, `Shows current ${grainId}`);
await selectChoose('.filter-builder__operator-trigger', 'In The Past');
assert
.dom('.filter-builder__operator-trigger')
.hasText('In The Past', 'In The Past is the selected filter builder operator');
await clickTrigger('.filter-values--lookback-input .ember-basic-dropdown-trigger');
assert.dom('.filter-values--lookback-dropdown').exists('Preset dropdown opened');
await selectChoose('.filter-builder__operator-trigger', 'Since');
assert.dom('.filter-builder__operator-trigger').hasText('Since', 'Since is the selected filter builder operator');
await clickTrigger('.filter-values--date-input__trigger.ember-basic-dropdown-trigger');
assert.dom('.ember-power-calendar').exists('Calendar opened');
await selectChoose('.filter-builder__operator-trigger', 'Before');
assert
.dom('.filter-builder__operator-trigger')
.hasText('Before', 'Before is the selected filter builder operator');
await clickTrigger('.filter-values--date-input__trigger.ember-basic-dropdown-trigger');
assert.dom('.ember-power-calendar').exists('Calendar opened');
}
});
test('Fili Required filters on new report', async function (assert) {
assert.expect(5);
await newReport();
assert.dom('.report-builder-sidebar__source').hasText('Network', 'A fili table is selected');
assert.dom('.filter-builder__subject').hasText('Date Time Day', 'A date time filter exists on a new report');
assert.dom('.filter-collection__remove').isDisabled('The date time filter cannot be removed');
await clickItem('timeDimension', 'Date Time');
assert.dom('.navi-column-config-item__name').hasText('Date Time (Day)', 'The date time column was added');
assert
.dom('.navi-column-config-item__remove-icon')
.isNotDisabled('The date time can be removed when there is an all grain');
});
test('Fili Required filters when changing table', async function (assert) {
assert.expect(2);
await newReport();
await click('.report-builder-sidebar__breadcrumb-item[data-level="1"]');
await click('.report-builder-source-selector__source-button[data-source-name="Table A"]');
await animationsSettled();
assert.dom('.filter-builder__subject').hasText('Date Time Day', 'A date time filter exists after switching tables');
assert.dom('.filter-collection__remove').isDisabled('The date time filter cannot be removed');
});
test('Fili Required filters when changing table without all grain', async function (assert) {
assert.expect(4);
await newReport();
await click('.report-builder-sidebar__breadcrumb-item[data-level="1"]');
await click('.report-builder-source-selector__source-button[data-source-name="Table C"]');
await animationsSettled();
assert.dom('.filter-builder__subject').hasText('Date Time Day', 'A date time filter exists after switching tables');
assert.dom('.filter-collection__remove').isDisabled('The date time filter cannot be removed');
assert
.dom('.navi-column-config-item__name')
.hasText('Date Time (Day)', 'A date time column exists after switching to a table with no all grain');
assert.dom('.navi-column-config-item__remove-icon').isDisabled('The date time column cannot be removed');
});
test('Fili supports since and before operators', async function (assert) {
assert.expect(2);
await newReport();
await clickItem('dimension', 'Date Time');
await selectChoose('.navi-column-config-item__parameter', 'Year');
await selectChoose('.filter-builder__operator-trigger', 'Before');
await click('.navi-report__run-btn');
assert.dom('.table-row').hasText('2013', 'Results are fetched for Before operator');
await selectChoose('.filter-builder__operator-trigger', 'Since');
await click('.dropdown-date-picker__trigger');
await click('.ember-power-calendar-selector-nav-control--previous');
await click('[data-date="2015"]');
await click('.navi-report__run-btn');
assert.dom('.table-row').hasText('2015', 'Results are fetched for Since operator');
});
test('Fili Dimension sorting disabled', async function (assert) {
assert.expect(7);
await newReport();
await clickItem('dimension', 'Date Time');
assert
.dom('.navi-column-config-base__sort-icon')
.doesNotHaveAttribute('disabled', 'A timeDimension column can be sorted');
await click('.navi-column-config-base__sort-icon');
assert
.dom('.navi-column-config-base__sort-icon')
.hasClass('navi-column-config-base__sort-icon--active', 'The timeDimension sort icon becomes active');
await clickItem('dimension', 'Age');
assert
.dom('.navi-column-config-base__sort-icon')
.hasAttribute('disabled', '', 'A dimension column cannot be sorted');
assert
.dom('.navi-column-config-base__sort-icon')
.hasAttribute('title', 'This column cannot be sorted', 'A dimension column cannot be sorted');
await click('.navi-column-config-base__sort-icon');
assert
.dom('.navi-column-config-base__sort-icon')
.doesNotHaveClass('navi-column-config-base__sort-icon--active', 'The dimension sort icon does not become active');
await clickItem('metric', 'Revenue');
assert.dom('.navi-column-config-base__sort-icon').doesNotHaveAttribute('disabled', 'A metric column can be sorted');
await click('.navi-column-config-base__sort-icon');
assert
.dom('.navi-column-config-base__sort-icon')
.hasClass('navi-column-config-base__sort-icon--active', 'The metric sort icon becomes active');
});
test('Fili Remove time column (all grain)', async function (assert) {
assert.expect(4);
await visit('/reports/1/edit');
// select month grain
await click('.navi-column-config-item__trigger');
await selectChoose('.navi-column-config-item__parameter', 'Month');
await clickTrigger('.filter-values--date-range-input__low-value');
await click('.ember-power-calendar-selector-month[data-date="2015-01"]');
await clickTrigger('.filter-values--date-range-input__high-value');
await click('.ember-power-calendar-selector-month[data-date="2015-05"]');
assert
.dom('.filter-values--date-range-input__low-value input')
.hasValue('Jan 2015', 'The start date is month Jan 2015');
assert
.dom('.filter-values--date-range-input__high-value input')
.hasValue('May 2015', 'The end date is month May 2015');
assert
.dom('.filter-values--date-range-input__low-value input')
.hasValue('Jan 2015', 'The start date is not changed');
assert
.dom('.filter-values--date-range-input__high-value input')
.hasValue('May 2015', 'The end date is not changed');
});
test('Fili filter grain updates column grain', async function (assert) {
assert.expect(6);
await visit('reports/1/edit');
assert.deepEqual(
findAll('.navi-column-config-item__name').map((el) => el.textContent?.trim()),
['Date Time (Day)', 'Property (id)', 'Ad Clicks', 'Nav Link Clicks'],
'All columns exist as expected'
);
await selectChoose('.dropdown-parameter-picker', 'Year');
assert
.dom('.filter-builder__subject')
.hasText('Date Time Year', 'Date time matches existing filter grain on the report');
assert.deepEqual(
findAll('.navi-column-config-item__name').map((el) => el.textContent?.trim()),
['Date Time (Year)', 'Property (id)', 'Ad Clicks', 'Nav Link Clicks'],
'Date Time column is updated to match filter grain of year'
);
await click('.navi-column-config-item__remove-icon'); // Remove Date Time (Day)
assert.deepEqual(
findAll('.navi-column-config-item__name').map((el) => el.textContent?.trim()),
['Property (id)', 'Ad Clicks', 'Nav Link Clicks'],
'Date Time is removed'
);
await selectChoose('.dropdown-parameter-picker', 'Week');
assert
.dom('.filter-builder__subject')
.hasText('Date Time Week', 'Date time matches existing filter grain on the report');
await clickItem('dimension', 'Date Time');
assert.deepEqual(
findAll('.navi-column-config-item__name').map((el) => el.textContent?.trim()),
['Date Time (Week)', 'Property (id)', 'Ad Clicks', 'Nav Link Clicks'],
'A Date Time column is added matching the existing filter grain'
);
});
test('Fili filter parameter updates', async function (assert) {
assert.expect(2);
await visit('/reports/2/edit');
assert.dom(findAll('.filter-builder__values')[1]).hasText('× 114 × 100001', 'The values are populated');
await selectChoose('[data-filter-subject="Property (id)"][data-filter-param="field"]', 'desc');
assert
.dom(findAll('.filter-builder__values')[1])
.hasText('', 'The values are cleared after switching dimension fields');
});
test('Fili request v1 to v2 date dimensions', async function (assert) {
assert.expect(3);
await visit('/reports/7/view');
assert.deepEqual(
findAll('.filter-builder__subject').map((el) => el.textContent?.trim().replace(/\s+/g, ' ')),
['Date Time Day', 'User Signup Date id second', 'User Signup Date id second', 'User Signup Date id second'],
'Date dimension filters are correctly migrated'
);
assert.deepEqual(
findAll('.filter-builder__values').map((el) =>
Array.from(el.querySelectorAll('input')).map((el) => el.value.trim())
),
[
['Feb 09, 2018', 'Feb 15, 2018'],
// date dimension values
['Oct 02, 2021'],
['Oct 09, 2021'],
['Sep 04, 2021', 'Sep 08, 2021'],
],
'Date dimension filter values are correctly migrated'
);
assert.deepEqual(
findAll('.navi-column-config-item__name').map((el) => el.textContent?.trim()),
['Date Time (Day)', 'User Signup Date (id,second)', 'Revenue (USD)'],
'Date dimension columns shows up correctly with fields and grains'
);
});
test('Fili date time column and filter are preserved when switching tables', async function (assert) {
assert.expect(11);
await visit('reports/1/edit');
assert.deepEqual(
findAll('.navi-column-config-item__name').map((el) => el.textContent?.trim()),
['Date Time (Day)', 'Property (id)', 'Ad Clicks', 'Nav Link Clicks'],
'All columns exist as expected'
);
await selectChoose('.dropdown-parameter-picker', 'Hour');
assert
.dom('.filter-builder__subject')
.hasText('Date Time Hour', 'Date time matches existing filter grain on the report');
assert
.dom('.navi-column-config-item__name')
.hasText('Date Time (Hour)', 'Date Time column is updated to match filter grain of hour');
assert.dom('.filter-values--date-range-input__low-value input').hasValue('Nov 09, 2015', 'Start Date is correct');
assert.dom('.filter-values--date-range-input__high-value input').hasValue('Nov 15, 2015', 'End Date is correct');
// Switch to Table A which also supports hour grain
await click('.report-builder-sidebar__breadcrumb-item[data-level="1"]');
await click('.report-builder-source-selector__source-button[data-source-name="Table A"]');
assert
.dom('.navi-column-config-item__name')
.hasText('Date Time (Hour)', 'Date Time column is updated to match filter grain of hour');
assert.dom('.filter-values--date-range-input__low-value input').hasValue('Nov 09, 2015', 'Start Date is correct');
assert.dom('.filter-values--date-range-input__high-value input').hasValue('Nov 15, 2015', 'End Date is correct');
// Switch to Table B which doesn't support hour grain
await click('.report-builder-sidebar__breadcrumb-item[data-level="1"]');
await click('.report-builder-source-selector__source-button[data-source-name="Table B"]');
assert
.dom('.navi-column-config-item__name')
.hasText('Date Time (Day)', 'Date Time column is updated to match filter grain of day');
assert.dom('.filter-values--date-range-input__low-value input').hasValue('Nov 09, 2015', 'Start Date is correct');
assert.dom('.filter-values--date-range-input__high-value input').hasValue('Nov 15, 2015', 'End Date is correct');
});
}); | the_stack |
import * as Leaflet from 'leaflet';
import * as React from 'react';
// All events need to be lowercase so they don't collide with React.DOMAttributes<T>
// which already declares things with some of the same names
export type Children = React.ReactNode | React.ReactNode[];
export interface MapEvents {
onclick?(event: Leaflet.LeafletMouseEvent): void;
ondblclick?(event: Leaflet.LeafletMouseEvent): void;
onmousedown?(event: Leaflet.LeafletMouseEvent): void;
onmouseup?(event: Leaflet.LeafletMouseEvent): void;
onmouseover?(event: Leaflet.LeafletMouseEvent): void;
onmouseout?(event: Leaflet.LeafletMouseEvent): void;
onmousemove?(event: Leaflet.LeafletMouseEvent): void;
oncontextmenu?(event: Leaflet.LeafletMouseEvent): void;
onfocus?(event: Leaflet.LeafletEvent): void;
onblur?(event: Leaflet.LeafletEvent): void;
onpreclick?(event: Leaflet.LeafletMouseEvent): void;
onload?(event: Leaflet.LeafletEvent): void;
onunload?(event: Leaflet.LeafletEvent): void;
onviewreset?(event: Leaflet.LeafletEvent): void;
onmove?(event: Leaflet.LeafletEvent): void;
onmovestart?(event: Leaflet.LeafletEvent): void;
onmoveend?(event: Leaflet.LeafletEvent): void;
ondragstart?(event: Leaflet.LeafletEvent): void;
ondrag?(event: Leaflet.LeafletEvent): void;
ondragend?(event: Leaflet.DragEndEvent): void;
onzoomstart?(event: Leaflet.LeafletEvent): void;
onzoom?(event: Leaflet.LeafletEvent): void;
onzoomend?(event: Leaflet.LeafletEvent): void;
onzoomlevelschange?(event: Leaflet.LeafletEvent): void;
onresize?(event: Leaflet.ResizeEvent): void;
onautopanstart?(event: Leaflet.LeafletEvent): void;
onlayeradd?(event: Leaflet.LayerEvent): void;
onlayerremove?(event: Leaflet.LayerEvent): void;
onbaselayerchange?(event: Leaflet.LayersControlEvent): void;
onoverlayadd?(event: Leaflet.LayersControlEvent): void;
onoverlayremove?(event: Leaflet.LayersControlEvent): void;
onlocationfound?(event: Leaflet.LocationEvent): void;
onlocationerror?(event: Leaflet.ErrorEvent): void;
onpopupopen?(event: Leaflet.PopupEvent): void;
onpopupclose?(event: Leaflet.PopupEvent): void;
}
export interface MarkerEvents {
onclick?(event: Leaflet.LeafletMouseEvent): void;
ondblclick?(event: Leaflet.LeafletMouseEvent): void;
onmousedown?(event: Leaflet.LeafletMouseEvent): void;
onmouseover?(event: Leaflet.LeafletMouseEvent): void;
onmouseout?(event: Leaflet.LeafletMouseEvent): void;
oncontextmenu?(event: Leaflet.LeafletMouseEvent): void;
ondragstart?(event: Leaflet.LeafletEvent): void;
ondrag?(event: Leaflet.LeafletEvent): void;
ondragend?(event: Leaflet.DragEndEvent): void;
onmove?(event: Leaflet.LeafletEvent): void;
onadd?(event: Leaflet.LeafletEvent): void;
onremove?(event: Leaflet.LeafletEvent): void;
onpopupopen?(event: Leaflet.PopupEvent): void;
onpopupclose?(event: Leaflet.PopupEvent): void;
}
export interface TileLayerEvents {
onloading?(event: Leaflet.LeafletEvent): void;
onload?(event: Leaflet.LeafletEvent): void;
ontileloadstart?(event: Leaflet.TileEvent): void;
ontileload?(event: Leaflet.TileEvent): void;
ontileunload?(event: Leaflet.TileEvent): void;
ontileerror?(event: Leaflet.TileEvent): void;
}
export interface PathEvents {
onclick?(event: Leaflet.LeafletMouseEvent): void;
ondblclick?(event: Leaflet.LeafletMouseEvent): void;
onmousedown?(event: Leaflet.LeafletMouseEvent): void;
onmouseover?(event: Leaflet.LeafletMouseEvent): void;
onmouseout?(event: Leaflet.LeafletMouseEvent): void;
oncontextmenu?(event: Leaflet.LeafletMouseEvent): void;
onadd?(event: Leaflet.LeafletEvent): void;
onremove?(event: Leaflet.LeafletEvent): void;
onpopupopen?(event: Leaflet.PopupEvent): void;
onpopupclose?(event: Leaflet.PopupEvent): void;
}
export interface FeatureGroupEvents {
onclick?(event: Leaflet.LeafletMouseEvent): void;
ondblclick?(event: Leaflet.LeafletMouseEvent): void;
onmouseover?(event: Leaflet.LeafletMouseEvent): void;
onmouseout?(event: Leaflet.LeafletMouseEvent): void;
oncontextmenu?(event: Leaflet.LeafletMouseEvent): void;
onlayeradd?(event: Leaflet.LayerEvent): void;
onlayerremove?(event: Leaflet.LayerEvent): void;
}
export interface LayersControlEvents {
onbaselayerchange?(event: Leaflet.LayersControlEvent): void;
onoverlayadd?(event: Leaflet.LayersControlEvent): void;
onoverlayremove?(event: Leaflet.LayersControlEvent): void;
}
export type LeafletEvents = MapEvents
& MarkerEvents
& TileLayerEvents
& PathEvents
& FeatureGroupEvents
& LayersControlEvents;
// Most react-leaflet components take two type parameters:
// - P : the component's props object
// - E : the corresponding Leaflet element
// These type parameters aren't needed for instantiating a component, but they are useful for
// extending react-leaflet classes.
export interface MapComponentProps {
leaflet?: LeafletContext | undefined;
pane?: string | undefined;
}
export class MapEvented<P, E extends Leaflet.Evented> extends React.Component<P> {
_leafletEvents: LeafletEvents;
leafletElement: E;
extractLeafletEvents(props: P): LeafletEvents;
bindLeafletEvents(next: LeafletEvents, prev: LeafletEvents): LeafletEvents;
fireLeafletEvent(type: string, data: any): void;
}
export class MapComponent<P extends MapComponentProps, E extends Leaflet.Evented> extends MapEvented<P, E> {
getOptions(props: P): P;
}
export interface MapProps extends MapEvents, Leaflet.MapOptions, Leaflet.LocateOptions, Leaflet.FitBoundsOptions {
animate?: boolean | undefined;
duration?: number | undefined;
noMoveStart?: boolean | undefined;
bounds?: Leaflet.LatLngBoundsExpression | undefined;
boundsOptions?: Leaflet.FitBoundsOptions | undefined;
children: Children;
className?: string | undefined;
id?: string | undefined;
style?: React.CSSProperties | undefined;
useFlyTo?: boolean | undefined;
viewport?: Viewport | undefined;
whenReady?: (() => void) | undefined;
onViewportChange?: ((viewport: Viewport) => void) | undefined;
onViewportChanged?: ((viewport: Viewport) => void) | undefined;
}
export class Map<P extends MapProps = MapProps, E extends Leaflet.Map = Leaflet.Map> extends MapEvented<P, E> {
className: string | null | undefined;
contextValue: LeafletContext | null | undefined;
container: HTMLDivElement | null | undefined;
viewport: Viewport;
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
onViewportChange: () => void;
onViewportChanged: () => void;
bindContainer(container: HTMLDivElement | null | undefined): void;
shouldUpdateCenter(next: Leaflet.LatLngExpression, prev: Leaflet.LatLngExpression): boolean;
shouldUpdateBounds(next: Leaflet.LatLngBoundsExpression, prev: Leaflet.LatLngBoundsExpression): boolean;
}
export interface DivOverlayProps extends MapComponentProps, Leaflet.DivOverlayOptions {
children: Children;
onClose?: (() => void) | undefined;
onOpen?: (() => void) | undefined;
}
export interface DivOverlayTypes extends Leaflet.Evented {
isOpen: () => boolean;
update: () => void;
}
export class DivOverlay<P extends DivOverlayProps, E extends DivOverlayTypes> extends MapComponent<P, E> {
createLeafletElement(_props: P): void;
updateLeafletElement(_prevProps: P, _props: P): void;
onClose: () => void;
onOpen: () => void;
onRender: () => void;
}
export interface PaneProps {
children?: Children | undefined;
className?: string | undefined;
leaflet?: LeafletContext | undefined;
name?: string | undefined;
style?: React.CSSProperties | undefined;
pane?: string | undefined;
}
export interface PaneState {
name: string | null | undefined;
context: LeafletContext | null | undefined;
}
export class Pane<P extends PaneProps = PaneProps, S extends PaneState = PaneState> extends React.Component<P, S> {
createPane(props: P): void;
removePane(): void;
setStyle(arg: { style?: string | undefined, className?: string | undefined }): void;
getParentPane(): HTMLElement | null | undefined;
getPane(name: string | null | undefined): HTMLElement | null | undefined;
}
export interface MapLayerProps extends MapComponentProps {
attribution?: string | undefined;
children?: Children | undefined;
}
export type AddLayerHandler = (layer: Leaflet.Layer, name: string, checked?: boolean) => void;
export type RemoveLayerHandler = (layer: Leaflet.Layer) => void;
export interface LayerContainer {
addLayer: AddLayerHandler;
removeLayer: RemoveLayerHandler;
}
export interface LeafletContext {
map?: Leaflet.Map | undefined;
pane?: string | undefined;
layerContainer?: LayerContainer | undefined;
popupContainer?: Leaflet.Layer | undefined;
}
export type LatLng = Leaflet.LatLng | number[] | object;
export type LatLngBounds = Leaflet.LatLngBounds | LatLng[];
export type Point = [number, number] | Leaflet.Point;
export interface Viewport {
center: [number, number] | null | undefined;
zoom: number | null | undefined;
}
export class MapLayer<P extends MapLayerProps = MapLayerProps, E extends Leaflet.Layer = Leaflet.Layer> extends MapComponent<P, E> {
contextValue: LeafletContext | null | undefined;
leafletElement: E;
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
readonly layerContainer: LayerContainer | Leaflet.Map;
}
export interface GridLayerProps extends MapLayerProps, Leaflet.GridLayerOptions { }
export class GridLayer<P extends GridLayerProps = GridLayerProps, E extends Leaflet.GridLayer = Leaflet.GridLayer> extends MapLayer<P, E> {
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
getOptions(props: P): P;
}
export interface TileLayerProps extends GridLayerProps, TileLayerEvents, Leaflet.TileLayerOptions {
url: string;
}
export class TileLayer<P extends TileLayerProps = TileLayerProps, E extends Leaflet.TileLayer = Leaflet.TileLayer> extends GridLayer<P, E> {
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
}
export interface WMSTileLayerProps extends TileLayerEvents, Leaflet.WMSOptions, GridLayerProps {
children?: Children | undefined;
url: string;
}
export class WMSTileLayer<P extends WMSTileLayerProps = WMSTileLayerProps, E extends Leaflet.TileLayer.WMS = Leaflet.TileLayer.WMS> extends GridLayer<P, E> {
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
getOptions(params: P): P;
}
export interface ImageOverlayProps extends MapLayerProps, Leaflet.ImageOverlayOptions {
bounds?: Leaflet.LatLngBoundsExpression | undefined;
url: string | HTMLImageElement;
zIndex?: number | undefined;
}
export class ImageOverlay<P extends ImageOverlayProps = ImageOverlayProps, E extends Leaflet.ImageOverlay = Leaflet.ImageOverlay> extends MapLayer<P, E> {
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
}
export interface SVGOverlayProps extends Leaflet.ImageOverlayOptions, MapComponentProps {
children?: Children | undefined;
preserveAspectRatio?: string | undefined;
viewBox?: string | undefined;
}
export class SVGOverlay<P extends SVGOverlayProps = SVGOverlayProps, E extends Leaflet.SVGOverlay = Leaflet.SVGOverlay> extends MapComponent<P, E> {
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
}
export interface VideoOverlayProps extends Leaflet.VideoOverlayOptions, MapComponentProps {
attribution?: string | undefined;
bounds: Leaflet.LatLngBoundsExpression;
opacity?: number | undefined;
play?: boolean | undefined;
url: string | string[] | HTMLVideoElement;
zIndex?: number | undefined;
}
export class VideoOverlay<P extends VideoOverlayProps = VideoOverlayProps, E extends Leaflet.VideoOverlay = Leaflet.VideoOverlay> extends MapLayer<P, E> {
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
}
export class LayerGroup<P extends MapLayerProps = MapLayerProps, E extends Leaflet.LayerGroup = Leaflet.LayerGroup> extends MapLayer<P, E> {
createLeafletElement(props: P): E;
}
export interface MarkerProps extends MapLayerProps, MarkerEvents, Leaflet.MarkerOptions {
position: Leaflet.LatLngExpression;
}
export class Marker<P extends MarkerProps = MarkerProps, E extends Leaflet.Marker = Leaflet.Marker> extends MapLayer<P, E> {
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
}
export interface PathProps extends PathEvents, Leaflet.PathOptions, MapLayerProps { }
export abstract class Path<P extends PathProps, E extends Leaflet.Path> extends MapLayer<P, E> {
getChildContext(): { popupContainer: E };
getPathOptions(props: P): Leaflet.PathOptions;
setStyle(options: Leaflet.PathOptions): void;
setStyleIfChanged(fromProps: P, toProps: P): void;
}
export interface CircleProps extends MapLayerProps, PathEvents, Leaflet.CircleMarkerOptions {
center: Leaflet.LatLngExpression;
radius: number;
}
export class Circle<P extends CircleProps = CircleProps, E extends Leaflet.Circle = Leaflet.Circle> extends Path<P, E> {
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
}
export interface CircleMarkerProps extends PathProps, PathEvents, Leaflet.CircleMarkerOptions {
center: Leaflet.LatLngExpression;
radius: number;
}
export class CircleMarker<P extends CircleMarkerProps = CircleMarkerProps, E extends Leaflet.CircleMarker = Leaflet.CircleMarker> extends Path<P, E> {
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
}
export interface FeatureGroupProps extends MapLayerProps, FeatureGroupEvents, Leaflet.PathOptions { }
export class FeatureGroup<P extends FeatureGroupProps = FeatureGroupProps, E extends Leaflet.FeatureGroup = Leaflet.FeatureGroup> extends LayerGroup<P, E> {
createLeafletElement(props: P): E;
}
export interface GeoJSONProps extends PathProps, FeatureGroupEvents, Leaflet.GeoJSONOptions {
data: GeoJSON.GeoJsonObject | GeoJSON.GeoJsonObject[];
markersInheritOptions?: boolean | undefined;
}
export class GeoJSON<P extends GeoJSONProps = GeoJSONProps, E extends Leaflet.GeoJSON = Leaflet.GeoJSON> extends FeatureGroup<P, E> {
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
}
export interface PolylineProps extends PathProps, PathEvents, Leaflet.PolylineOptions {
positions: Leaflet.LatLngExpression[] | Leaflet.LatLngExpression[][];
}
export class Polyline<P extends PolylineProps = PolylineProps, E extends Leaflet.Polyline = Leaflet.Polyline> extends Path<P, E> {
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
}
export interface PolygonProps extends PathProps, PathEvents, Leaflet.PolylineOptions {
positions: Leaflet.LatLngExpression[] | Leaflet.LatLngExpression[][] | Leaflet.LatLngExpression[][][];
}
export class Polygon<P extends PolygonProps = PolygonProps, E extends Leaflet.Polygon = Leaflet.Polygon> extends Path<P, E> {
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
}
export interface RectangleProps extends PathProps, PathEvents, Leaflet.PolylineOptions {
bounds: Leaflet.LatLngBoundsExpression;
}
export class Rectangle<P extends RectangleProps = RectangleProps, E extends Leaflet.Rectangle = Leaflet.Rectangle> extends Path<P, E> {
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
}
export interface PopupProps extends Leaflet.PopupOptions, DivOverlayProps {
position?: Leaflet.LatLngExpression | undefined;
}
export class Popup<P extends PopupProps = PopupProps, E extends Leaflet.Popup = Leaflet.Popup> extends DivOverlay<P, E> {
getOptions(props: P): P;
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
onPopupOpen(arg: { popup: E }): void;
onPopupClose(arg: { popup: E }): void;
onRender: () => void;
}
export interface TooltipProps extends Leaflet.TooltipOptions, DivOverlayProps { }
export class Tooltip<P extends TooltipProps = TooltipProps, E extends Leaflet.Tooltip = Leaflet.Tooltip> extends DivOverlay<P, E> {
onTooltipOpen(arg: { tooltip: E }): void;
onTooltipClose(arg: { tooltip: E }): void;
}
export type MapControlProps = {
leaflet?: LeafletContext | undefined
} & Leaflet.ControlOptions;
export class MapControl<P extends MapControlProps = MapControlProps, E extends Leaflet.Control = Leaflet.Control> extends React.Component<P> {
leafletElement: E;
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
}
export type AttributionControlProps = Leaflet.Control.AttributionOptions & MapControlProps;
export class AttributionControl<P extends AttributionControlProps = AttributionControlProps, E extends Leaflet.Control.Attribution = Leaflet.Control.Attribution> extends MapControl<P, E> {
createLeafletElement(props: P): E;
}
export interface LayersControlProps extends MapControlProps, LayersControlEvents, Leaflet.Control.LayersOptions {
children: Children;
collapsed?: boolean | undefined;
}
export class LayersControl<P extends LayersControlProps = LayersControlProps, E extends Leaflet.Control.Layers = Leaflet.Control.Layers> extends MapControl<P, E> {
controlProps: {
addBaseLayer: AddLayerHandler,
addOverlay: AddLayerHandler,
removeLayer: RemoveLayerHandler,
removeLayerControl: RemoveLayerHandler
};
createLeafletElement(props: P): E;
updateLeafletElement(fromProps: P, toProps: P): void;
addBaseLayer(layer: Leaflet.Layer, name: string, checked: boolean): void;
addOverlay(layer: Leaflet.Layer, name: string, checked: boolean): void;
removeLayer(layer: Leaflet.Layer): void;
removeLayerControl(layer: Leaflet.Layer): void;
}
export namespace LayersControl {
interface ControlledLayerProps {
addBaseLayer?: AddLayerHandler | undefined;
addOverlay?: AddLayerHandler | undefined;
checked?: boolean | undefined;
children: Children;
leaflet?: LeafletContext | undefined;
name: string;
removeLayer?: RemoveLayerHandler | undefined;
removeLayerControl?: RemoveLayerHandler | undefined;
}
class ControlledLayer<P extends ControlledLayerProps = ControlledLayerProps> extends React.Component<P> {
contextValue: LeafletContext;
layer: Leaflet.Layer | null | undefined;
removeLayer(layer: Leaflet.Layer): void;
}
class BaseLayer<P extends ControlledLayerProps = ControlledLayerProps> extends ControlledLayer<P> {
constructor(props: ControlledLayerProps);
addLayer: (layer: Leaflet.Layer) => void;
}
class Overlay<P extends ControlledLayerProps = ControlledLayerProps> extends ControlledLayer<P> {
constructor(props: ControlledLayerProps);
addLayer: (layer: Leaflet.Layer) => void;
}
}
export type ScaleControlProps = Leaflet.Control.ScaleOptions & MapControlProps;
export class ScaleControl<P extends ScaleControlProps = ScaleControlProps, E extends Leaflet.Control.Scale = Leaflet.Control.Scale> extends MapControl<P, E> {
createLeafletElement(props: P): E;
}
export type ZoomControlProps = Leaflet.Control.ZoomOptions & MapControlProps;
export class ZoomControl<P extends ZoomControlProps = ZoomControlProps, E extends Leaflet.Control.Zoom = Leaflet.Control.Zoom> extends MapControl<P, E> {
createLeafletElement(props: P): E;
}
// context.js
export const LeafletProvider: React.Provider<LeafletContext>;
export const LeafletConsumer: React.Consumer<LeafletContext>;
export interface ContextProps {
leaflet?: LeafletContext | undefined;
}
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export function withLeaflet<T extends ContextProps>(WrappedComponent: React.ComponentType<T>): React.ComponentType<Omit<T, 'leaflet'>>;
export function useLeaflet(): LeafletContext; | the_stack |
/*global TurbulenzBridge*/
/*global TurbulenzServices*/
//
// API
//
class LeaderboardManager
{
/* tslint:disable:no-unused-variable */
static version = 1;
/* tslint:enable:no-unused-variable */
getTypes = {
top: 'top',
near: 'near',
above: 'above',
below: 'below'
};
maxGetSize = 32;
gameSession : GameSession;
gameSessionId : string;
errorCallbackFn : ServiceErrorCB;
service : ServiceRequester;
requestHandler : RequestHandler;
ready : boolean;
meta : any;
getOverview(spec, callbackFn, errorCallbackFn)
{
var errorCallback = errorCallbackFn || this.errorCallbackFn;
if (!this.meta)
{
errorCallback("The leaderboard manager failed to initialize properly.");
return;
}
var that = this;
var getOverviewCallback =
function getOverviewCallbackFn(jsonResponse, status)
{
if (status === 200)
{
var overview = jsonResponse.data;
var overviewLength = overview.length;
for (var i = 0; i < overviewLength; i += 1)
{
var leaderboard = overview[i];
if (leaderboard.hasOwnProperty('score'))
{
that.meta[leaderboard.key].bestScore = leaderboard.score;
}
}
callbackFn(overview);
}
else
{
errorCallback("LeaderboardManager.getKeys failed with status " + status + ": " + jsonResponse.msg,
status,
that.getOverview,
[spec, callbackFn]);
}
};
var dataSpec : LeaderboardDataSpec = { };
if (spec.friendsOnly)
{
dataSpec.friendsonly = spec.friendsOnly && 1;
}
this.service.request({
url: '/api/v1/leaderboards/scores/read/' + that.gameSession.gameSlug,
method: 'GET',
data : dataSpec,
callback: getOverviewCallback,
requestHandler: this.requestHandler
}, 'leaderboard.read');
}
getAggregates(spec, callbackFn, errorCallbackFn)
{
var errorCallback = errorCallbackFn || this.errorCallbackFn;
if (!this.meta)
{
errorCallback("The leaderboard manager failed to initialize properly.");
return;
}
var that = this;
var getAggregatesCallback =
function getAggregatesCallbackFn(jsonResponse, status)
{
if (status === 200)
{
var aggregates = jsonResponse.data;
callbackFn(aggregates);
}
else
{
errorCallback("LeaderboardManager.getKeys failed with status " + status + ": " + jsonResponse.msg,
status,
that.getAggregates,
[spec, callbackFn, errorCallbackFn]);
}
};
var dataSpec = {};
this.service.request({
url: '/api/v1/leaderboards/aggregates/read/' + that.gameSession.gameSlug,
method: 'GET',
data : dataSpec,
callback: getAggregatesCallback,
requestHandler: this.requestHandler
}, 'leaderboard.aggregates');
}
getRaw(key, spec, callbackFn, errorCallbackFn): boolean
{
var that = this;
var errorCallback = errorCallbackFn || this.errorCallbackFn;
var getCallback = function getCallbackFn(jsonResponse, status)
{
if (status === 200)
{
var data = jsonResponse.data;
callbackFn(data);
}
else
{
errorCallback("LeaderboardManager.get failed with status " + status + ": " + jsonResponse.msg,
status,
that.get,
[key, spec, callbackFn]);
}
};
this.service.request({
url: '/api/v1/leaderboards/scores/read/' + that.gameSession.gameSlug + '/' + key,
method: 'GET',
data: spec,
callback: getCallback,
requestHandler: this.requestHandler
}, 'leaderboard.read');
return true;
}
get(key, spec, callbackFn, errorCallbackFn): boolean
{
var errorCallback = errorCallbackFn || this.errorCallbackFn;
if (!this.meta)
{
errorCallback("The leaderboard manager failed to initialize properly.");
return false;
}
var meta = this.meta[key];
if (!meta)
{
errorCallback("No leaderboard with the name '" + key + "' exists.");
return false;
}
var dataSpec : LeaderboardDataSpec = {};
// backwards compatibility
if (spec.numNear)
{
dataSpec.type = this.getTypes.near;
dataSpec.size = spec.numNear * 2 + 1;
}
if (spec.numTop)
{
dataSpec.type = this.getTypes.top;
dataSpec.size = spec.numTop;
}
// new arguments
if (spec.size)
{
dataSpec.size = spec.size;
}
if (!dataSpec.size)
{
// default value
dataSpec.size = 9;
}
if (dataSpec.size > this.maxGetSize)
{
throw new Error('Leaderboard get request size must be smaller than ' + this.maxGetSize);
}
if (spec.friendsOnly)
{
dataSpec.friendsonly = spec.friendsOnly && 1;
}
if (spec.type)
{
dataSpec.type = spec.type;
}
if (spec.hasOwnProperty('score'))
{
dataSpec.score = spec.score;
}
if (spec.hasOwnProperty('time'))
{
dataSpec.time = spec.time;
}
var that = this;
var callbackWrapper = function callbackWrapperFn(data)
{
var lbr = LeaderboardResult.create(that, key, dataSpec, data);
callbackFn(key, lbr);
};
return this.getRaw(key, dataSpec, callbackWrapper, errorCallbackFn);
}
set(key, score, callbackFn, errorCallbackFn)
{
var errorCallback = errorCallbackFn || this.errorCallbackFn;
if (!this.meta)
{
errorCallback("The leaderboard manager failed to initialize properly.");
return;
}
var meta = this.meta[key];
if (!meta)
{
errorCallback("No leaderboard with the name '" + key + "' exists.");
return;
}
if (typeof(score) !== 'number' || isNaN(score))
{
throw new Error("Score must be a number.");
}
if (score < 0)
{
throw new Error("Score cannot be negative.");
}
var sortBy = meta.sortBy;
var bestScore = meta.bestScore;
// Avoid making an ajax query if the new score is worse than current score
if ((bestScore && ((sortBy === 1 && score <= bestScore) || (sortBy === -1 && score >= bestScore))))
{
TurbulenzEngine.setTimeout(function () {
callbackFn(key, score, false, bestScore);
}, 0);
return;
}
var that = this;
var setCallback = function setCallbackFn(jsonResponse, status)
{
if (status === 200)
{
var data = jsonResponse.data;
var bestScore = data.bestScore || data.lastScore || null;
var newBest = data.newBest || false;
if (newBest)
{
bestScore = score;
// Assemble data for notification system.
var scoreData = {
key: key,
title: meta.title,
sortBy: meta.sortBy,
score: score,
prevBest: data.prevBest, // may be 'undefined'
gameSlug: that.gameSession.gameSlug,
};
// Trigger notification (only for new best scores).
TurbulenzBridge.updateLeaderBoard(scoreData);
}
meta.bestScore = bestScore;
callbackFn(key, score, newBest, bestScore);
}
else
{
errorCallback("LeaderboardManager.set failed with status " + status + ": " + jsonResponse.msg,
status,
that.set,
[key, score, callbackFn]);
}
};
var dataSpec = {
score: score,
gameSessionId: that.gameSessionId,
key: undefined
};
var url = '/api/v1/leaderboards/scores/set/' + key;
this.service.request({
url: url,
method: 'POST',
data : dataSpec,
callback: setCallback,
requestHandler: this.requestHandler,
encrypt: true
}, 'leaderboard.set');
}
// ONLY available on Local and Hub
reset(callbackFn, errorCallbackFn)
{
var errorCallback = errorCallbackFn || this.errorCallbackFn;
if (!this.meta)
{
errorCallback("The leaderboard manager failed to initialize properly.");
return;
}
var that = this;
var resetCallback = function resetCallbackFn(jsonResponse, status)
{
if (status === 200)
{
var meta = that.meta;
var m;
for (m in meta)
{
if (meta.hasOwnProperty(m))
{
delete meta[m].bestScore;
}
}
if (callbackFn)
{
callbackFn();
}
}
else
{
errorCallback("LeaderboardManager.reset failed with status " + status + ": " + jsonResponse.msg,
status,
that.reset,
[callbackFn]);
}
};
// for testing only (this is not available on the Gamesite)
this.service.request({
url: '/api/v1/leaderboards/scores/remove-all/' + this.gameSession.gameSlug,
method: 'POST',
callback: resetCallback,
requestHandler: this.requestHandler
}, 'leaderboard.removeall');
}
static create(requestHandler: RequestHandler,
gameSession: GameSession,
leaderboardMetaReceived?:
{ (mngr: LeaderboardManager): void; },
errorCallbackFn?: { (errMsg: string): void; }
): LeaderboardManager
{
if (!TurbulenzServices.available())
{
// Call error callback on a timeout to get the same behaviour as the ajax call
TurbulenzEngine.setTimeout(function () {
if (errorCallbackFn)
{
errorCallbackFn('TurbulenzServices.createLeaderboardManager could not load leaderboards meta data');
}
}, 0);
return null;
}
var leaderboardManager = new LeaderboardManager();
leaderboardManager.gameSession = gameSession;
leaderboardManager.gameSessionId = gameSession.gameSessionId;
leaderboardManager.errorCallbackFn = errorCallbackFn || TurbulenzServices.defaultErrorCallback;
leaderboardManager.service = TurbulenzServices.getService('leaderboards');
leaderboardManager.requestHandler = requestHandler;
leaderboardManager.ready = false;
leaderboardManager.service.request({
url: '/api/v1/leaderboards/read/' + gameSession.gameSlug,
method: 'GET',
callback: function createLeaderboardManagerAjaxErrorCheck(jsonResponse, status) {
if (status === 200)
{
var metaArray = jsonResponse.data;
if (metaArray)
{
leaderboardManager.meta = {};
var metaLength = metaArray.length;
var i;
for (i = 0; i < metaLength; i += 1)
{
var board = metaArray[i];
leaderboardManager.meta[board.key] = board;
}
}
leaderboardManager.ready = true;
if (leaderboardMetaReceived)
{
leaderboardMetaReceived(leaderboardManager);
}
}
else
{
leaderboardManager.errorCallbackFn("TurbulenzServices.createLeaderboardManager " +
"error with HTTP status " + status + ": " +
jsonResponse.msg, status);
}
},
requestHandler: requestHandler,
neverDiscard: true
}, 'leaderboard.meta');
return leaderboardManager;
}
}
interface LeaderboardDataSpec
{
type?: string;
size?: number;
friendsOnly?: boolean;
friendsonly?: number;
score?: number;
time?: number;
}
// =============================================================================
// LeaderboardResult
// =============================================================================
interface LeaderboardResultsData
{
spec: any; // TODO:
overlap: any; // TODO:
player?: any; // TODO:
ranking?: any[]; // TODO;
playerIndex?: number;
top?: boolean;
bottom?: boolean;
}
class LeaderboardResult
{
leaderboardManager: LeaderboardManager;
key: string;
originalSpec: LeaderboardDataSpec;
spec: LeaderboardDataSpec;
results: any; // TODO
viewTop: number;
viewSize: number;
viewLock: boolean;
view: { player; // TODO
ranking; // TODO
playerIndex: number;
top: boolean;
bottom: boolean; };
invalidView: boolean;
onSlidingWindowUpdate: any; // TODO
// Prototype:
version: number;
requestSize: number;
computeOverlap(): void
{
// calculates the number of scores that the leaderboard results have overlapped
// this only happens at the end of the leaderboards
var results = this.results;
var overlap = 0;
if (results.top || results.bottom)
{
var ranking = results.ranking;
var rankingLength = ranking.length;
var sortBy = this.leaderboardManager.meta[this.key].sortBy;
var aboveType = this.leaderboardManager.getTypes.above;
var specScore = results.spec.score;
var specTime = results.spec.time;
var i;
for (i = 0; i < rankingLength; i += 1)
{
var rank = ranking[i];
// find the overlapping point where the score was requested
if (rank.score * sortBy < specScore * sortBy ||
(rank.score === specScore && rank.time >= specTime))
{
// get the distance from end of the board to score requested
// add 1 becuase the above/below requests are exclusive of the requested score
if (results.spec.type === aboveType)
{
overlap = rankingLength - i;
}
else
{
overlap = i + 1;
}
break;
}
}
}
results.overlap = overlap;
}
getPageOffset(type, offsetIndex, callbackFn, errorCallbackFn)
{
var offsetScore = this.results.ranking[offsetIndex];
if (!offsetScore)
{
TurbulenzEngine.setTimeout(callbackFn, 0);
return false;
}
var newSpec = {
type: type,
score: offsetScore.score,
time: offsetScore.time,
size: this.requestSize,
// remeber to map to backend lowercase format!
friendsonly: this.originalSpec.friendsOnly && 1 || 0
};
// store the spec for refresh calls
this.spec = newSpec;
var that = this;
function parseResults(data)
{
that.parseResults(that.key, newSpec, data);
that.computeOverlap();
callbackFn();
}
this.leaderboardManager.getRaw(this.key, newSpec, parseResults, errorCallbackFn);
return true;
}
viewOperationBegin()
{
// lock the view object so not other page/scroll calls can be made
if (this.viewLock)
{
return false;
}
this.viewLock = true;
return true;
}
viewOperationEnd(callbackFn)
{
// unlock the view object so other page/scroll calls can be made
this.viewLock = false;
var that = this;
function callbackWrapperFn()
{
callbackFn(that.key, that);
}
if (callbackFn)
{
TurbulenzEngine.setTimeout(callbackWrapperFn, 0);
}
}
wrapViewOperationError(errorCallbackFn)
{
var that = this;
return function errorWrapper(errorMsg, httpStatus, calledByFn, calledByParams)
{
// unlock the view object so other page/scroll calls can be made
that.viewLock = false;
errorCallbackFn(errorMsg, httpStatus, calledByFn, calledByParams);
};
}
refresh(callbackFn, errorCallbackFn)
{
if (!this.viewOperationBegin())
{
return false;
}
var that = this;
function parseResults(data)
{
that.parseResults(that.key, that.spec, data);
that.computeOverlap();
that.invalidView = true;
if (that.onSlidingWindowUpdate)
{
that.onSlidingWindowUpdate();
}
that.viewOperationEnd(callbackFn);
}
this.leaderboardManager.getRaw(this.key, this.spec, parseResults, this.wrapViewOperationError(errorCallbackFn));
return true;
}
moveUp(offset, callbackFn, errorCallbackFn)
{
if (!this.viewOperationBegin())
{
return false;
}
var that = this;
function newResult()
{
var results = that.results;
that.viewTop = Math.max(0, results.ranking.length - that.viewSize - results.overlap);
that.invalidView = true;
if (that.onSlidingWindowUpdate)
{
that.onSlidingWindowUpdate();
}
that.viewOperationEnd(callbackFn);
}
if (this.viewTop - offset < 0)
{
if (this.results.top)
{
this.viewTop = 0;
this.viewOperationEnd(callbackFn);
}
else
{
this.getPageOffset(this.leaderboardManager.getTypes.above,
this.viewTop + this.viewSize - offset,
newResult,
this.wrapViewOperationError(errorCallbackFn));
}
return true;
}
this.viewTop -= offset;
this.invalidView = true;
this.viewOperationEnd(callbackFn);
return true;
}
moveDown(offset, callbackFn, errorCallbackFn)
{
if (!this.viewOperationBegin())
{
return false;
}
var that = this;
function newResult()
{
var results = that.results;
that.viewTop = Math.min(results.overlap, Math.max(results.ranking.length - that.viewSize, 0));
that.invalidView = true;
if (that.onSlidingWindowUpdate)
{
that.onSlidingWindowUpdate();
}
that.viewOperationEnd(callbackFn);
}
var results = this.results;
if (this.viewTop + this.viewSize + offset > results.ranking.length)
{
if (results.bottom)
{
var orginalViewTop = this.viewTop;
this.viewTop = Math.max(results.ranking.length - this.viewSize, 0);
this.invalidView = this.invalidView || (this.viewTop !== orginalViewTop);
this.viewOperationEnd(callbackFn);
}
else
{
this.getPageOffset(this.leaderboardManager.getTypes.below,
this.viewTop + offset - 1,
newResult,
this.wrapViewOperationError(errorCallbackFn));
}
return true;
}
this.viewTop += offset;
this.invalidView = true;
this.viewOperationEnd(callbackFn);
return true;
}
pageUp(callbackFn, errorCallbackFn)
{
return this.moveUp(this.viewSize, callbackFn, errorCallbackFn);
}
pageDown(callbackFn, errorCallbackFn)
{
return this.moveDown(this.viewSize, callbackFn, errorCallbackFn);
}
scrollUp(callbackFn, errorCallbackFn)
{
return this.moveUp(1, callbackFn, errorCallbackFn);
}
scrollDown(callbackFn, errorCallbackFn)
{
return this.moveDown(1, callbackFn, errorCallbackFn);
}
getView()
{
if (this.invalidView)
{
var viewTop = this.viewTop;
var viewSize = this.viewSize;
var results = this.results;
var ranking = results.ranking;
var rankingLength = ranking.length;
var playerIndex : number = null;
if (results.playerIndex !== undefined)
{
playerIndex = results.playerIndex - viewTop;
if (playerIndex < 0 || playerIndex >= viewSize)
{
playerIndex = null;
}
}
this.view = {
ranking: ranking.slice(viewTop, Math.min(viewTop + viewSize, rankingLength)),
top: results.top && (viewTop === 0),
bottom: results.bottom && (viewTop >= rankingLength - viewSize),
player: results.player,
playerIndex: playerIndex
};
}
return this.view;
}
getSlidingWindow()
{
return this.results;
}
private parseResults(key, spec, data): LeaderboardResultsData
{
var results : LeaderboardResultsData = {
spec: spec,
overlap: null
};
var player = results.player = data.player;
var ranking = results.ranking = data.ranking;
var entities = data.entities;
var playerUsername;
if (player)
{
this.leaderboardManager.meta[key].bestScore = player.score;
if (entities)
{
player.user = entities[player.user];
}
playerUsername = player.user.username;
}
var rankingLength = ranking.length;
var i;
for (i = 0; i < rankingLength; i += 1)
{
var rank = ranking[i];
if (entities)
{
rank.user = entities[rank.user];
}
if (rank.user.username === playerUsername)
{
results.playerIndex = i;
}
}
results.top = data.top;
results.bottom = data.bottom;
this.results = results;
return results;
}
static create(leaderboardManager: LeaderboardManager,
key: string,
spec: LeaderboardDataSpec,
data: any): LeaderboardResult
{
var leaderboardResult = new LeaderboardResult();
leaderboardResult.leaderboardManager = leaderboardManager;
leaderboardResult.key = key;
// patch up friendsOnly for frontend
spec.friendsOnly = (0 !== spec.friendsonly);
delete spec.friendsonly;
// store the original spec used to create the results
leaderboardResult.originalSpec = spec;
// the spec used to generate the current results
leaderboardResult.spec = spec;
var results = leaderboardResult.results = leaderboardResult.parseResults(key, spec, data);
leaderboardResult.viewTop = 0;
leaderboardResult.viewSize = spec.size;
// lock to stop multiple synchronous view operations
// as that will have unknown consequences
leaderboardResult.viewLock = false;
// for lazy evaluation
leaderboardResult.view = {
player: results.player,
ranking: results.ranking,
playerIndex: results.playerIndex,
top: results.top,
bottom: results.bottom
};
leaderboardResult.invalidView = false;
// callback called when the results is requested
leaderboardResult.onSlidingWindowUpdate = null;
return leaderboardResult;
}
}
LeaderboardResult.prototype.version = 1;
LeaderboardResult.prototype.requestSize = 64; | the_stack |
import { Data } from '../data';
import { Type } from '../enum';
import { Visitor } from '../visitor';
import { VectorType } from '../interfaces';
import { instance as iteratorVisitor } from './iterator';
import {
DataType, Dictionary,
Bool, Null, Utf8, Binary, Decimal, FixedSizeBinary, List, FixedSizeList, Map_, Struct,
Float, Float16, Float32, Float64,
Int, Uint8, Uint16, Uint32, Uint64, Int8, Int16, Int32, Int64,
Date_, DateDay, DateMillisecond,
Interval, IntervalDayTime, IntervalYearMonth,
Time, TimeSecond, TimeMillisecond, TimeMicrosecond, TimeNanosecond,
Timestamp, TimestampSecond, TimestampMillisecond, TimestampMicrosecond, TimestampNanosecond,
Union, DenseUnion, SparseUnion,
} from '../type';
/** @ignore */
export interface ToArrayVisitor extends Visitor {
visit<T extends VectorType>(node: T): T['TArray'];
visitMany<T extends VectorType>(nodes: T[]): T['TArray'][];
getVisitFn<T extends Type>(node: T): (vector: VectorType<T>) => VectorType<T>['TArray'];
getVisitFn<T extends DataType>(node: VectorType<T> | Data<T> | T): (vector: VectorType<T>) => VectorType<T>['TArray'];
visitNull <T extends Null> (vector: VectorType<T>): VectorType<T>['TArray'];
visitBool <T extends Bool> (vector: VectorType<T>): VectorType<T>['TArray'];
visitInt <T extends Int> (vector: VectorType<T>): VectorType<T>['TArray'];
visitInt8 <T extends Int8> (vector: VectorType<T>): VectorType<T>['TArray'];
visitInt16 <T extends Int16> (vector: VectorType<T>): VectorType<T>['TArray'];
visitInt32 <T extends Int32> (vector: VectorType<T>): VectorType<T>['TArray'];
visitInt64 <T extends Int64> (vector: VectorType<T>): VectorType<T>['TArray'];
visitUint8 <T extends Uint8> (vector: VectorType<T>): VectorType<T>['TArray'];
visitUint16 <T extends Uint16> (vector: VectorType<T>): VectorType<T>['TArray'];
visitUint32 <T extends Uint32> (vector: VectorType<T>): VectorType<T>['TArray'];
visitUint64 <T extends Uint64> (vector: VectorType<T>): VectorType<T>['TArray'];
visitFloat <T extends Float> (vector: VectorType<T>): VectorType<T>['TArray'];
visitFloat16 <T extends Float16> (vector: VectorType<T>): VectorType<T>['TArray'];
visitFloat32 <T extends Float32> (vector: VectorType<T>): VectorType<T>['TArray'];
visitFloat64 <T extends Float64> (vector: VectorType<T>): VectorType<T>['TArray'];
visitUtf8 <T extends Utf8> (vector: VectorType<T>): VectorType<T>['TArray'];
visitBinary <T extends Binary> (vector: VectorType<T>): VectorType<T>['TArray'];
visitFixedSizeBinary <T extends FixedSizeBinary> (vector: VectorType<T>): VectorType<T>['TArray'];
visitDate <T extends Date_> (vector: VectorType<T>): VectorType<T>['TArray'];
visitDateDay <T extends DateDay> (vector: VectorType<T>): VectorType<T>['TArray'];
visitDateMillisecond <T extends DateMillisecond> (vector: VectorType<T>): VectorType<T>['TArray'];
visitTimestamp <T extends Timestamp> (vector: VectorType<T>): VectorType<T>['TArray'];
visitTimestampSecond <T extends TimestampSecond> (vector: VectorType<T>): VectorType<T>['TArray'];
visitTimestampMillisecond <T extends TimestampMillisecond>(vector: VectorType<T>): VectorType<T>['TArray'];
visitTimestampMicrosecond <T extends TimestampMicrosecond>(vector: VectorType<T>): VectorType<T>['TArray'];
visitTimestampNanosecond <T extends TimestampNanosecond> (vector: VectorType<T>): VectorType<T>['TArray'];
visitTime <T extends Time> (vector: VectorType<T>): VectorType<T>['TArray'];
visitTimeSecond <T extends TimeSecond> (vector: VectorType<T>): VectorType<T>['TArray'];
visitTimeMillisecond <T extends TimeMillisecond> (vector: VectorType<T>): VectorType<T>['TArray'];
visitTimeMicrosecond <T extends TimeMicrosecond> (vector: VectorType<T>): VectorType<T>['TArray'];
visitTimeNanosecond <T extends TimeNanosecond> (vector: VectorType<T>): VectorType<T>['TArray'];
visitDecimal <T extends Decimal> (vector: VectorType<T>): VectorType<T>['TArray'];
visitList <R extends DataType, T extends List<R>> (vector: VectorType<T>): VectorType<T>['TArray'];
visitStruct <T extends Struct> (vector: VectorType<T>): VectorType<T>['TArray'];
visitUnion <T extends Union> (vector: VectorType<T>): VectorType<T>['TArray'];
visitDenseUnion <T extends DenseUnion> (vector: VectorType<T>): VectorType<T>['TArray'];
visitSparseUnion <T extends SparseUnion> (vector: VectorType<T>): VectorType<T>['TArray'];
visitDictionary <R extends DataType, T extends Dictionary<R>> (vector: VectorType<T>): VectorType<T>['TArray'];
visitInterval <T extends Interval> (vector: VectorType<T>): VectorType<T>['TArray'];
visitIntervalDayTime <T extends IntervalDayTime> (vector: VectorType<T>): VectorType<T>['TArray'];
visitIntervalYearMonth <T extends IntervalYearMonth> (vector: VectorType<T>): VectorType<T>['TArray'];
visitFixedSizeList <R extends DataType, T extends FixedSizeList<R>> (vector: VectorType<T>): VectorType<T>['TArray'];
visitMap <T extends Map_> (vector: VectorType<T>): VectorType<T>['TArray'];
}
/** @ignore */
export class ToArrayVisitor extends Visitor {}
/** @ignore */
function arrayOfVector<T extends DataType>(vector: VectorType<T>): T['TArray'] {
const { type, length, stride } = vector;
// Fast case, return subarray if possible
switch (type.typeId) {
case Type.Int:
case Type.Float: case Type.Decimal:
case Type.Time: case Type.Timestamp:
return vector.data.values.subarray(0, length * stride);
}
// Otherwise if not primitive, slow copy
return [...iteratorVisitor.visit(vector)] as T['TArray'];
}
ToArrayVisitor.prototype.visitNull = arrayOfVector;
ToArrayVisitor.prototype.visitBool = arrayOfVector;
ToArrayVisitor.prototype.visitInt = arrayOfVector;
ToArrayVisitor.prototype.visitInt8 = arrayOfVector;
ToArrayVisitor.prototype.visitInt16 = arrayOfVector;
ToArrayVisitor.prototype.visitInt32 = arrayOfVector;
ToArrayVisitor.prototype.visitInt64 = arrayOfVector;
ToArrayVisitor.prototype.visitUint8 = arrayOfVector;
ToArrayVisitor.prototype.visitUint16 = arrayOfVector;
ToArrayVisitor.prototype.visitUint32 = arrayOfVector;
ToArrayVisitor.prototype.visitUint64 = arrayOfVector;
ToArrayVisitor.prototype.visitFloat = arrayOfVector;
ToArrayVisitor.prototype.visitFloat16 = arrayOfVector;
ToArrayVisitor.prototype.visitFloat32 = arrayOfVector;
ToArrayVisitor.prototype.visitFloat64 = arrayOfVector;
ToArrayVisitor.prototype.visitUtf8 = arrayOfVector;
ToArrayVisitor.prototype.visitBinary = arrayOfVector;
ToArrayVisitor.prototype.visitFixedSizeBinary = arrayOfVector;
ToArrayVisitor.prototype.visitDate = arrayOfVector;
ToArrayVisitor.prototype.visitDateDay = arrayOfVector;
ToArrayVisitor.prototype.visitDateMillisecond = arrayOfVector;
ToArrayVisitor.prototype.visitTimestamp = arrayOfVector;
ToArrayVisitor.prototype.visitTimestampSecond = arrayOfVector;
ToArrayVisitor.prototype.visitTimestampMillisecond = arrayOfVector;
ToArrayVisitor.prototype.visitTimestampMicrosecond = arrayOfVector;
ToArrayVisitor.prototype.visitTimestampNanosecond = arrayOfVector;
ToArrayVisitor.prototype.visitTime = arrayOfVector;
ToArrayVisitor.prototype.visitTimeSecond = arrayOfVector;
ToArrayVisitor.prototype.visitTimeMillisecond = arrayOfVector;
ToArrayVisitor.prototype.visitTimeMicrosecond = arrayOfVector;
ToArrayVisitor.prototype.visitTimeNanosecond = arrayOfVector;
ToArrayVisitor.prototype.visitDecimal = arrayOfVector;
ToArrayVisitor.prototype.visitList = arrayOfVector;
ToArrayVisitor.prototype.visitStruct = arrayOfVector;
ToArrayVisitor.prototype.visitUnion = arrayOfVector;
ToArrayVisitor.prototype.visitDenseUnion = arrayOfVector;
ToArrayVisitor.prototype.visitSparseUnion = arrayOfVector;
ToArrayVisitor.prototype.visitDictionary = arrayOfVector;
ToArrayVisitor.prototype.visitInterval = arrayOfVector;
ToArrayVisitor.prototype.visitIntervalDayTime = arrayOfVector;
ToArrayVisitor.prototype.visitIntervalYearMonth = arrayOfVector;
ToArrayVisitor.prototype.visitFixedSizeList = arrayOfVector;
ToArrayVisitor.prototype.visitMap = arrayOfVector;
/** @ignore */
export const instance = new ToArrayVisitor(); | the_stack |
import Logger from '../logger/Logger';
import AsyncScheduler from '../scheduler/AsyncScheduler';
import SimulcastLayers from '../simulcastlayers/SimulcastLayers';
import SimulcastTransceiverController from '../transceivercontroller/SimulcastTransceiverController';
import { Maybe } from '../utils/Types';
import DefaultVideoAndEncodeParameter from '../videocaptureandencodeparameter/DefaultVideoCaptureAndEncodeParameter';
import VideoStreamDescription from '../videostreamindex/VideoStreamDescription';
import VideoStreamIndex from '../videostreamindex/VideoStreamIndex';
import BitrateParameters from './BitrateParameters';
import ConnectionMetrics from './ConnectionMetrics';
import SimulcastUplinkObserver from './SimulcastUplinkObserver';
import SimulcastUplinkPolicy from './SimulcastUplinkPolicy';
const enum ActiveStreams {
kHi,
kHiAndLow,
kMidAndLow,
kLow,
}
/**
* [[DefaultSimulcastUplinkPolicy]] determines capture and encode
* parameters that reacts to estimated uplink bandwidth
*/
export default class DefaultSimulcastUplinkPolicy implements SimulcastUplinkPolicy {
static readonly defaultUplinkBandwidthKbps: number = 1200;
static readonly startupDurationMs: number = 6000;
static readonly holdDownDurationMs: number = 4000;
static readonly defaultMaxFrameRate = 15;
// Current rough estimates where webrtc disables streams
static readonly kHiDisabledRate = 700;
static readonly kMidDisabledRate = 240;
private numSenders: number = 0;
private numParticipants: number = -1;
private optimalParameters: DefaultVideoAndEncodeParameter;
private parametersInEffect: DefaultVideoAndEncodeParameter;
private newQualityMap = new Map<string, RTCRtpEncodingParameters>();
private currentQualityMap = new Map<string, RTCRtpEncodingParameters>();
private newActiveStreams: ActiveStreams = ActiveStreams.kHiAndLow;
private currentActiveStreams: ActiveStreams = ActiveStreams.kHiAndLow;
private lastUplinkBandwidthKbps: number = DefaultSimulcastUplinkPolicy.defaultUplinkBandwidthKbps;
private startTimeMs: number = 0;
private lastUpdatedMs: number = Date.now();
private videoIndex: VideoStreamIndex | null = null;
private currLocalDescriptions: VideoStreamDescription[] = [];
private nextLocalDescriptions: VideoStreamDescription[] = [];
private activeStreamsToPublish: ActiveStreams;
private observerQueue: Set<SimulcastUplinkObserver> = new Set<SimulcastUplinkObserver>();
constructor(private selfAttendeeId: string, private logger: Logger) {
this.optimalParameters = new DefaultVideoAndEncodeParameter(0, 0, 0, 0, true);
this.parametersInEffect = new DefaultVideoAndEncodeParameter(0, 0, 0, 0, true);
this.lastUplinkBandwidthKbps = DefaultSimulcastUplinkPolicy.defaultUplinkBandwidthKbps;
this.currentQualityMap = this.fillEncodingParamWithBitrates([300, 0, 1200]);
this.newQualityMap = this.fillEncodingParamWithBitrates([300, 0, 1200]);
}
updateConnectionMetric({ uplinkKbps = 0 }: ConnectionMetrics): void {
if (isNaN(uplinkKbps)) {
return;
}
// Check if startup period in order to ignore estimate when video first enabled.
// If only audio was active then the estimate will be very low
if (this.startTimeMs === 0) {
this.startTimeMs = Date.now();
}
if (Date.now() - this.startTimeMs < DefaultSimulcastUplinkPolicy.startupDurationMs) {
this.lastUplinkBandwidthKbps = DefaultSimulcastUplinkPolicy.defaultUplinkBandwidthKbps;
} else {
this.lastUplinkBandwidthKbps = uplinkKbps;
}
this.logger.debug(() => {
return `simulcast: uplink policy update metrics ${this.lastUplinkBandwidthKbps}`;
});
let holdTime = DefaultSimulcastUplinkPolicy.holdDownDurationMs;
if (this.currentActiveStreams === ActiveStreams.kLow) {
holdTime = DefaultSimulcastUplinkPolicy.holdDownDurationMs * 2;
} else if (
(this.currentActiveStreams === ActiveStreams.kMidAndLow &&
uplinkKbps <= DefaultSimulcastUplinkPolicy.kMidDisabledRate) ||
(this.currentActiveStreams === ActiveStreams.kHiAndLow &&
uplinkKbps <= DefaultSimulcastUplinkPolicy.kHiDisabledRate)
) {
holdTime = DefaultSimulcastUplinkPolicy.holdDownDurationMs / 2;
}
if (Date.now() < this.lastUpdatedMs + holdTime) {
return;
}
this.newQualityMap = this.calculateEncodingParameters(false);
}
private calculateEncodingParameters(
numSendersChanged: boolean
): Map<string, RTCRtpEncodingParameters> {
// bitrates parameter min is not used for now
const newBitrates: BitrateParameters[] = [
new BitrateParameters(),
new BitrateParameters(),
new BitrateParameters(),
];
let hysteresisIncrease = 0,
hysteresisDecrease = 0;
if (this.currentActiveStreams === ActiveStreams.kHi) {
// Don't trigger redetermination based on rate if only one simulcast stream
hysteresisIncrease = this.lastUplinkBandwidthKbps + 1;
hysteresisDecrease = 0;
} else if (this.currentActiveStreams === ActiveStreams.kHiAndLow) {
hysteresisIncrease = 2400;
hysteresisDecrease = DefaultSimulcastUplinkPolicy.kHiDisabledRate;
} else if (this.currentActiveStreams === ActiveStreams.kMidAndLow) {
hysteresisIncrease = 1000;
hysteresisDecrease = DefaultSimulcastUplinkPolicy.kMidDisabledRate;
} else {
hysteresisIncrease = 300;
hysteresisDecrease = 0;
}
if (
numSendersChanged ||
this.lastUplinkBandwidthKbps >= hysteresisIncrease ||
this.lastUplinkBandwidthKbps <= hysteresisDecrease
) {
if (this.numParticipants >= 0 && this.numParticipants <= 2) {
// Simulcast disabled
this.newActiveStreams = ActiveStreams.kHi;
newBitrates[0].maxBitrateKbps = 0;
newBitrates[1].maxBitrateKbps = 0;
newBitrates[2].maxBitrateKbps = 1200;
} else if (
this.numSenders <= 4 &&
this.lastUplinkBandwidthKbps >= DefaultSimulcastUplinkPolicy.kHiDisabledRate
) {
// 320x192+ (640x384) + 1280x768
this.newActiveStreams = ActiveStreams.kHiAndLow;
newBitrates[0].maxBitrateKbps = 300;
newBitrates[1].maxBitrateKbps = 0;
newBitrates[2].maxBitrateKbps = 1200;
} else if (this.lastUplinkBandwidthKbps >= DefaultSimulcastUplinkPolicy.kMidDisabledRate) {
// 320x192 + 640x384 + (1280x768)
this.newActiveStreams = ActiveStreams.kMidAndLow;
newBitrates[0].maxBitrateKbps = this.lastUplinkBandwidthKbps >= 350 ? 200 : 150;
newBitrates[1].maxBitrateKbps = this.numSenders <= 6 ? 600 : 350;
newBitrates[2].maxBitrateKbps = 0;
} else {
// 320x192 + 640x384 + (1280x768)
this.newActiveStreams = ActiveStreams.kLow;
newBitrates[0].maxBitrateKbps = 300;
newBitrates[1].maxBitrateKbps = 0;
newBitrates[2].maxBitrateKbps = 0;
}
const bitrates: number[] = newBitrates.map((v, _i, _a) => {
return v.maxBitrateKbps;
});
this.newQualityMap = this.fillEncodingParamWithBitrates(bitrates);
if (!this.encodingParametersEqual()) {
this.logger.info(
`simulcast: policy:calculateEncodingParameters bw:${
this.lastUplinkBandwidthKbps
} numSources:${this.numSenders} numClients:${
this.numParticipants
} newQualityMap: ${this.getQualityMapString(this.newQualityMap)}`
);
}
}
return this.newQualityMap;
}
chooseMediaTrackConstraints(): MediaTrackConstraints {
// Changing MediaTrackConstraints causes a restart of video input and possible small
// scaling changes. Always use 720p for now
const trackConstraint: MediaTrackConstraints = {
width: { ideal: 1280 },
height: { ideal: 768 },
frameRate: { ideal: 15 },
};
return trackConstraint;
}
chooseEncodingParameters(): Map<string, RTCRtpEncodingParameters> {
this.currentQualityMap = this.newQualityMap;
this.currentActiveStreams = this.newActiveStreams;
if (this.activeStreamsToPublish !== this.newActiveStreams) {
this.activeStreamsToPublish = this.newActiveStreams;
this.publishEncodingSimulcastLayer();
}
return this.currentQualityMap;
}
updateIndex(videoIndex: VideoStreamIndex): void {
// the +1 for self is assuming that we intend to send video, since
// the context here is VideoUplinkBandwidthPolicy
const numSenders =
videoIndex.numberOfVideoPublishingParticipantsExcludingSelf(this.selfAttendeeId) + 1;
const numParticipants = videoIndex.numberOfParticipants();
const numSendersChanged = numSenders !== this.numSenders;
const numParticipantsChanged =
(numParticipants > 2 && this.numParticipants <= 2) ||
(numParticipants <= 2 && this.numParticipants > 2);
this.numSenders = numSenders;
this.numParticipants = numParticipants;
this.optimalParameters = new DefaultVideoAndEncodeParameter(
this.captureWidth(),
this.captureHeight(),
this.captureFrameRate(),
this.maxBandwidthKbps(),
false
);
this.videoIndex = videoIndex;
this.newQualityMap = this.calculateEncodingParameters(
numSendersChanged || numParticipantsChanged
);
}
wantsResubscribe(): boolean {
let constraintDiff = !this.encodingParametersEqual();
this.nextLocalDescriptions = this.videoIndex.localStreamDescriptions();
for (let i = 0; i < this.nextLocalDescriptions.length; i++) {
const streamId = this.nextLocalDescriptions[i].streamId;
if (streamId !== 0 && !!streamId) {
const prevIndex = this.currLocalDescriptions.findIndex(val => {
return val.streamId === streamId;
});
if (prevIndex !== -1) {
if (
this.nextLocalDescriptions[i].disabledByWebRTC !==
this.currLocalDescriptions[prevIndex].disabledByWebRTC
) {
constraintDiff = true;
}
}
}
}
if (constraintDiff) {
this.lastUpdatedMs = Date.now();
}
this.currLocalDescriptions = this.nextLocalDescriptions;
return constraintDiff;
}
private compareEncodingParameter(
encoding1: RTCRtpEncodingParameters,
encoding2: RTCRtpEncodingParameters
): boolean {
return JSON.stringify(encoding1) === JSON.stringify(encoding2);
}
private encodingParametersEqual(): boolean {
let different = false;
for (const ridName of SimulcastTransceiverController.NAME_ARR_ASCENDING) {
different =
different ||
!this.compareEncodingParameter(
this.newQualityMap.get(ridName),
this.currentQualityMap.get(ridName)
);
if (different) {
break;
}
}
return !different;
}
chooseCaptureAndEncodeParameters(): DefaultVideoAndEncodeParameter {
// should deprecate in this policy
this.parametersInEffect = this.optimalParameters.clone();
return this.parametersInEffect.clone();
}
private captureWidth(): number {
// should deprecate in this policy
const width = 1280;
return width;
}
private captureHeight(): number {
// should deprecate in this policy
const height = 768;
return height;
}
private captureFrameRate(): number {
// should deprecate in this policy
return 15;
}
maxBandwidthKbps(): number {
// should deprecate in this policy
return 1400;
}
setIdealMaxBandwidthKbps(_idealMaxBandwidthKbps: number): void {
// should deprecate in this policy
}
setHasBandwidthPriority(_hasBandwidthPriority: boolean): void {
// should deprecate in this policy
}
private fillEncodingParamWithBitrates(
bitratesKbps: number[]
): Map<string, RTCRtpEncodingParameters> {
const newMap = new Map<string, RTCRtpEncodingParameters>();
const toBps = 1000;
const nameArr = SimulcastTransceiverController.NAME_ARR_ASCENDING;
const bitrateArr = bitratesKbps;
let scale = 4;
for (let i = 0; i < nameArr.length; i++) {
const ridName = nameArr[i];
newMap.set(ridName, {
rid: ridName,
active: bitrateArr[i] > 0 ? true : false,
scaleResolutionDownBy: scale,
maxBitrate: bitrateArr[i] * toBps,
});
scale = scale / 2;
}
return newMap;
}
private getQualityMapString(params: Map<string, RTCRtpEncodingParameters>): string {
let qualityString = '';
const localDescriptions = this.videoIndex.localStreamDescriptions();
if (localDescriptions.length === 3) {
params.forEach((value: RTCRtpEncodingParameters) => {
let disabledByWebRTC = false;
if (value.rid === 'low') disabledByWebRTC = localDescriptions[0].disabledByWebRTC;
else if (value.rid === 'mid') disabledByWebRTC = localDescriptions[1].disabledByWebRTC;
else disabledByWebRTC = localDescriptions[2].disabledByWebRTC;
qualityString += `{ rid: ${value.rid} active:${value.active} disabledByWebRTC: ${disabledByWebRTC} maxBitrate:${value.maxBitrate}}`;
});
}
return qualityString;
}
getEncodingSimulcastLayer(activeStreams: ActiveStreams): SimulcastLayers {
switch (activeStreams) {
case ActiveStreams.kHi:
return SimulcastLayers.High;
case ActiveStreams.kHiAndLow:
return SimulcastLayers.LowAndHigh;
case ActiveStreams.kMidAndLow:
return SimulcastLayers.LowAndMedium;
case ActiveStreams.kLow:
return SimulcastLayers.Low;
}
}
private publishEncodingSimulcastLayer(): void {
const simulcastLayers = this.getEncodingSimulcastLayer(this.activeStreamsToPublish);
this.forEachObserver(observer => {
Maybe.of(observer.encodingSimulcastLayersDidChange).map(f =>
f.bind(observer)(simulcastLayers)
);
});
}
addObserver(observer: SimulcastUplinkObserver): void {
this.logger.info('adding simulcast uplink observer');
this.observerQueue.add(observer);
}
removeObserver(observer: SimulcastUplinkObserver): void {
this.logger.info('removing simulcast uplink observer');
this.observerQueue.delete(observer);
}
forEachObserver(observerFunc: (observer: SimulcastUplinkObserver) => void): void {
for (const observer of this.observerQueue) {
AsyncScheduler.nextTick(() => {
if (this.observerQueue.has(observer)) {
observerFunc(observer);
}
});
}
}
} | the_stack |
import {
Middleware,
AnyMiddlewareArgs,
SlackActionMiddlewareArgs,
SlackCommandMiddlewareArgs,
SlackEventMiddlewareArgs,
SlackOptionsMiddlewareArgs,
SlackShortcutMiddlewareArgs,
SlackViewMiddlewareArgs,
SlackEvent,
SlackAction,
SlackShortcut,
SlashCommand,
SlackOptions,
BlockSuggestion,
InteractiveMessageSuggestion,
DialogSuggestion,
InteractiveMessage,
DialogSubmitAction,
GlobalShortcut,
MessageShortcut,
BlockElementAction,
SlackViewAction,
EventTypePattern,
ViewOutput,
} from '../types';
import { ActionConstraints, ViewConstraints, ShortcutConstraints } from '../App';
import { ContextMissingPropertyError } from '../errors';
/**
* Middleware that filters out any event that isn't an action
*/
export const onlyActions: Middleware<AnyMiddlewareArgs & { action?: SlackAction }> = async (args) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { action, next } = args as any; // FIXME: workaround for TypeScript 4.7 breaking changes
// Filter out any non-actions
if (action === undefined) {
return;
}
// It matches so we should continue down this middleware listener chain
await next();
};
/**
* Middleware that filters out any event that isn't a shortcut
*/
export const onlyShortcuts: Middleware<AnyMiddlewareArgs & { shortcut?: SlackShortcut }> = async (args) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { shortcut, next } = args as any; // FIXME: workaround for TypeScript 4.7 breaking changes
// Filter out any non-shortcuts
if (shortcut === undefined) {
return;
}
// It matches so we should continue down this middleware listener chain
await next();
};
/**
* Middleware that filters out any event that isn't a command
*/
export const onlyCommands: Middleware<AnyMiddlewareArgs & { command?: SlashCommand }> = async (args) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { command, next } = args as any; // FIXME: workaround for TypeScript 4.7 breaking changes
// Filter out any non-commands
if (command === undefined) {
return;
}
// It matches so we should continue down this middleware listener chain
await next();
};
/**
* Middleware that filters out any event that isn't an options
*/
export const onlyOptions: Middleware<AnyMiddlewareArgs & { options?: SlackOptions }> = async (args) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { options, next } = args as any; // FIXME: workaround for TypeScript 4.7 breaking changes
// Filter out any non-options requests
if (options === undefined) {
return;
}
// It matches so we should continue down this middleware listener chain
await next();
};
/**
* Middleware that filters out any event that isn't an event
*/
export const onlyEvents: Middleware<AnyMiddlewareArgs & { event?: SlackEvent }> = async (args) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { event, next } = args as any; // FIXME: workaround for TypeScript 4.7 breaking changes
// Filter out any non-events
if (event === undefined) {
return;
}
// It matches so we should continue down this middleware listener chain
await next();
};
/**
* Middleware that filters out any event that isn't a view_submission or view_closed event
*/
export const onlyViewActions: Middleware<AnyMiddlewareArgs & { view?: ViewOutput }> = async (args) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { view, next } = args as any; // FIXME: workaround for TypeScript 4.7 breaking changes
// Filter out anything that doesn't have a view
if (view === undefined) {
return;
}
// It matches so we should continue down this middleware listener chain
await next();
};
/**
* Middleware that checks for matches given constraints
*/
export function matchConstraints(
constraints: ActionConstraints | ViewConstraints | ShortcutConstraints,
): Middleware<SlackActionMiddlewareArgs | SlackOptionsMiddlewareArgs | SlackViewMiddlewareArgs> {
return async ({ payload, body, next, context }) => {
// TODO: is putting matches in an array actually helpful? there's no way to know which of the regexps contributed
// which matches (and in which order)
let tempMatches: RegExpMatchArray | null;
// Narrow type for ActionConstraints
if ('block_id' in constraints || 'action_id' in constraints) {
if (!isBlockPayload(payload)) {
return;
}
// Check block_id
if (constraints.block_id !== undefined) {
if (typeof constraints.block_id === 'string') {
if (payload.block_id !== constraints.block_id) {
return;
}
} else {
tempMatches = payload.block_id.match(constraints.block_id);
if (tempMatches !== null) {
context['blockIdMatches'] = tempMatches;
} else {
return;
}
}
}
// Check action_id
if (constraints.action_id !== undefined) {
if (typeof constraints.action_id === 'string') {
if (payload.action_id !== constraints.action_id) {
return;
}
} else {
tempMatches = payload.action_id.match(constraints.action_id);
if (tempMatches !== null) {
context['actionIdMatches'] = tempMatches;
} else {
return;
}
}
}
}
// Check callback_id
if ('callback_id' in constraints && constraints.callback_id !== undefined) {
let callbackId: string = '';
if (isViewBody(body)) {
callbackId = body['view']['callback_id'];
} else if (isCallbackIdentifiedBody(body)) {
callbackId = body['callback_id'];
} else {
return;
}
if (typeof constraints.callback_id === 'string') {
if (callbackId !== constraints.callback_id) {
return;
}
} else {
tempMatches = callbackId.match(constraints.callback_id);
if (tempMatches !== null) {
context['callbackIdMatches'] = tempMatches;
} else {
return;
}
}
}
// Check type
if ('type' in constraints) {
if (body.type !== constraints.type) return;
}
await next();
};
}
/*
* Middleware that filters out messages that don't match pattern
*/
export function matchMessage(
pattern: string | RegExp,
): Middleware<SlackEventMiddlewareArgs<'message' | 'app_mention'>> {
return async ({ event, context, next }) => {
let tempMatches: RegExpMatchArray | null;
if (!('text' in event) || event.text === undefined) {
return;
}
// Filter out messages or app mentions that don't contain the pattern
if (typeof pattern === 'string') {
if (!event.text.includes(pattern)) {
return;
}
} else {
tempMatches = event.text.match(pattern);
if (tempMatches !== null) {
context['matches'] = tempMatches;
} else {
return;
}
}
await next();
};
}
/**
* Middleware that filters out any command that doesn't match the pattern
*/
export function matchCommandName(pattern: string | RegExp): Middleware<SlackCommandMiddlewareArgs> {
return async ({ command, next }) => {
// Filter out any commands that do not match the correct command name or pattern
if (!matchesPattern(pattern, command.command)) {
return;
}
await next();
};
}
function matchesPattern(pattern: string | RegExp, candidate: string): boolean {
if (typeof pattern === 'string') {
return pattern === candidate;
}
return pattern.test(candidate);
}
/*
* Middleware that filters out events that don't match pattern
*/
export function matchEventType(pattern: EventTypePattern): Middleware<SlackEventMiddlewareArgs> {
return async ({ event, context, next }) => {
let tempMatches: RegExpMatchArray | null;
if (!('type' in event) || event.type === undefined) {
return;
}
// Filter out events that don't contain the pattern
if (typeof pattern === 'string') {
if (event.type !== pattern) {
return;
}
} else {
tempMatches = event.type.match(pattern);
if (tempMatches !== null) {
context['matches'] = tempMatches;
} else {
return;
}
}
await next();
};
}
export function ignoreSelf(): Middleware<AnyMiddlewareArgs> {
return async (args) => {
const botId = args.context.botId as string;
const botUserId = args.context.botUserId !== undefined ? (args.context.botUserId as string) : undefined;
if (isEventArgs(args)) {
// Once we've narrowed the type down to SlackEventMiddlewareArgs, there's no way to further narrow it down to
// SlackEventMiddlewareArgs<'message'> without a cast, so the following couple lines do that.
if (args.message !== undefined) {
const message = args.message as SlackEventMiddlewareArgs<'message'>['message'];
// TODO: revisit this once we have all the message subtypes defined to see if we can do this better with
// type narrowing
// Look for an event that is identified as a bot message from the same bot ID as this app, and return to skip
if (message.subtype === 'bot_message' && message.bot_id === botId) {
return;
}
}
// Its an Events API event that isn't of type message, but the user ID might match our own app. Filter these out.
// However, some events still must be fired, because they can make sense.
const eventsWhichShouldBeKept = ['member_joined_channel', 'member_left_channel'];
const isEventShouldBeKept = eventsWhichShouldBeKept.includes(args.event.type);
if (botUserId !== undefined && 'user' in args.event && args.event.user === botUserId && !isEventShouldBeKept) {
return;
}
}
// If all the previous checks didn't skip this message, then its okay to resume to next
await args.next();
};
}
export function subtype(subtype1: string): Middleware<SlackEventMiddlewareArgs<'message'>> {
return async ({ message, next }) => {
if (message.subtype === subtype1) {
await next();
}
};
}
const slackLink = /<(?<type>[@#!])?(?<link>[^>|]+)(?:\|(?<label>[^>]+))?>/;
export function directMention(): Middleware<SlackEventMiddlewareArgs<'message'>> {
return async ({ message, context, next }) => {
// When context does not have a botUserId in it, then this middleware cannot perform its job. Bail immediately.
if (context.botUserId === undefined) {
throw new ContextMissingPropertyError(
'botUserId',
'Cannot match direct mentions of the app without a bot user ID. Ensure authorize callback returns a botUserId.',
);
}
if (!('text' in message) || message.text === undefined) {
return;
}
// Match the message text with a user mention format
const text = message.text.trim();
const matches = slackLink.exec(text);
if (
matches === null || // stop when no matches are found
matches.index !== 0 || // stop if match isn't at the beginning
// stop if match isn't a user mention with the right user ID
matches.groups === undefined ||
matches.groups.type !== '@' ||
matches.groups.link !== context.botUserId
) {
return;
}
await next();
};
}
function isBlockPayload(
payload:
| SlackActionMiddlewareArgs['payload']
| SlackOptionsMiddlewareArgs['payload']
| SlackViewMiddlewareArgs['payload'],
): payload is BlockElementAction | BlockSuggestion {
return (payload as BlockElementAction | BlockSuggestion).action_id !== undefined;
}
type CallbackIdentifiedBody =
| InteractiveMessage
| DialogSubmitAction
| MessageShortcut
| GlobalShortcut
| InteractiveMessageSuggestion
| DialogSuggestion;
function isCallbackIdentifiedBody(
body: SlackActionMiddlewareArgs['body'] | SlackOptionsMiddlewareArgs['body'] | SlackShortcutMiddlewareArgs['body'],
): body is CallbackIdentifiedBody {
return (body as CallbackIdentifiedBody).callback_id !== undefined;
}
function isViewBody(
body: SlackActionMiddlewareArgs['body'] | SlackOptionsMiddlewareArgs['body'] | SlackViewMiddlewareArgs['body'],
): body is SlackViewAction {
return (body as SlackViewAction).view !== undefined;
}
function isEventArgs(args: AnyMiddlewareArgs): args is SlackEventMiddlewareArgs {
return (args as SlackEventMiddlewareArgs).event !== undefined;
} | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config';
interface Blob {}
declare class ECR extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: ECR.Types.ClientConfiguration)
config: Config & ECR.Types.ClientConfiguration;
/**
* Check the availability of multiple image layers in a specified registry and repository. This operation is used by the Amazon ECR proxy, and it is not intended for general use by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.
*/
batchCheckLayerAvailability(params: ECR.Types.BatchCheckLayerAvailabilityRequest, callback?: (err: AWSError, data: ECR.Types.BatchCheckLayerAvailabilityResponse) => void): Request<ECR.Types.BatchCheckLayerAvailabilityResponse, AWSError>;
/**
* Check the availability of multiple image layers in a specified registry and repository. This operation is used by the Amazon ECR proxy, and it is not intended for general use by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.
*/
batchCheckLayerAvailability(callback?: (err: AWSError, data: ECR.Types.BatchCheckLayerAvailabilityResponse) => void): Request<ECR.Types.BatchCheckLayerAvailabilityResponse, AWSError>;
/**
* Deletes a list of specified images within a specified repository. Images are specified with either imageTag or imageDigest. You can remove a tag from an image by specifying the image's tag in your request. When you remove the last tag from an image, the image is deleted from your repository. You can completely delete an image (and all of its tags) by specifying the image's digest in your request.
*/
batchDeleteImage(params: ECR.Types.BatchDeleteImageRequest, callback?: (err: AWSError, data: ECR.Types.BatchDeleteImageResponse) => void): Request<ECR.Types.BatchDeleteImageResponse, AWSError>;
/**
* Deletes a list of specified images within a specified repository. Images are specified with either imageTag or imageDigest. You can remove a tag from an image by specifying the image's tag in your request. When you remove the last tag from an image, the image is deleted from your repository. You can completely delete an image (and all of its tags) by specifying the image's digest in your request.
*/
batchDeleteImage(callback?: (err: AWSError, data: ECR.Types.BatchDeleteImageResponse) => void): Request<ECR.Types.BatchDeleteImageResponse, AWSError>;
/**
* Gets detailed information for specified images within a specified repository. Images are specified with either imageTag or imageDigest.
*/
batchGetImage(params: ECR.Types.BatchGetImageRequest, callback?: (err: AWSError, data: ECR.Types.BatchGetImageResponse) => void): Request<ECR.Types.BatchGetImageResponse, AWSError>;
/**
* Gets detailed information for specified images within a specified repository. Images are specified with either imageTag or imageDigest.
*/
batchGetImage(callback?: (err: AWSError, data: ECR.Types.BatchGetImageResponse) => void): Request<ECR.Types.BatchGetImageResponse, AWSError>;
/**
* Informs Amazon ECR that the image layer upload has completed for a specified registry, repository name, and upload ID. You can optionally provide a sha256 digest of the image layer for data validation purposes. This operation is used by the Amazon ECR proxy, and it is not intended for general use by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.
*/
completeLayerUpload(params: ECR.Types.CompleteLayerUploadRequest, callback?: (err: AWSError, data: ECR.Types.CompleteLayerUploadResponse) => void): Request<ECR.Types.CompleteLayerUploadResponse, AWSError>;
/**
* Informs Amazon ECR that the image layer upload has completed for a specified registry, repository name, and upload ID. You can optionally provide a sha256 digest of the image layer for data validation purposes. This operation is used by the Amazon ECR proxy, and it is not intended for general use by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.
*/
completeLayerUpload(callback?: (err: AWSError, data: ECR.Types.CompleteLayerUploadResponse) => void): Request<ECR.Types.CompleteLayerUploadResponse, AWSError>;
/**
* Creates an image repository.
*/
createRepository(params: ECR.Types.CreateRepositoryRequest, callback?: (err: AWSError, data: ECR.Types.CreateRepositoryResponse) => void): Request<ECR.Types.CreateRepositoryResponse, AWSError>;
/**
* Creates an image repository.
*/
createRepository(callback?: (err: AWSError, data: ECR.Types.CreateRepositoryResponse) => void): Request<ECR.Types.CreateRepositoryResponse, AWSError>;
/**
* Deletes the specified lifecycle policy.
*/
deleteLifecyclePolicy(params: ECR.Types.DeleteLifecyclePolicyRequest, callback?: (err: AWSError, data: ECR.Types.DeleteLifecyclePolicyResponse) => void): Request<ECR.Types.DeleteLifecyclePolicyResponse, AWSError>;
/**
* Deletes the specified lifecycle policy.
*/
deleteLifecyclePolicy(callback?: (err: AWSError, data: ECR.Types.DeleteLifecyclePolicyResponse) => void): Request<ECR.Types.DeleteLifecyclePolicyResponse, AWSError>;
/**
* Deletes an existing image repository. If a repository contains images, you must use the force option to delete it.
*/
deleteRepository(params: ECR.Types.DeleteRepositoryRequest, callback?: (err: AWSError, data: ECR.Types.DeleteRepositoryResponse) => void): Request<ECR.Types.DeleteRepositoryResponse, AWSError>;
/**
* Deletes an existing image repository. If a repository contains images, you must use the force option to delete it.
*/
deleteRepository(callback?: (err: AWSError, data: ECR.Types.DeleteRepositoryResponse) => void): Request<ECR.Types.DeleteRepositoryResponse, AWSError>;
/**
* Deletes the repository policy from a specified repository.
*/
deleteRepositoryPolicy(params: ECR.Types.DeleteRepositoryPolicyRequest, callback?: (err: AWSError, data: ECR.Types.DeleteRepositoryPolicyResponse) => void): Request<ECR.Types.DeleteRepositoryPolicyResponse, AWSError>;
/**
* Deletes the repository policy from a specified repository.
*/
deleteRepositoryPolicy(callback?: (err: AWSError, data: ECR.Types.DeleteRepositoryPolicyResponse) => void): Request<ECR.Types.DeleteRepositoryPolicyResponse, AWSError>;
/**
* Returns metadata about the images in a repository, including image size, image tags, and creation date. Beginning with Docker version 1.9, the Docker client compresses image layers before pushing them to a V2 Docker registry. The output of the docker images command shows the uncompressed image size, so it may return a larger image size than the image sizes returned by DescribeImages.
*/
describeImages(params: ECR.Types.DescribeImagesRequest, callback?: (err: AWSError, data: ECR.Types.DescribeImagesResponse) => void): Request<ECR.Types.DescribeImagesResponse, AWSError>;
/**
* Returns metadata about the images in a repository, including image size, image tags, and creation date. Beginning with Docker version 1.9, the Docker client compresses image layers before pushing them to a V2 Docker registry. The output of the docker images command shows the uncompressed image size, so it may return a larger image size than the image sizes returned by DescribeImages.
*/
describeImages(callback?: (err: AWSError, data: ECR.Types.DescribeImagesResponse) => void): Request<ECR.Types.DescribeImagesResponse, AWSError>;
/**
* Describes image repositories in a registry.
*/
describeRepositories(params: ECR.Types.DescribeRepositoriesRequest, callback?: (err: AWSError, data: ECR.Types.DescribeRepositoriesResponse) => void): Request<ECR.Types.DescribeRepositoriesResponse, AWSError>;
/**
* Describes image repositories in a registry.
*/
describeRepositories(callback?: (err: AWSError, data: ECR.Types.DescribeRepositoriesResponse) => void): Request<ECR.Types.DescribeRepositoriesResponse, AWSError>;
/**
* Retrieves a token that is valid for a specified registry for 12 hours. This command allows you to use the docker CLI to push and pull images with Amazon ECR. If you do not specify a registry, the default registry is assumed. The authorizationToken returned for each registry specified is a base64 encoded string that can be decoded and used in a docker login command to authenticate to a registry. The AWS CLI offers an aws ecr get-login command that simplifies the login process.
*/
getAuthorizationToken(params: ECR.Types.GetAuthorizationTokenRequest, callback?: (err: AWSError, data: ECR.Types.GetAuthorizationTokenResponse) => void): Request<ECR.Types.GetAuthorizationTokenResponse, AWSError>;
/**
* Retrieves a token that is valid for a specified registry for 12 hours. This command allows you to use the docker CLI to push and pull images with Amazon ECR. If you do not specify a registry, the default registry is assumed. The authorizationToken returned for each registry specified is a base64 encoded string that can be decoded and used in a docker login command to authenticate to a registry. The AWS CLI offers an aws ecr get-login command that simplifies the login process.
*/
getAuthorizationToken(callback?: (err: AWSError, data: ECR.Types.GetAuthorizationTokenResponse) => void): Request<ECR.Types.GetAuthorizationTokenResponse, AWSError>;
/**
* Retrieves the pre-signed Amazon S3 download URL corresponding to an image layer. You can only get URLs for image layers that are referenced in an image. This operation is used by the Amazon ECR proxy, and it is not intended for general use by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.
*/
getDownloadUrlForLayer(params: ECR.Types.GetDownloadUrlForLayerRequest, callback?: (err: AWSError, data: ECR.Types.GetDownloadUrlForLayerResponse) => void): Request<ECR.Types.GetDownloadUrlForLayerResponse, AWSError>;
/**
* Retrieves the pre-signed Amazon S3 download URL corresponding to an image layer. You can only get URLs for image layers that are referenced in an image. This operation is used by the Amazon ECR proxy, and it is not intended for general use by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.
*/
getDownloadUrlForLayer(callback?: (err: AWSError, data: ECR.Types.GetDownloadUrlForLayerResponse) => void): Request<ECR.Types.GetDownloadUrlForLayerResponse, AWSError>;
/**
* Retrieves the specified lifecycle policy.
*/
getLifecyclePolicy(params: ECR.Types.GetLifecyclePolicyRequest, callback?: (err: AWSError, data: ECR.Types.GetLifecyclePolicyResponse) => void): Request<ECR.Types.GetLifecyclePolicyResponse, AWSError>;
/**
* Retrieves the specified lifecycle policy.
*/
getLifecyclePolicy(callback?: (err: AWSError, data: ECR.Types.GetLifecyclePolicyResponse) => void): Request<ECR.Types.GetLifecyclePolicyResponse, AWSError>;
/**
* Retrieves the results of the specified lifecycle policy preview request.
*/
getLifecyclePolicyPreview(params: ECR.Types.GetLifecyclePolicyPreviewRequest, callback?: (err: AWSError, data: ECR.Types.GetLifecyclePolicyPreviewResponse) => void): Request<ECR.Types.GetLifecyclePolicyPreviewResponse, AWSError>;
/**
* Retrieves the results of the specified lifecycle policy preview request.
*/
getLifecyclePolicyPreview(callback?: (err: AWSError, data: ECR.Types.GetLifecyclePolicyPreviewResponse) => void): Request<ECR.Types.GetLifecyclePolicyPreviewResponse, AWSError>;
/**
* Retrieves the repository policy for a specified repository.
*/
getRepositoryPolicy(params: ECR.Types.GetRepositoryPolicyRequest, callback?: (err: AWSError, data: ECR.Types.GetRepositoryPolicyResponse) => void): Request<ECR.Types.GetRepositoryPolicyResponse, AWSError>;
/**
* Retrieves the repository policy for a specified repository.
*/
getRepositoryPolicy(callback?: (err: AWSError, data: ECR.Types.GetRepositoryPolicyResponse) => void): Request<ECR.Types.GetRepositoryPolicyResponse, AWSError>;
/**
* Notify Amazon ECR that you intend to upload an image layer. This operation is used by the Amazon ECR proxy, and it is not intended for general use by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.
*/
initiateLayerUpload(params: ECR.Types.InitiateLayerUploadRequest, callback?: (err: AWSError, data: ECR.Types.InitiateLayerUploadResponse) => void): Request<ECR.Types.InitiateLayerUploadResponse, AWSError>;
/**
* Notify Amazon ECR that you intend to upload an image layer. This operation is used by the Amazon ECR proxy, and it is not intended for general use by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.
*/
initiateLayerUpload(callback?: (err: AWSError, data: ECR.Types.InitiateLayerUploadResponse) => void): Request<ECR.Types.InitiateLayerUploadResponse, AWSError>;
/**
* Lists all the image IDs for a given repository. You can filter images based on whether or not they are tagged by setting the tagStatus parameter to TAGGED or UNTAGGED. For example, you can filter your results to return only UNTAGGED images and then pipe that result to a BatchDeleteImage operation to delete them. Or, you can filter your results to return only TAGGED images to list all of the tags in your repository.
*/
listImages(params: ECR.Types.ListImagesRequest, callback?: (err: AWSError, data: ECR.Types.ListImagesResponse) => void): Request<ECR.Types.ListImagesResponse, AWSError>;
/**
* Lists all the image IDs for a given repository. You can filter images based on whether or not they are tagged by setting the tagStatus parameter to TAGGED or UNTAGGED. For example, you can filter your results to return only UNTAGGED images and then pipe that result to a BatchDeleteImage operation to delete them. Or, you can filter your results to return only TAGGED images to list all of the tags in your repository.
*/
listImages(callback?: (err: AWSError, data: ECR.Types.ListImagesResponse) => void): Request<ECR.Types.ListImagesResponse, AWSError>;
/**
* Creates or updates the image manifest and tags associated with an image. This operation is used by the Amazon ECR proxy, and it is not intended for general use by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.
*/
putImage(params: ECR.Types.PutImageRequest, callback?: (err: AWSError, data: ECR.Types.PutImageResponse) => void): Request<ECR.Types.PutImageResponse, AWSError>;
/**
* Creates or updates the image manifest and tags associated with an image. This operation is used by the Amazon ECR proxy, and it is not intended for general use by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.
*/
putImage(callback?: (err: AWSError, data: ECR.Types.PutImageResponse) => void): Request<ECR.Types.PutImageResponse, AWSError>;
/**
* Creates or updates a lifecycle policy. For information about lifecycle policy syntax, see Lifecycle Policy Template.
*/
putLifecyclePolicy(params: ECR.Types.PutLifecyclePolicyRequest, callback?: (err: AWSError, data: ECR.Types.PutLifecyclePolicyResponse) => void): Request<ECR.Types.PutLifecyclePolicyResponse, AWSError>;
/**
* Creates or updates a lifecycle policy. For information about lifecycle policy syntax, see Lifecycle Policy Template.
*/
putLifecyclePolicy(callback?: (err: AWSError, data: ECR.Types.PutLifecyclePolicyResponse) => void): Request<ECR.Types.PutLifecyclePolicyResponse, AWSError>;
/**
* Applies a repository policy on a specified repository to control access permissions.
*/
setRepositoryPolicy(params: ECR.Types.SetRepositoryPolicyRequest, callback?: (err: AWSError, data: ECR.Types.SetRepositoryPolicyResponse) => void): Request<ECR.Types.SetRepositoryPolicyResponse, AWSError>;
/**
* Applies a repository policy on a specified repository to control access permissions.
*/
setRepositoryPolicy(callback?: (err: AWSError, data: ECR.Types.SetRepositoryPolicyResponse) => void): Request<ECR.Types.SetRepositoryPolicyResponse, AWSError>;
/**
* Starts a preview of the specified lifecycle policy. This allows you to see the results before creating the lifecycle policy.
*/
startLifecyclePolicyPreview(params: ECR.Types.StartLifecyclePolicyPreviewRequest, callback?: (err: AWSError, data: ECR.Types.StartLifecyclePolicyPreviewResponse) => void): Request<ECR.Types.StartLifecyclePolicyPreviewResponse, AWSError>;
/**
* Starts a preview of the specified lifecycle policy. This allows you to see the results before creating the lifecycle policy.
*/
startLifecyclePolicyPreview(callback?: (err: AWSError, data: ECR.Types.StartLifecyclePolicyPreviewResponse) => void): Request<ECR.Types.StartLifecyclePolicyPreviewResponse, AWSError>;
/**
* Uploads an image layer part to Amazon ECR. This operation is used by the Amazon ECR proxy, and it is not intended for general use by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.
*/
uploadLayerPart(params: ECR.Types.UploadLayerPartRequest, callback?: (err: AWSError, data: ECR.Types.UploadLayerPartResponse) => void): Request<ECR.Types.UploadLayerPartResponse, AWSError>;
/**
* Uploads an image layer part to Amazon ECR. This operation is used by the Amazon ECR proxy, and it is not intended for general use by customers for pulling and pushing images. In most cases, you should use the docker CLI to pull, tag, and push images.
*/
uploadLayerPart(callback?: (err: AWSError, data: ECR.Types.UploadLayerPartResponse) => void): Request<ECR.Types.UploadLayerPartResponse, AWSError>;
}
declare namespace ECR {
export type Arn = string;
export interface AuthorizationData {
/**
* A base64-encoded string that contains authorization data for the specified Amazon ECR registry. When the string is decoded, it is presented in the format user:password for private registry authentication using docker login.
*/
authorizationToken?: Base64;
/**
* The Unix time in seconds and milliseconds when the authorization token expires. Authorization tokens are valid for 12 hours.
*/
expiresAt?: ExpirationTimestamp;
/**
* The registry URL to use for this authorization token in a docker login command. The Amazon ECR registry URL format is https://aws_account_id.dkr.ecr.region.amazonaws.com. For example, https://012345678910.dkr.ecr.us-east-1.amazonaws.com..
*/
proxyEndpoint?: ProxyEndpoint;
}
export type AuthorizationDataList = AuthorizationData[];
export type Base64 = string;
export interface BatchCheckLayerAvailabilityRequest {
/**
* The AWS account ID associated with the registry that contains the image layers to check. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository that is associated with the image layers to check.
*/
repositoryName: RepositoryName;
/**
* The digests of the image layers to check.
*/
layerDigests: BatchedOperationLayerDigestList;
}
export interface BatchCheckLayerAvailabilityResponse {
/**
* A list of image layer objects corresponding to the image layer references in the request.
*/
layers?: LayerList;
/**
* Any failures associated with the call.
*/
failures?: LayerFailureList;
}
export interface BatchDeleteImageRequest {
/**
* The AWS account ID associated with the registry that contains the image to delete. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The repository that contains the image to delete.
*/
repositoryName: RepositoryName;
/**
* A list of image ID references that correspond to images to delete. The format of the imageIds reference is imageTag=tag or imageDigest=digest.
*/
imageIds: ImageIdentifierList;
}
export interface BatchDeleteImageResponse {
/**
* The image IDs of the deleted images.
*/
imageIds?: ImageIdentifierList;
/**
* Any failures associated with the call.
*/
failures?: ImageFailureList;
}
export interface BatchGetImageRequest {
/**
* The AWS account ID associated with the registry that contains the images to describe. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The repository that contains the images to describe.
*/
repositoryName: RepositoryName;
/**
* A list of image ID references that correspond to images to describe. The format of the imageIds reference is imageTag=tag or imageDigest=digest.
*/
imageIds: ImageIdentifierList;
/**
* The accepted media types for the request. Valid values: application/vnd.docker.distribution.manifest.v1+json | application/vnd.docker.distribution.manifest.v2+json | application/vnd.oci.image.manifest.v1+json
*/
acceptedMediaTypes?: MediaTypeList;
}
export interface BatchGetImageResponse {
/**
* A list of image objects corresponding to the image references in the request.
*/
images?: ImageList;
/**
* Any failures associated with the call.
*/
failures?: ImageFailureList;
}
export type BatchedOperationLayerDigest = string;
export type BatchedOperationLayerDigestList = BatchedOperationLayerDigest[];
export interface CompleteLayerUploadRequest {
/**
* The AWS account ID associated with the registry to which to upload layers. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository to associate with the image layer.
*/
repositoryName: RepositoryName;
/**
* The upload ID from a previous InitiateLayerUpload operation to associate with the image layer.
*/
uploadId: UploadId;
/**
* The sha256 digest of the image layer.
*/
layerDigests: LayerDigestList;
}
export interface CompleteLayerUploadResponse {
/**
* The registry ID associated with the request.
*/
registryId?: RegistryId;
/**
* The repository name associated with the request.
*/
repositoryName?: RepositoryName;
/**
* The upload ID associated with the layer.
*/
uploadId?: UploadId;
/**
* The sha256 digest of the image layer.
*/
layerDigest?: LayerDigest;
}
export interface CreateRepositoryRequest {
/**
* The name to use for the repository. The repository name may be specified on its own (such as nginx-web-app) or it can be prepended with a namespace to group the repository into a category (such as project-a/nginx-web-app).
*/
repositoryName: RepositoryName;
}
export interface CreateRepositoryResponse {
/**
* The repository that was created.
*/
repository?: Repository;
}
export type CreationTimestamp = Date;
export interface DeleteLifecyclePolicyRequest {
/**
* The AWS account ID associated with the registry that contains the repository. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository.
*/
repositoryName: RepositoryName;
}
export interface DeleteLifecyclePolicyResponse {
/**
* The registry ID associated with the request.
*/
registryId?: RegistryId;
/**
* The repository name associated with the request.
*/
repositoryName?: RepositoryName;
/**
* The JSON lifecycle policy text.
*/
lifecyclePolicyText?: LifecyclePolicyText;
/**
* The time stamp of the last time that the lifecycle policy was run.
*/
lastEvaluatedAt?: EvaluationTimestamp;
}
export interface DeleteRepositoryPolicyRequest {
/**
* The AWS account ID associated with the registry that contains the repository policy to delete. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository that is associated with the repository policy to delete.
*/
repositoryName: RepositoryName;
}
export interface DeleteRepositoryPolicyResponse {
/**
* The registry ID associated with the request.
*/
registryId?: RegistryId;
/**
* The repository name associated with the request.
*/
repositoryName?: RepositoryName;
/**
* The JSON repository policy that was deleted from the repository.
*/
policyText?: RepositoryPolicyText;
}
export interface DeleteRepositoryRequest {
/**
* The AWS account ID associated with the registry that contains the repository to delete. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository to delete.
*/
repositoryName: RepositoryName;
/**
* If a repository contains images, forces the deletion.
*/
force?: ForceFlag;
}
export interface DeleteRepositoryResponse {
/**
* The repository that was deleted.
*/
repository?: Repository;
}
export interface DescribeImagesFilter {
/**
* The tag status with which to filter your DescribeImages results. You can filter results based on whether they are TAGGED or UNTAGGED.
*/
tagStatus?: TagStatus;
}
export interface DescribeImagesRequest {
/**
* The AWS account ID associated with the registry that contains the repository in which to describe images. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* A list of repositories to describe. If this parameter is omitted, then all repositories in a registry are described.
*/
repositoryName: RepositoryName;
/**
* The list of image IDs for the requested repository.
*/
imageIds?: ImageIdentifierList;
/**
* The nextToken value returned from a previous paginated DescribeImages request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return. This option cannot be used when you specify images with imageIds.
*/
nextToken?: NextToken;
/**
* The maximum number of repository results returned by DescribeImages in paginated output. When this parameter is used, DescribeImages only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeImages request with the returned nextToken value. This value can be between 1 and 100. If this parameter is not used, then DescribeImages returns up to 100 results and a nextToken value, if applicable. This option cannot be used when you specify images with imageIds.
*/
maxResults?: MaxResults;
/**
* The filter key and value with which to filter your DescribeImages results.
*/
filter?: DescribeImagesFilter;
}
export interface DescribeImagesResponse {
/**
* A list of ImageDetail objects that contain data about the image.
*/
imageDetails?: ImageDetailList;
/**
* The nextToken value to include in a future DescribeImages request. When the results of a DescribeImages request exceed maxResults, this value can be used to retrieve the next page of results. This value is null when there are no more results to return.
*/
nextToken?: NextToken;
}
export interface DescribeRepositoriesRequest {
/**
* The AWS account ID associated with the registry that contains the repositories to be described. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* A list of repositories to describe. If this parameter is omitted, then all repositories in a registry are described.
*/
repositoryNames?: RepositoryNameList;
/**
* The nextToken value returned from a previous paginated DescribeRepositories request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return. This option cannot be used when you specify repositories with repositoryNames. This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and not for other programmatic purposes.
*/
nextToken?: NextToken;
/**
* The maximum number of repository results returned by DescribeRepositories in paginated output. When this parameter is used, DescribeRepositories only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeRepositories request with the returned nextToken value. This value can be between 1 and 100. If this parameter is not used, then DescribeRepositories returns up to 100 results and a nextToken value, if applicable. This option cannot be used when you specify repositories with repositoryNames.
*/
maxResults?: MaxResults;
}
export interface DescribeRepositoriesResponse {
/**
* A list of repository objects corresponding to valid repositories.
*/
repositories?: RepositoryList;
/**
* The nextToken value to include in a future DescribeRepositories request. When the results of a DescribeRepositories request exceed maxResults, this value can be used to retrieve the next page of results. This value is null when there are no more results to return.
*/
nextToken?: NextToken;
}
export type EvaluationTimestamp = Date;
export type ExceptionMessage = string;
export type ExpirationTimestamp = Date;
export type ForceFlag = boolean;
export type GetAuthorizationTokenRegistryIdList = RegistryId[];
export interface GetAuthorizationTokenRequest {
/**
* A list of AWS account IDs that are associated with the registries for which to get authorization tokens. If you do not specify a registry, the default registry is assumed.
*/
registryIds?: GetAuthorizationTokenRegistryIdList;
}
export interface GetAuthorizationTokenResponse {
/**
* A list of authorization token data objects that correspond to the registryIds values in the request.
*/
authorizationData?: AuthorizationDataList;
}
export interface GetDownloadUrlForLayerRequest {
/**
* The AWS account ID associated with the registry that contains the image layer to download. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository that is associated with the image layer to download.
*/
repositoryName: RepositoryName;
/**
* The digest of the image layer to download.
*/
layerDigest: LayerDigest;
}
export interface GetDownloadUrlForLayerResponse {
/**
* The pre-signed Amazon S3 download URL for the requested layer.
*/
downloadUrl?: Url;
/**
* The digest of the image layer to download.
*/
layerDigest?: LayerDigest;
}
export interface GetLifecyclePolicyPreviewRequest {
/**
* The AWS account ID associated with the registry that contains the repository. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository.
*/
repositoryName: RepositoryName;
/**
* The list of imageIDs to be included.
*/
imageIds?: ImageIdentifierList;
/**
* The nextToken value returned from a previous paginated
 GetLifecyclePolicyPreviewRequest request where maxResults was used and the
 results exceeded the value of that parameter. Pagination continues from the end of the
 previous results that returned the nextToken value. This value is
 null when there are no more results to return. This option cannot be used when you specify images with imageIds.
*/
nextToken?: NextToken;
/**
* The maximum number of repository results returned by GetLifecyclePolicyPreviewRequest in
 paginated output. When this parameter is used, GetLifecyclePolicyPreviewRequest only returns
 maxResults results in a single page along with a nextToken
 response element. The remaining results of the initial request can be seen by sending
 another GetLifecyclePolicyPreviewRequest request with the returned nextToken
 value. This value can be between 1 and 100. If this
 parameter is not used, then GetLifecyclePolicyPreviewRequest returns up to
 100 results and a nextToken value, if
 applicable. This option cannot be used when you specify images with imageIds.
*/
maxResults?: MaxResults;
/**
* An optional parameter that filters results based on image tag status and all tags, if tagged.
*/
filter?: LifecyclePolicyPreviewFilter;
}
export interface GetLifecyclePolicyPreviewResponse {
/**
* The registry ID associated with the request.
*/
registryId?: RegistryId;
/**
* The repository name associated with the request.
*/
repositoryName?: RepositoryName;
/**
* The JSON lifecycle policy text.
*/
lifecyclePolicyText?: LifecyclePolicyText;
/**
* The status of the lifecycle policy preview request.
*/
status?: LifecyclePolicyPreviewStatus;
/**
* The nextToken value to include in a future GetLifecyclePolicyPreview request. When the results of a GetLifecyclePolicyPreview request exceed maxResults, this value can be used to retrieve the next page of results. This value is null when there are no more results to return.
*/
nextToken?: NextToken;
/**
* The results of the lifecycle policy preview request.
*/
previewResults?: LifecyclePolicyPreviewResultList;
/**
* The list of images that is returned as a result of the action.
*/
summary?: LifecyclePolicyPreviewSummary;
}
export interface GetLifecyclePolicyRequest {
/**
* The AWS account ID associated with the registry that contains the repository. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository.
*/
repositoryName: RepositoryName;
}
export interface GetLifecyclePolicyResponse {
/**
* The registry ID associated with the request.
*/
registryId?: RegistryId;
/**
* The repository name associated with the request.
*/
repositoryName?: RepositoryName;
/**
* The JSON lifecycle policy text.
*/
lifecyclePolicyText?: LifecyclePolicyText;
/**
* The time stamp of the last time that the lifecycle policy was run.
*/
lastEvaluatedAt?: EvaluationTimestamp;
}
export interface GetRepositoryPolicyRequest {
/**
* The AWS account ID associated with the registry that contains the repository. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository with the policy to retrieve.
*/
repositoryName: RepositoryName;
}
export interface GetRepositoryPolicyResponse {
/**
* The registry ID associated with the request.
*/
registryId?: RegistryId;
/**
* The repository name associated with the request.
*/
repositoryName?: RepositoryName;
/**
* The JSON repository policy text associated with the repository.
*/
policyText?: RepositoryPolicyText;
}
export interface Image {
/**
* The AWS account ID associated with the registry containing the image.
*/
registryId?: RegistryId;
/**
* The name of the repository associated with the image.
*/
repositoryName?: RepositoryName;
/**
* An object containing the image tag and image digest associated with an image.
*/
imageId?: ImageIdentifier;
/**
* The image manifest associated with the image.
*/
imageManifest?: ImageManifest;
}
export type ImageActionType = "EXPIRE"|string;
export type ImageCount = number;
export interface ImageDetail {
/**
* The AWS account ID associated with the registry to which this image belongs.
*/
registryId?: RegistryId;
/**
* The name of the repository to which this image belongs.
*/
repositoryName?: RepositoryName;
/**
* The sha256 digest of the image manifest.
*/
imageDigest?: ImageDigest;
/**
* The list of tags associated with this image.
*/
imageTags?: ImageTagList;
/**
* The size, in bytes, of the image in the repository. Beginning with Docker version 1.9, the Docker client compresses image layers before pushing them to a V2 Docker registry. The output of the docker images command shows the uncompressed image size, so it may return a larger image size than the image sizes returned by DescribeImages.
*/
imageSizeInBytes?: ImageSizeInBytes;
/**
* The date and time, expressed in standard JavaScript date format, at which the current image was pushed to the repository.
*/
imagePushedAt?: PushTimestamp;
}
export type ImageDetailList = ImageDetail[];
export type ImageDigest = string;
export interface ImageFailure {
/**
* The image ID associated with the failure.
*/
imageId?: ImageIdentifier;
/**
* The code associated with the failure.
*/
failureCode?: ImageFailureCode;
/**
* The reason for the failure.
*/
failureReason?: ImageFailureReason;
}
export type ImageFailureCode = "InvalidImageDigest"|"InvalidImageTag"|"ImageTagDoesNotMatchDigest"|"ImageNotFound"|"MissingDigestAndTag"|string;
export type ImageFailureList = ImageFailure[];
export type ImageFailureReason = string;
export interface ImageIdentifier {
/**
* The sha256 digest of the image manifest.
*/
imageDigest?: ImageDigest;
/**
* The tag used for the image.
*/
imageTag?: ImageTag;
}
export type ImageIdentifierList = ImageIdentifier[];
export type ImageList = Image[];
export type ImageManifest = string;
export type ImageSizeInBytes = number;
export type ImageTag = string;
export type ImageTagList = ImageTag[];
export interface InitiateLayerUploadRequest {
/**
* The AWS account ID associated with the registry to which you intend to upload layers. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository to which you intend to upload layers.
*/
repositoryName: RepositoryName;
}
export interface InitiateLayerUploadResponse {
/**
* The upload ID for the layer upload. This parameter is passed to further UploadLayerPart and CompleteLayerUpload operations.
*/
uploadId?: UploadId;
/**
* The size, in bytes, that Amazon ECR expects future layer part uploads to be.
*/
partSize?: PartSize;
}
export interface Layer {
/**
* The sha256 digest of the image layer.
*/
layerDigest?: LayerDigest;
/**
* The availability status of the image layer.
*/
layerAvailability?: LayerAvailability;
/**
* The size, in bytes, of the image layer.
*/
layerSize?: LayerSizeInBytes;
/**
* The media type of the layer, such as application/vnd.docker.image.rootfs.diff.tar.gzip or application/vnd.oci.image.layer.v1.tar+gzip.
*/
mediaType?: MediaType;
}
export type LayerAvailability = "AVAILABLE"|"UNAVAILABLE"|string;
export type LayerDigest = string;
export type LayerDigestList = LayerDigest[];
export interface LayerFailure {
/**
* The layer digest associated with the failure.
*/
layerDigest?: BatchedOperationLayerDigest;
/**
* The failure code associated with the failure.
*/
failureCode?: LayerFailureCode;
/**
* The reason for the failure.
*/
failureReason?: LayerFailureReason;
}
export type LayerFailureCode = "InvalidLayerDigest"|"MissingLayerDigest"|string;
export type LayerFailureList = LayerFailure[];
export type LayerFailureReason = string;
export type LayerList = Layer[];
export type LayerPartBlob = Buffer|Uint8Array|Blob|string;
export type LayerSizeInBytes = number;
export interface LifecyclePolicyPreviewFilter {
/**
* The tag status of the image.
*/
tagStatus?: TagStatus;
}
export interface LifecyclePolicyPreviewResult {
/**
* The list of tags associated with this image.
*/
imageTags?: ImageTagList;
/**
* The sha256 digest of the image manifest.
*/
imageDigest?: ImageDigest;
/**
* The date and time, expressed in standard JavaScript date format, at which the current image was pushed to the repository.
*/
imagePushedAt?: PushTimestamp;
/**
* The type of action to be taken.
*/
action?: LifecyclePolicyRuleAction;
/**
* The priority of the applied rule.
*/
appliedRulePriority?: LifecyclePolicyRulePriority;
}
export type LifecyclePolicyPreviewResultList = LifecyclePolicyPreviewResult[];
export type LifecyclePolicyPreviewStatus = "IN_PROGRESS"|"COMPLETE"|"EXPIRED"|"FAILED"|string;
export interface LifecyclePolicyPreviewSummary {
/**
* The number of expiring images.
*/
expiringImageTotalCount?: ImageCount;
}
export interface LifecyclePolicyRuleAction {
/**
* The type of action to be taken.
*/
type?: ImageActionType;
}
export type LifecyclePolicyRulePriority = number;
export type LifecyclePolicyText = string;
export interface ListImagesFilter {
/**
* The tag status with which to filter your ListImages results. You can filter results based on whether they are TAGGED or UNTAGGED.
*/
tagStatus?: TagStatus;
}
export interface ListImagesRequest {
/**
* The AWS account ID associated with the registry that contains the repository in which to list images. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The repository with image IDs to be listed.
*/
repositoryName: RepositoryName;
/**
* The nextToken value returned from a previous paginated ListImages request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return. This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and not for other programmatic purposes.
*/
nextToken?: NextToken;
/**
* The maximum number of image results returned by ListImages in paginated output. When this parameter is used, ListImages only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another ListImages request with the returned nextToken value. This value can be between 1 and 100. If this parameter is not used, then ListImages returns up to 100 results and a nextToken value, if applicable.
*/
maxResults?: MaxResults;
/**
* The filter key and value with which to filter your ListImages results.
*/
filter?: ListImagesFilter;
}
export interface ListImagesResponse {
/**
* The list of image IDs for the requested repository.
*/
imageIds?: ImageIdentifierList;
/**
* The nextToken value to include in a future ListImages request. When the results of a ListImages request exceed maxResults, this value can be used to retrieve the next page of results. This value is null when there are no more results to return.
*/
nextToken?: NextToken;
}
export type MaxResults = number;
export type MediaType = string;
export type MediaTypeList = MediaType[];
export type NextToken = string;
export type PartSize = number;
export type ProxyEndpoint = string;
export type PushTimestamp = Date;
export interface PutImageRequest {
/**
* The AWS account ID associated with the registry that contains the repository in which to put the image. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository in which to put the image.
*/
repositoryName: RepositoryName;
/**
* The image manifest corresponding to the image to be uploaded.
*/
imageManifest: ImageManifest;
/**
* The tag to associate with the image. This parameter is required for images that use the Docker Image Manifest V2 Schema 2 or OCI formats.
*/
imageTag?: ImageTag;
}
export interface PutImageResponse {
/**
* Details of the image uploaded.
*/
image?: Image;
}
export interface PutLifecyclePolicyRequest {
/**
* The AWS account ID associated with the registry that contains the repository. If you do
 not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository to receive the policy.
*/
repositoryName: RepositoryName;
/**
* The JSON repository policy text to apply to the repository.
*/
lifecyclePolicyText: LifecyclePolicyText;
}
export interface PutLifecyclePolicyResponse {
/**
* The registry ID associated with the request.
*/
registryId?: RegistryId;
/**
* The repository name associated with the request.
*/
repositoryName?: RepositoryName;
/**
* The JSON repository policy text.
*/
lifecyclePolicyText?: LifecyclePolicyText;
}
export type RegistryId = string;
export interface Repository {
/**
* The Amazon Resource Name (ARN) that identifies the repository. The ARN contains the arn:aws:ecr namespace, followed by the region of the repository, AWS account ID of the repository owner, repository namespace, and repository name. For example, arn:aws:ecr:region:012345678910:repository/test.
*/
repositoryArn?: Arn;
/**
* The AWS account ID associated with the registry that contains the repository.
*/
registryId?: RegistryId;
/**
* The name of the repository.
*/
repositoryName?: RepositoryName;
/**
* The URI for the repository. You can use this URI for Docker push or pull operations.
*/
repositoryUri?: Url;
/**
* The date and time, in JavaScript date format, when the repository was created.
*/
createdAt?: CreationTimestamp;
}
export type RepositoryList = Repository[];
export type RepositoryName = string;
export type RepositoryNameList = RepositoryName[];
export type RepositoryPolicyText = string;
export interface SetRepositoryPolicyRequest {
/**
* The AWS account ID associated with the registry that contains the repository. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository to receive the policy.
*/
repositoryName: RepositoryName;
/**
* The JSON repository policy text to apply to the repository.
*/
policyText: RepositoryPolicyText;
/**
* If the policy you are attempting to set on a repository policy would prevent you from setting another policy in the future, you must force the SetRepositoryPolicy operation. This is intended to prevent accidental repository lock outs.
*/
force?: ForceFlag;
}
export interface SetRepositoryPolicyResponse {
/**
* The registry ID associated with the request.
*/
registryId?: RegistryId;
/**
* The repository name associated with the request.
*/
repositoryName?: RepositoryName;
/**
* The JSON repository policy text applied to the repository.
*/
policyText?: RepositoryPolicyText;
}
export interface StartLifecyclePolicyPreviewRequest {
/**
* The AWS account ID associated with the registry that contains the repository. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository to be evaluated.
*/
repositoryName: RepositoryName;
/**
* The policy to be evaluated against. If you do not specify a policy, the current policy for the repository is used.
*/
lifecyclePolicyText?: LifecyclePolicyText;
}
export interface StartLifecyclePolicyPreviewResponse {
/**
* The registry ID associated with the request.
*/
registryId?: RegistryId;
/**
* The repository name associated with the request.
*/
repositoryName?: RepositoryName;
/**
* The JSON repository policy text.
*/
lifecyclePolicyText?: LifecyclePolicyText;
/**
* The status of the lifecycle policy preview request.
*/
status?: LifecyclePolicyPreviewStatus;
}
export type TagStatus = "TAGGED"|"UNTAGGED"|string;
export type UploadId = string;
export interface UploadLayerPartRequest {
/**
* The AWS account ID associated with the registry to which you are uploading layer parts. If you do not specify a registry, the default registry is assumed.
*/
registryId?: RegistryId;
/**
* The name of the repository to which you are uploading layer parts.
*/
repositoryName: RepositoryName;
/**
* The upload ID from a previous InitiateLayerUpload operation to associate with the layer part upload.
*/
uploadId: UploadId;
/**
* The integer value of the first byte of the layer part.
*/
partFirstByte: PartSize;
/**
* The integer value of the last byte of the layer part.
*/
partLastByte: PartSize;
/**
* The base64-encoded layer part payload.
*/
layerPartBlob: LayerPartBlob;
}
export interface UploadLayerPartResponse {
/**
* The registry ID associated with the request.
*/
registryId?: RegistryId;
/**
* The repository name associated with the request.
*/
repositoryName?: RepositoryName;
/**
* The upload ID associated with the request.
*/
uploadId?: UploadId;
/**
* The integer value of the last byte received in the request.
*/
lastByteReceived?: PartSize;
}
export type Url = string;
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2015-09-21"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the ECR client.
*/
export import Types = ECR;
}
export = ECR; | the_stack |
import { alert } from 'store/alert';
import * as rosterOperations from 'store/roster/operations';
import { onPost, onPut, onDelete } from 'store/rest/RestTestUtils';
import { Shift } from 'domain/Shift';
import moment from 'moment';
import { serializeLocalDateTime } from 'store/rest/DataSerialization';
import { HardMediumSoftScore } from 'domain/HardMediumSoftScore';
import { createIdMapFromList } from 'util/ImmutableCollectionOperations';
import { shiftAdapter, KindaShiftView, kindaShiftViewAdapter } from './KindaShiftView';
import { shiftOperations } from './index';
import { AppState } from '../types';
import { mockStore } from '../mockStore';
describe('Shift operations', () => {
it('should dispatch actions and call client on addShift', async () => {
const { store, client } = mockStore(state);
const tenantId = store.getState().tenantData.currentTenantId;
const shiftStartTime = moment('2018-01-01T09:00').toDate();
const shiftEndTime = moment('2018-01-01T12:00').toDate();
const mockRefreshShiftRoster = jest.spyOn(rosterOperations, 'refreshShiftRoster');
const addedShift: Shift = {
tenantId,
startDateTime: shiftStartTime,
endDateTime: shiftEndTime,
spot: {
tenantId: 0,
id: 20,
name: 'Spot',
requiredSkillSet: [],
},
requiredSkillSet: [],
originalEmployee: null,
employee: null,
rotationEmployee: null,
pinnedByUser: true,
};
onPost(`/tenant/${tenantId}/shift/add`, shiftAdapter(addedShift), shiftAdapter(addedShift));
await store.dispatch(shiftOperations.addShift(addedShift));
expect(client.post).toBeCalled();
expect(client.post).toBeCalledWith(`/tenant/${tenantId}/shift/add`, shiftAdapter(addedShift));
expect(mockRefreshShiftRoster).toBeCalled();
expect(store.getActions()).toEqual([]);
});
it('should dispatch actions and call client on a successful delete shift', async () => {
const { store, client } = mockStore(state);
const tenantId = store.getState().tenantData.currentTenantId;
const shiftStartTime = moment('2018-01-01T09:00').toDate();
const shiftEndTime = moment('2018-01-01T12:00').toDate();
const mockRefreshShiftRoster = jest.spyOn(rosterOperations, 'refreshShiftRoster');
const deletedShift: Shift = {
tenantId,
startDateTime: shiftStartTime,
endDateTime: shiftEndTime,
id: 10,
version: 0,
spot: {
tenantId: 0,
id: 20,
name: 'Spot',
requiredSkillSet: [],
},
requiredSkillSet: [],
originalEmployee: null,
employee: null,
rotationEmployee: null,
pinnedByUser: true,
};
onDelete(`/tenant/${tenantId}/shift/${deletedShift.id}`, true);
await store.dispatch(shiftOperations.removeShift(deletedShift));
expect(client.delete).toBeCalled();
expect(client.delete).toBeCalledWith(`/tenant/${tenantId}/shift/${deletedShift.id}`);
expect(mockRefreshShiftRoster).toBeCalled();
expect(store.getActions()).toEqual([]);
});
it('should call client but not dispatch actions on a failed delete shift', async () => {
const { store, client } = mockStore(state);
const tenantId = store.getState().tenantData.currentTenantId;
const shiftStartTime = moment('2018-01-01T09:00').toDate();
const shiftEndTime = moment('2018-01-01T12:00').toDate();
const mockRefreshShiftRoster = jest.spyOn(rosterOperations, 'refreshShiftRoster');
const deletedShift: Shift = {
tenantId,
startDateTime: shiftStartTime,
endDateTime: shiftEndTime,
id: 10,
version: 0,
spot: {
tenantId: 0,
id: 20,
name: 'Spot',
requiredSkillSet: [],
},
requiredSkillSet: [],
originalEmployee: null,
employee: null,
rotationEmployee: null,
pinnedByUser: true,
};
onDelete(`/tenant/${tenantId}/shift/${deletedShift.id}`, false);
await store.dispatch(shiftOperations.removeShift(deletedShift));
expect(client.delete).toBeCalled();
expect(client.delete).toBeCalledWith(`/tenant/${tenantId}/shift/${deletedShift.id}`);
expect(mockRefreshShiftRoster).not.toBeCalled();
expect(store.getActions()).toEqual([
alert.showErrorMessage('removeShiftError', {
id: deletedShift.id,
startDateTime: moment(deletedShift.startDateTime).format('LLL'),
endDateTime: moment(deletedShift.endDateTime).format('LLL'),
}),
]);
});
it('should dispatch actions and call client on updateShift', async () => {
const { store, client } = mockStore(state);
const tenantId = store.getState().tenantData.currentTenantId;
const shiftStartTime = moment('2018-01-01T09:00').toDate();
const shiftEndTime = moment('2018-01-01T12:00').toDate();
const mockRefreshShiftRoster = jest.spyOn(rosterOperations, 'refreshShiftRoster');
const updatedShift: Shift = {
tenantId,
id: 11,
version: 0,
startDateTime: shiftStartTime,
endDateTime: shiftEndTime,
spot: {
tenantId: 0,
id: 20,
name: 'Spot',
requiredSkillSet: [],
},
requiredSkillSet: [],
originalEmployee: null,
employee: null,
rotationEmployee: null,
pinnedByUser: true,
};
const updatedShiftWithUpdatedVersion: Shift = {
...updatedShift,
version: 1,
};
onPut(`/tenant/${tenantId}/shift/update`, shiftAdapter(updatedShift), shiftAdapter(updatedShiftWithUpdatedVersion));
await store.dispatch(shiftOperations.updateShift(updatedShift));
expect(client.put).toBeCalled();
expect(client.put).toBeCalledWith(`/tenant/${tenantId}/shift/update`, shiftAdapter(updatedShift));
expect(mockRefreshShiftRoster).toBeCalled();
});
});
describe('shift adapters', () => {
it('shiftAdapter should convert a Shift to a KindaShiftView', () => {
const shiftStartTime = moment('2018-01-01T09:00').toDate();
const shiftEndTime = moment('2018-01-01T12:00').toDate();
const shift: Shift = {
tenantId: 0,
id: 11,
version: 0,
startDateTime: shiftStartTime,
endDateTime: shiftEndTime,
spot: {
tenantId: 0,
id: 20,
name: 'Spot',
requiredSkillSet: [],
},
requiredSkillSet: [],
originalEmployee: null,
employee: {
tenantId: 10,
id: 20,
version: 0,
name: 'Bill',
contract: {
tenantId: 0,
id: 100,
version: 0,
name: 'Contract',
maximumMinutesPerDay: null,
maximumMinutesPerWeek: null,
maximumMinutesPerMonth: null,
maximumMinutesPerYear: null,
},
skillProficiencySet: [],
shortId: 'B',
color: '#FFFFFF',
},
rotationEmployee: null,
pinnedByUser: true,
indictmentScore: { hardScore: 0, mediumScore: 0, softScore: 0 },
desiredTimeslotForEmployeeRewardList: [],
shiftEmployeeConflictList: [],
};
expect(shiftAdapter(shift)).toEqual({
tenantId: 0,
id: 11,
version: 0,
startDateTime: serializeLocalDateTime(shiftStartTime),
endDateTime: serializeLocalDateTime(shiftEndTime),
spotId: 20,
requiredSkillSetIdList: [],
originalEmployeeId: null,
employeeId: 20,
rotationEmployeeId: null,
pinnedByUser: true,
});
});
it('kindaShiftAdapter should convert a KindaShiftView to a ShiftView', () => {
const shiftStartTime = moment('2018-01-01T09:00').toDate();
const shiftEndTime = moment('2018-01-01T12:00').toDate();
const kindaShiftView: KindaShiftView = {
tenantId: 0,
id: 11,
version: 0,
startDateTime: serializeLocalDateTime(shiftStartTime),
endDateTime: serializeLocalDateTime(shiftEndTime),
spotId: 20,
requiredSkillSetIdList: [],
originalEmployeeId: null,
employeeId: null,
rotationEmployeeId: null,
pinnedByUser: true,
indictmentScore: '5hard/0medium/-14soft',
// @ts-ignore
unassignedShiftPenaltyList: [{
score: '5hard/0medium/-14soft' as unknown as HardMediumSoftScore,
shift: {
tenantId: 0,
id: 11,
version: 0,
startDateTime: shiftStartTime,
endDateTime: shiftEndTime,
spot: {
tenantId: 0,
id: 20,
version: 0,
name: 'Spot',
requiredSkillSet: [],
},
requiredSkillSet: [],
originalEmployee: null,
employee: null,
rotationEmployee: null,
pinnedByUser: true,
},
}],
};
expect(kindaShiftViewAdapter(kindaShiftView)).toEqual({
tenantId: 0,
id: 11,
version: 0,
startDateTime: shiftStartTime,
endDateTime: shiftEndTime,
spotId: 20,
requiredSkillSetIdList: [],
originalEmployeeId: null,
employeeId: null,
rotationEmployeeId: null,
pinnedByUser: true,
indictmentScore: { hardScore: 5, mediumScore: 0, softScore: -14 },
// @ts-ignore
unassignedShiftPenaltyList: [{
score: { hardScore: 5, mediumScore: 0, softScore: -14 },
shift: {
tenantId: 0,
id: 11,
version: 0,
startDateTime: shiftStartTime,
endDateTime: shiftEndTime,
spot: {
tenantId: 0,
id: 20,
version: 0,
name: 'Spot',
requiredSkillSet: [],
},
requiredSkillSet: [],
originalEmployee: null,
employee: null,
rotationEmployee: null,
pinnedByUser: true,
},
}],
});
});
});
const state: Partial<AppState> = {
skillList: {
isLoading: false,
skillMapById: createIdMapFromList([
{
tenantId: 0,
id: 1234,
version: 0,
name: 'Skill 2',
},
{
tenantId: 0,
id: 2312,
version: 1,
name: 'Skill 3',
},
]),
},
}; | the_stack |
import * as React from 'react';
import type { LatLng } from 'leaflet';
import { MapContainer, Marker, TileLayer, useMapEvents } from 'react-leaflet';
import classnames from 'classnames';
import axios from 'axios';
import produce from 'immer';
import type { LatLngTuple, Venue, VenueLocation } from 'types/venues';
import config from 'config';
import { MapPin, ThumbsUp } from 'react-feather';
import LoadingSpinner from 'views/components/LoadingSpinner';
import { markerIcon } from 'views/components/map/icons';
import ExpandMap from 'views/components/map/ExpandMap';
import MapViewportChanger from 'views/components/map/MapViewportChanger';
import { isIOS } from 'bootstrapping/browser';
import mapStyles from 'views/components/map/LocationMap.scss';
import { captureException } from 'utils/error';
import styles from './ImproveVenueForm.scss';
/**
* Calls `onLocationSelected` whenever the map is dragged or clicked on.
*
* This component exists as passing `eventHandlers` to `MapContainer` has no
* effect. See: https://github.com/PaulLeCam/react-leaflet/issues/779
*/
const MapLocationSelector: React.FC<{
onLocationSelected: (latlng: LatLng, isFinal: boolean) => void;
}> = ({ onLocationSelected }) => {
const map = useMapEvents({
drag: () => onLocationSelected(map.getCenter(), false),
dragend: () => onLocationSelected(map.getCenter(), true),
click: ({ latlng }) => onLocationSelected(latlng, true),
});
return null;
};
type Props = {
venue: Venue;
existingLocation?: VenueLocation | null;
onBack?: () => void;
};
type State = {
// Form data
reporterEmail: string;
roomName: string;
floor: number;
location: LatLngTuple;
// Form state
latlngUpdated: boolean;
submitting: boolean;
submitted: boolean;
isMapExpanded: boolean;
promptUpdateMap: boolean;
/**
* Viewport center.
*
* `center` is stored as a separate state because it may be animated
* separately from `location`. `center` may not be updated; use
* `map.getCenter` if possible.
*/
center: LatLng | LatLngTuple;
error?: Error;
};
const wellKnownLocations: Record<string, LatLngTuple> = {
'Central Library': [1.2966113099432135, 103.77322643995288],
UTown: [1.304448761575499, 103.77278119325639],
Science: [1.2964893900409042, 103.78065884113312],
Engineering: [1.3002873614041492, 103.77067700028421],
Computing: [1.2935772164129489, 103.7741592837536],
"Prince George's Park": [1.2909124430918655, 103.78115504980089],
'Bukit Timah Campus': [1.3189664358274156, 103.81760090589525],
};
export default class ImproveVenueForm extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props);
const { existingLocation } = props;
const locationInfo = {
roomName: '',
floor: 1,
location: wellKnownLocations['Central Library'],
};
// Make sure we copy only non-null values into the new location
if (existingLocation) {
locationInfo.roomName = existingLocation.roomName;
if (typeof existingLocation.floor === 'number') {
locationInfo.floor = existingLocation.floor;
}
if (existingLocation.location) {
locationInfo.location = [existingLocation.location.y, existingLocation.location.x];
}
}
this.state = {
center: locationInfo.location,
reporterEmail: '',
latlngUpdated: false,
submitting: false,
submitted: false,
isMapExpanded: false,
promptUpdateMap: false,
...locationInfo,
};
}
onSubmit = (evt: React.SyntheticEvent<HTMLFormElement>) => {
evt.preventDefault();
// Don't allow the user to submit without changing the latlng on the map
if (!this.state.latlngUpdated) {
// Shake the prompt a little to prompt the user to update the map
this.setState({ promptUpdateMap: true });
setTimeout(() => this.setState({ promptUpdateMap: false }), 500);
return;
}
this.setState({ submitting: true });
const { reporterEmail, roomName, location, floor } = this.state;
const { venue } = this.props;
axios
.post(config.venueFeedbackApi, {
venue,
reporterEmail,
floor,
latlng: location,
room: roomName,
})
.then(() => this.setState({ submitted: true }))
.catch((originalError) => {
const error = new Error(
`Error while submitting improve venue form - ${originalError.message}`,
);
captureException(error, { originalError });
this.setState({ error });
})
.then(() => this.setState({ submitting: false }));
};
onMapJump = (evt: React.SyntheticEvent<HTMLSelectElement>) => {
if (!(evt.target instanceof HTMLSelectElement)) return;
const location = wellKnownLocations[evt.target.value];
if (location) this.updateLocation(location);
};
geolocate = () => {
navigator.geolocation.getCurrentPosition((position) =>
this.updateLocation([position.coords.latitude, position.coords.longitude]),
);
};
updateLocation = (latlng: LatLng | LatLngTuple, updateViewport = true) => {
this.setState((state) =>
produce(state, (draft) => {
const latlngTuple: [number, number] = Array.isArray(latlng)
? latlng
: [latlng.lat, latlng.lng];
draft.location = latlngTuple;
draft.latlngUpdated = true;
if (updateViewport) {
draft.center = latlngTuple;
}
}),
);
};
render() {
const { location, reporterEmail, floor, roomName, isMapExpanded } = this.state;
if (this.state.submitted) {
return (
<div className={styles.submitted}>
<ThumbsUp />
<p>
Thank you for helping us improve NUSMods. If you have left your email, we will send you
a message when your update goes live!
</p>
</div>
);
}
if (this.state.submitting) {
return <LoadingSpinner />;
}
// HACK: There's an iOS bug that clips the expanded map around the modal,
// making it impossible to exit the expanded state. While we find a better
// solution for now we'll just hide the button
const showExpandMapBtn = !isIOS;
return (
<form className="form-row" onSubmit={this.onSubmit}>
{this.state.error && (
<div className="col-sm-12">
<div className="alert alert-warning">
There was a problem submitting your feedback. Please try again later.
</div>
</div>
)}
<div className="form-group col-sm-12">
<label htmlFor="improve-venue-email">Email (optional)</label>
<input
className="form-control"
id="improve-venue-email"
aria-describedby="improve-venue-email-help"
type="email"
placeholder="example@nusmods.com"
value={reporterEmail}
onChange={(evt) => this.setState({ reporterEmail: evt.target.value })}
/>
<small className="form-text text-muted" id="improve-venue-email-help">
This will be visible publicly. If you fill this we can contact you when your
contribution goes live.
</small>
</div>
<div className="form-group col-sm-7">
<label htmlFor="improve-venue-room">Room Name</label>
<input
className="form-control"
id="improve-venue-room"
type="text"
placeholder="eg. Seminar Room 2, Physics Lab 5"
value={roomName}
onChange={(evt) => this.setState({ roomName: evt.target.value })}
required
/>
</div>
<div className="form-group col-sm-5">
<label htmlFor="improve-venue-floor">What floor is this room on?</label>
<input
className="form-control"
id="improve-venue-floor"
aria-describedby="improve-venue-floor-help"
type="number"
step="1"
placeholder="eg. 1"
value={floor}
onChange={(evt) => {
const newFloor = parseInt(evt.target.value, 10);
if (!Number.isNaN(newFloor)) {
this.setState({ floor: newFloor });
}
}}
required
/>
<small className="form-text text-muted" id="improve-venue-floor-help">
Use negative numbers for basement floors
</small>
</div>
<div
className={classnames('col-sm-12', mapStyles.mapWrapper, {
[mapStyles.expanded]: isMapExpanded,
})}
>
<MapContainer className={mapStyles.map} center={this.state.center} zoom={18} maxZoom={18}>
<MapViewportChanger center={this.state.center} />
<MapLocationSelector onLocationSelected={this.updateLocation} />
<Marker
position={location}
icon={markerIcon}
eventHandlers={{
dragend: (evt) => this.updateLocation(evt.target.getLatLng()),
}}
draggable
autoPan
/>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{showExpandMapBtn && (
<ExpandMap
isExpanded={isMapExpanded}
onToggleExpand={() => this.setState({ isMapExpanded: !isMapExpanded })}
/>
)}
</MapContainer>
<select
className={classnames('form-control', styles.jumpSelect)}
onChange={this.onMapJump}
>
<option>Jump to...</option>
{Object.keys(wellKnownLocations).map((name) => (
<option key={name} value={name}>
{name}
</option>
))}
</select>
<small
className={classnames(styles.instructions, {
[styles.moved]: this.state.latlngUpdated,
[styles.shake]: this.state.promptUpdateMap,
})}
>
Move marker or map so that marker is pointing to {this.props.venue}
</small>
{'geolocation' in navigator && (
<button
className={classnames('btn btn-sm btn-secondary', styles.geolocate)}
title="Center on my location"
aria-label="Center on my location"
type="button"
onClick={this.geolocate}
>
<MapPin /> Use my location
</button>
)}
</div>
{showExpandMapBtn && (
<p className={styles.fullscreenTip}>
Tip: Open the map in fullscreen to easily edit the location
</p>
)}
<div className={classnames(styles.actions, 'col-sm-12')}>
{this.props.onBack && (
<button type="button" className="btn btn-lg btn-secondary" onClick={this.props.onBack}>
Back
</button>
)}
<button
className={classnames('btn btn-lg btn-primary', {
disabled: !this.state.latlngUpdated,
})}
type="submit"
>
Submit
</button>
</div>
</form>
);
}
} | the_stack |
import { mat2, mat4, vec3, vec4 } from 'gl-matrix';
import Point, { PointLike } from '../geo/point';
import { clamp, interpolate, wrap } from '../util';
import Aabb from '../utils/Aabb';
import Frustum from '../utils/primitives';
import EdgeInsets, { IPaddingOptions } from './edge_insets';
import LngLat from './lng_lat';
import LngLatBounds from './lng_lat_bounds';
import MercatorCoordinate, {
mercatorXfromLng,
mercatorYfromLat,
mercatorZfromAltitude,
} from './mercator';
export const EXTENT = 8192;
export default class Transform {
get minZoom(): number {
return this._minZoom;
}
set minZoom(zoom: number) {
if (this._minZoom === zoom) {
return;
}
this._minZoom = zoom;
this.zoom = Math.max(this.zoom, zoom);
}
get maxZoom(): number {
return this._maxZoom;
}
set maxZoom(zoom: number) {
if (this._maxZoom === zoom) {
return;
}
this._maxZoom = zoom;
this.zoom = Math.min(this.zoom, zoom);
}
get minPitch(): number {
return this._minPitch;
}
set minPitch(pitch: number) {
if (this._minPitch === pitch) {
return;
}
this._minPitch = pitch;
this._pitch = Math.max(this._pitch, pitch);
}
get maxPitch(): number {
return this._maxPitch;
}
set maxPitch(pitch: number) {
if (this._maxPitch === pitch) {
return;
}
this._maxPitch = pitch;
this._pitch = Math.min(this._pitch, pitch);
}
get renderWorldCopies(): boolean {
return this._renderWorldCopies;
}
set renderWorldCopies(renderWorldCopies: boolean) {
if (renderWorldCopies === undefined) {
renderWorldCopies = true;
} else if (renderWorldCopies === null) {
renderWorldCopies = false;
}
this._renderWorldCopies = renderWorldCopies;
}
get worldSize(): number {
return this.tileSize * this.scale;
}
get centerOffset(): Point {
return this.centerPoint._sub(this.size._div(2));
}
get size(): Point {
return new Point(this.width, this.height);
}
get bearing(): number {
return (-this.angle / Math.PI) * 180;
}
set bearing(bearing: number) {
const b = (-wrap(bearing, -180, 180) * Math.PI) / 180;
if (this.angle === b) {
return;
}
this.unmodified = false;
this.angle = b;
this.calcMatrices();
// 2x2 matrix for rotating points
this.rotationMatrix = mat2.create();
mat2.rotate(this.rotationMatrix, this.rotationMatrix, this.angle);
}
get pitch(): number {
return (this._pitch / Math.PI) * 180;
}
set pitch(pitch: number) {
const p = (clamp(pitch, this._minPitch, this._maxPitch) / 180) * Math.PI;
if (this._pitch === p) {
return;
}
this.unmodified = false;
this._pitch = p;
this.calcMatrices();
}
get fov(): number {
return (this._fov / Math.PI) * 180;
}
set fov(fov: number) {
fov = Math.max(0.01, Math.min(60, fov));
if (this._fov === fov) {
return;
}
this.unmodified = false;
this._fov = (fov / 180) * Math.PI;
this.calcMatrices();
}
get zoom(): number {
return this._zoom;
}
set zoom(zoom: number) {
const z = Math.min(Math.max(zoom, this._minZoom), this._maxZoom);
if (this._zoom === z) {
return;
}
this.unmodified = false;
this._zoom = z;
this.scale = this.zoomScale(z);
this.tileZoom = Math.floor(z);
this.zoomFraction = z - this.tileZoom;
this.constrain();
this.calcMatrices();
}
get center(): LngLat {
return this._center;
}
set center(center: LngLat) {
if (center.lat === this._center.lat && center.lng === this._center.lng) {
return;
}
this.unmodified = false;
this._center = center;
this.constrain();
this.calcMatrices();
}
get padding(): IPaddingOptions {
return this.edgeInsets.toJSON();
}
set padding(padding: IPaddingOptions) {
if (this.edgeInsets.equals(padding)) {
return;
}
this.unmodified = false;
// Update edge-insets inplace
this.edgeInsets.interpolate(this.edgeInsets, padding, 1);
this.calcMatrices();
}
/**
* The center of the screen in pixels with the top-left corner being (0,0)
* and +y axis pointing downwards. This accounts for padding.
*
* @readonly
* @type {Point}
* @memberof Transform
*/
get centerPoint(): Point {
return this.edgeInsets.getCenter(this.width, this.height);
}
get point(): Point {
return this.project(this.center);
}
public tileSize: number;
public tileZoom: number;
public lngRange?: [number, number];
public latRange?: [number, number];
public maxValidLatitude: number;
public scale: number;
public width: number;
public height: number;
public angle: number;
public rotationMatrix: mat2;
public pixelsToGLUnits: [number, number];
public cameraToCenterDistance: number;
public mercatorMatrix: mat4;
public projMatrix: mat4;
public invProjMatrix: mat4;
public alignedProjMatrix: mat4;
public pixelMatrix: mat4;
public pixelMatrixInverse: mat4;
public glCoordMatrix: mat4;
public labelPlaneMatrix: mat4;
// tslint:disable:variable-name
private _fov: number;
private _pitch: number;
private _zoom: number;
private _renderWorldCopies: boolean;
private _minZoom: number;
private _maxZoom: number;
private _minPitch: number;
private _maxPitch: number;
private _center: LngLat;
// tslint:enable
private zoomFraction: number;
private unmodified: boolean;
private edgeInsets: EdgeInsets;
private constraining: boolean;
private posMatrixCache: { [_: string]: Float32Array };
private alignedPosMatrixCache: { [_: string]: Float32Array };
constructor(
minZoom: number,
maxZoom: number,
minPitch: number,
maxPitch: number,
renderWorldCopies: boolean | void,
) {
this.tileSize = 512; // constant
this.maxValidLatitude = 85.051129; // constant
this._renderWorldCopies = (renderWorldCopies === undefined
? true
: renderWorldCopies) as boolean;
this._minZoom = minZoom || 0;
this._maxZoom = maxZoom || 22;
this._minPitch = minPitch === undefined || minPitch === null ? 0 : minPitch;
this._maxPitch =
maxPitch === undefined || maxPitch === null ? 60 : maxPitch;
this.setMaxBounds();
this.width = 0;
this.height = 0;
this._center = new LngLat(0, 0);
this.zoom = 0;
this.angle = 0;
this._fov = 0.6435011087932844;
this._pitch = 0;
this.unmodified = true;
this.edgeInsets = new EdgeInsets();
this.posMatrixCache = {};
this.alignedPosMatrixCache = {};
}
public clone(): Transform {
const clone = new Transform(
this._minZoom,
this._maxZoom,
this._minPitch,
this._maxPitch,
this._renderWorldCopies,
);
clone.tileSize = this.tileSize;
clone.latRange = this.latRange;
clone.width = this.width;
clone.height = this.height;
clone.center = this._center;
clone.zoom = this.zoom;
clone.angle = this.angle;
clone.fov = this._fov;
clone.pitch = this._pitch;
clone.unmodified = this.unmodified;
clone.edgeInsets = this.edgeInsets.clone();
clone.calcMatrices();
return clone;
}
/**
* Returns if the padding params match
*
* @param {IPaddingOptions} padding
* @returns {boolean}
* @memberof Transform
*/
public isPaddingEqual(padding: IPaddingOptions): boolean {
return this.edgeInsets.equals(padding);
}
/**
* Helper method to upadte edge-insets inplace
*
* @param {IPaddingOptions} target
* @param {number} t
* @memberof Transform
*/
public interpolatePadding(
start: IPaddingOptions,
target: IPaddingOptions,
t: number,
) {
this.unmodified = false;
this.edgeInsets.interpolate(start, target, t);
this.constrain();
this.calcMatrices();
}
/**
* Return a zoom level that will cover all tiles the transform
* @param {Object} options options
* @param {number} options.tileSize Tile size, expressed in screen pixels.
* @param {boolean} options.roundZoom Target zoom level. If true, the value will be rounded to the closest integer. Otherwise the value will be floored.
* @returns {number} zoom level An integer zoom level at which all tiles will be visible.
*/
public coveringZoomLevel(options: { roundZoom?: boolean; tileSize: number }) {
const z = (options.roundZoom ? Math.round : Math.floor)(
this.zoom + this.scaleZoom(this.tileSize / options.tileSize),
);
// At negative zoom levels load tiles from z0 because negative tile zoom levels don't exist.
return Math.max(0, z);
}
/**
* Return any "wrapped" copies of a given tile coordinate that are visible
* in the current view.
*
* @private
*/
// public getVisibleUnwrappedCoordinates(tileID: CanonicalTileID) {
// const result = [new UnwrappedTileID(0, tileID)];
// if (this._renderWorldCopies) {
// const utl = this.pointCoordinate(new Point(0, 0));
// const utr = this.pointCoordinate(new Point(this.width, 0));
// const ubl = this.pointCoordinate(new Point(this.width, this.height));
// const ubr = this.pointCoordinate(new Point(0, this.height));
// const w0 = Math.floor(Math.min(utl.x, utr.x, ubl.x, ubr.x));
// const w1 = Math.floor(Math.max(utl.x, utr.x, ubl.x, ubr.x));
// // Add an extra copy of the world on each side to properly render ImageSources and CanvasSources.
// // Both sources draw outside the tile boundaries of the tile that "contains them" so we need
// // to add extra copies on both sides in case offscreen tiles need to draw into on-screen ones.
// const extraWorldCopy = 1;
// for (let w = w0 - extraWorldCopy; w <= w1 + extraWorldCopy; w++) {
// if (w === 0) {
// continue;
// }
// result.push(new UnwrappedTileID(w, tileID));
// }
// }
// return result;
// }
/**
* Return all coordinates that could cover this transform for a covering
* zoom level.
* @param {Object} options
* @param {number} options.tileSize
* @param {number} options.minzoom
* @param {number} options.maxzoom
* @param {boolean} options.roundZoom
* @param {boolean} options.reparseOverscaled
* @param {boolean} options.renderWorldCopies
* @returns {Array<OverscaledTileID>} OverscaledTileIDs
* @private
*/
// public coveringTiles(options: {
// tileSize: number;
// minzoom?: number;
// maxzoom?: number;
// roundZoom?: boolean;
// reparseOverscaled?: boolean;
// renderWorldCopies?: boolean;
// }): OverscaledTileID[] {
// let z = this.coveringZoomLevel(options);
// const actualZ = z;
// if (options.minzoom !== undefined && z < options.minzoom) {
// return [];
// }
// if (options.maxzoom !== undefined && z > options.maxzoom) {
// z = options.maxzoom;
// }
// const centerCoord = MercatorCoordinate.fromLngLat(this.center);
// const numTiles = Math.pow(2, z);
// const centerPoint = [numTiles * centerCoord.x, numTiles * centerCoord.y, 0];
// const cameraFrustum = Frustum.fromInvProjectionMatrix(
// this.invProjMatrix,
// this.worldSize,
// z,
// );
// // No change of LOD behavior for pitch lower than 60 and when there is no top padding: return only tile ids from the requested zoom level
// let minZoom = options.minzoom || 0;
// // Use 0.1 as an epsilon to avoid for explicit == 0.0 floating point checks
// if (this._pitch <= 60.0 && this.edgeInsets.top < 0.1) {
// minZoom = z;
// }
// // There should always be a certain number of maximum zoom level tiles surrounding the center location
// const radiusOfMaxLvlLodInTiles = 3;
// const newRootTile = (wrap: number): any => {
// return {
// // All tiles are on zero elevation plane => z difference is zero
// aabb: new Aabb(
// [wrap * numTiles, 0, 0],
// [(wrap + 1) * numTiles, numTiles, 0],
// ),
// zoom: 0,
// x: 0,
// y: 0,
// wrap,
// fullyVisible: false,
// };
// };
// // Do a depth-first traversal to find visible tiles and proper levels of detail
// const stack = [];
// const result = [];
// const maxZoom = z;
// const overscaledZ = options.reparseOverscaled ? actualZ : z;
// if (this._renderWorldCopies) {
// // Render copy of the globe thrice on both sides
// for (let i = 1; i <= 3; i++) {
// stack.push(newRootTile(-i));
// stack.push(newRootTile(i));
// }
// }
// stack.push(newRootTile(0));
// while (stack.length > 0) {
// const it = stack.pop();
// const x = it.x;
// const y = it.y;
// let fullyVisible = it.fullyVisible;
// // Visibility of a tile is not required if any of its ancestor if fully inside the frustum
// if (!fullyVisible) {
// const intersectResult = it.aabb.intersects(cameraFrustum);
// if (intersectResult === 0) {
// continue;
// }
// fullyVisible = intersectResult === 2;
// }
// const distanceX = it.aabb.distanceX(centerPoint);
// const distanceY = it.aabb.distanceY(centerPoint);
// const longestDim = Math.max(Math.abs(distanceX), Math.abs(distanceY));
// // We're using distance based heuristics to determine if a tile should be split into quadrants or not.
// // radiusOfMaxLvlLodInTiles defines that there's always a certain number of maxLevel tiles next to the map center.
// // Using the fact that a parent node in quadtree is twice the size of its children (per dimension)
// // we can define distance thresholds for each relative level:
// // f(k) = offset + 2 + 4 + 8 + 16 + ... + 2^k. This is the same as "offset+2^(k+1)-2"
// const distToSplit =
// radiusOfMaxLvlLodInTiles + (1 << (maxZoom - it.zoom)) - 2;
// // Have we reached the target depth or is the tile too far away to be any split further?
// if (
// it.zoom === maxZoom ||
// (longestDim > distToSplit && it.zoom >= minZoom)
// ) {
// result.push({
// tileID: new OverscaledTileID(
// it.zoom === maxZoom ? overscaledZ : it.zoom,
// it.wrap,
// it.zoom,
// x,
// y,
// ),
// distanceSq: vec2.sqrLen([
// centerPoint[0] - 0.5 - x,
// centerPoint[1] - 0.5 - y,
// ]),
// });
// continue;
// }
// for (let i = 0; i < 4; i++) {
// const childX = (x << 1) + (i % 2);
// const childY = (y << 1) + (i >> 1);
// stack.push({
// aabb: it.aabb.quadrant(i),
// zoom: it.zoom + 1,
// x: childX,
// y: childY,
// wrap: it.wrap,
// fullyVisible,
// });
// }
// }
// return result
// .sort((a, b) => a.distanceSq - b.distanceSq)
// .map((a) => a.tileID);
// }
public resize(width: number, height: number) {
this.width = width;
this.height = height;
this.pixelsToGLUnits = [2 / width, -2 / height];
this.constrain();
this.calcMatrices();
}
public zoomScale(zoom: number) {
return Math.pow(2, zoom);
}
public scaleZoom(scale: number) {
return Math.log(scale) / Math.LN2;
}
public project(lnglat: LngLat) {
const lat = clamp(
lnglat.lat,
-this.maxValidLatitude,
this.maxValidLatitude,
);
return new Point(
mercatorXfromLng(lnglat.lng) * this.worldSize,
mercatorYfromLat(lat) * this.worldSize,
);
}
public unproject(point: Point): LngLat {
return new MercatorCoordinate(
point.x / this.worldSize,
point.y / this.worldSize,
).toLngLat();
}
public setLocationAtPoint(lnglat: LngLat, point: Point) {
const a = this.pointCoordinate(point);
const b = this.pointCoordinate(this.centerPoint);
const loc = this.locationCoordinate(lnglat);
const newCenter = new MercatorCoordinate(
loc.x - (a.x - b.x),
loc.y - (a.y - b.y),
);
this.center = this.coordinateLocation(newCenter);
if (this._renderWorldCopies) {
this.center = this.center.wrap();
}
}
public pointCoordinate(p: Point) {
const targetZ = 0;
// since we don't know the correct projected z value for the point,
// unproject two points to get a line and then find the point on that
// line with z=0
const coord0 = new Float32Array([p.x, p.y, 0, 1]);
const coord1 = new Float32Array([p.x, p.y, 1, 1]);
vec4.transformMat4(coord0, coord0, this.pixelMatrixInverse);
vec4.transformMat4(coord1, coord1, this.pixelMatrixInverse);
const w0 = coord0[3];
const w1 = coord1[3];
const x0 = coord0[0] / w0;
const x1 = coord1[0] / w1;
const y0 = coord0[1] / w0;
const y1 = coord1[1] / w1;
const z0 = coord0[2] / w0;
const z1 = coord1[2] / w1;
const t = z0 === z1 ? 0 : (targetZ - z0) / (z1 - z0);
return new MercatorCoordinate(
interpolate(x0, x1, t) / this.worldSize,
interpolate(y0, y1, t) / this.worldSize,
);
}
/**
* Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not
* an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.
* @returns {LngLatBounds} Returns a {@link LngLatBounds} object describing the map's geographical bounds.
*/
public getBounds(): LngLatBounds {
return new LngLatBounds()
.extend(this.pointLocation(new Point(0, 0)))
.extend(this.pointLocation(new Point(this.width, 0)))
.extend(this.pointLocation(new Point(this.width, this.height)))
.extend(this.pointLocation(new Point(0, this.height)));
}
/**
* Returns the maximum geographical bounds the map is constrained to, or `null` if none set.
* @returns {LngLatBounds} {@link LngLatBounds}
*/
public getMaxBounds(): LngLatBounds | null {
if (
!this.latRange ||
this.latRange.length !== 2 ||
!this.lngRange ||
this.lngRange.length !== 2
) {
return null;
}
return new LngLatBounds(
[this.lngRange[0], this.latRange[0]],
[this.lngRange[1], this.latRange[1]],
);
}
/**
* Sets or clears the map's geographical constraints.
* @param {LngLatBounds} bounds A {@link LngLatBounds} object describing the new geographic boundaries of the map.
*/
public setMaxBounds(bounds?: LngLatBounds) {
if (bounds) {
this.lngRange = [bounds.getWest(), bounds.getEast()];
this.latRange = [bounds.getSouth(), bounds.getNorth()];
this.constrain();
} else {
this.lngRange = undefined;
this.latRange = [-this.maxValidLatitude, this.maxValidLatitude];
}
}
public customLayerMatrix(): number[] {
return (this.mercatorMatrix as number[]).slice();
}
public maxPitchScaleFactor() {
// calcMatrices hasn't run yet
if (!this.pixelMatrixInverse) {
return 1;
}
const coord = this.pointCoordinate(new Point(0, 0));
const p = new Float32Array([
coord.x * this.worldSize,
coord.y * this.worldSize,
0,
1,
]);
const topPoint = vec4.transformMat4(p, p, this.pixelMatrix);
return topPoint[3] / this.cameraToCenterDistance;
}
/*
* The camera looks at the map from a 3D (lng, lat, altitude) location. Let's use `cameraLocation`
* as the name for the location under the camera and on the surface of the earth (lng, lat, 0).
* `cameraPoint` is the projected position of the `cameraLocation`.
*
* This point is useful to us because only fill-extrusions that are between `cameraPoint` and
* the query point on the surface of the earth can extend and intersect the query.
*
* When the map is not pitched the `cameraPoint` is equivalent to the center of the map because
* the camera is right above the center of the map.
*/
public getCameraPoint() {
const pitch = this._pitch;
const yOffset = Math.tan(pitch) * (this.cameraToCenterDistance || 1);
return this.centerPoint.add(new Point(0, yOffset));
}
/*
* When the map is pitched, some of the 3D features that intersect a query will not intersect
* the query at the surface of the earth. Instead the feature may be closer and only intersect
* the query because it extrudes into the air.
*
* This returns a geometry that includes all of the original query as well as all possible ares of the
* screen where the *base* of a visible extrusion could be.
* - For point queries, the line from the query point to the "camera point"
* - For other geometries, the envelope of the query geometry and the "camera point"
*/
public getCameraQueryGeometry(queryGeometry: Point[]): Point[] {
const c = this.getCameraPoint();
if (queryGeometry.length === 1) {
return [queryGeometry[0], c];
} else {
let minX = c.x;
let minY = c.y;
let maxX = c.x;
let maxY = c.y;
for (const p of queryGeometry) {
minX = Math.min(minX, p.x);
minY = Math.min(minY, p.y);
maxX = Math.max(maxX, p.x);
maxY = Math.max(maxY, p.y);
}
return [
new Point(minX, minY),
new Point(maxX, minY),
new Point(maxX, maxY),
new Point(minX, maxY),
new Point(minX, minY),
];
}
}
/**
* Given a coordinate, return the screen point that corresponds to it
* @param {Coordinate} coord
* @returns {Point} screen point
* @private
*/
public coordinatePoint(coord: MercatorCoordinate) {
const p = vec4.fromValues(
coord.x * this.worldSize,
coord.y * this.worldSize,
0,
1,
);
vec4.transformMat4(p, p, this.pixelMatrix);
return new Point(p[0] / p[3], p[1] / p[3]);
}
/**
* Given a location, return the screen point that corresponds to it
* @param {LngLat} lnglat location
* @returns {Point} screen point
* @private
*/
public locationPoint(lnglat: LngLat) {
return this.coordinatePoint(this.locationCoordinate(lnglat));
}
/**
* Given a point on screen, return its lnglat
* @param {Point} p screen point
* @returns {LngLat} lnglat location
* @private
*/
public pointLocation(p: Point) {
return this.coordinateLocation(this.pointCoordinate(p));
}
/**
* Given a geographical lnglat, return an unrounded
* coordinate that represents it at this transform's zoom level.
* @param {LngLat} lnglat
* @returns {Coordinate}
* @private
*/
public locationCoordinate(lnglat: LngLat) {
return MercatorCoordinate.fromLngLat(lnglat);
}
/**
* Given a Coordinate, return its geographical position.
* @param {Coordinate} coord
* @returns {LngLat} lnglat
* @private
*/
public coordinateLocation(coord: MercatorCoordinate) {
return coord.toLngLat();
}
public getProjectionMatrix(): mat4 {
return this.projMatrix;
}
/**
* Calculate the posMatrix that, given a tile coordinate, would be used to display the tile on a map.
* @param {UnwrappedTileID} unwrappedTileID;
* @private
*/
// private calculatePosMatrix(
// unwrappedTileID: UnwrappedTileID,
// aligned: boolean = false,
// ): Float32Array {
// const posMatrixKey = unwrappedTileID.key;
// const cache = aligned ? this.alignedPosMatrixCache : this.posMatrixCache;
// if (cache[posMatrixKey]) {
// return cache[posMatrixKey];
// }
// const canonical = unwrappedTileID.canonical;
// const scale = this.worldSize / this.zoomScale(canonical.z);
// const unwrappedX =
// canonical.x + Math.pow(2, canonical.z) * unwrappedTileID.wrap;
// const posMatrix = mat4.identity(new Float64Array(16));
// mat4.translate(posMatrix, posMatrix, [
// unwrappedX * scale,
// canonical.y * scale,
// 0,
// ]);
// mat4.scale(posMatrix, posMatrix, [scale / EXTENT, scale / EXTENT, 1]);
// mat4.multiply(
// posMatrix,
// aligned ? this.alignedProjMatrix : this.projMatrix,
// posMatrix,
// );
// cache[posMatrixKey] = new Float32Array(posMatrix);
// return cache[posMatrixKey];
// }
private constrain() {
if (!this.center || !this.width || !this.height || this.constraining) {
return;
}
this.constraining = true;
let minY = -90;
let maxY = 90;
let minX = -180;
let maxX = 180;
let sy;
let sx;
let x2;
let y2;
const size = this.size;
const unmodified = this.unmodified;
if (this.latRange) {
const latRange = this.latRange;
minY = mercatorYfromLat(latRange[1]) * this.worldSize;
maxY = mercatorYfromLat(latRange[0]) * this.worldSize;
sy = maxY - minY < size.y ? size.y / (maxY - minY) : 0;
}
if (this.lngRange) {
const lngRange = this.lngRange;
minX = mercatorXfromLng(lngRange[0]) * this.worldSize;
maxX = mercatorXfromLng(lngRange[1]) * this.worldSize;
sx = maxX - minX < size.x ? size.x / (maxX - minX) : 0;
}
const point = this.point;
// how much the map should scale to fit the screen into given latitude/longitude ranges
const s = Math.max(sx || 0, sy || 0);
if (s) {
this.center = this.unproject(
new Point(
sx ? (maxX + minX) / 2 : point.x,
sy ? (maxY + minY) / 2 : point.y,
),
);
this.zoom += this.scaleZoom(s);
this.unmodified = unmodified;
this.constraining = false;
return;
}
if (this.latRange) {
const y = point.y;
const h2 = size.y / 2;
if (y - h2 < minY) {
y2 = minY + h2;
}
if (y + h2 > maxY) {
y2 = maxY - h2;
}
}
if (this.lngRange) {
const x = point.x;
const w2 = size.x / 2;
if (x - w2 < minX) {
x2 = minX + w2;
}
if (x + w2 > maxX) {
x2 = maxX - w2;
}
}
// pan the map if the screen goes off the range
if (x2 !== undefined || y2 !== undefined) {
this.center = this.unproject(
new Point(
x2 !== undefined ? x2 : point.x,
y2 !== undefined ? y2 : point.y,
),
);
}
this.unmodified = unmodified;
this.constraining = false;
}
private calcMatrices() {
if (!this.height) {
return;
}
const halfFov = this._fov / 2;
const offset = this.centerOffset;
this.cameraToCenterDistance = (0.5 / Math.tan(halfFov)) * this.height;
// Find the distance from the center point [width/2 + offset.x, height/2 + offset.y] to the
// center top point [width/2 + offset.x, 0] in Z units, using the law of sines.
// 1 Z unit is equivalent to 1 horizontal px at the center of the map
// (the distance between[width/2, height/2] and [width/2 + 1, height/2])
const groundAngle = Math.PI / 2 + this._pitch;
const fovAboveCenter = this._fov * (0.5 + offset.y / this.height);
const topHalfSurfaceDistance =
(Math.sin(fovAboveCenter) * this.cameraToCenterDistance) /
Math.sin(
clamp(Math.PI - groundAngle - fovAboveCenter, 0.01, Math.PI - 0.01),
);
const point = this.point;
const x = point.x;
const y = point.y;
// Calculate z distance of the farthest fragment that should be rendered.
const furthestDistance =
Math.cos(Math.PI / 2 - this._pitch) * topHalfSurfaceDistance +
this.cameraToCenterDistance;
// Add a bit extra to avoid precision problems when a fragment's distance is exactly `furthestDistance`
const farZ = furthestDistance * 1.01;
// The larger the value of nearZ is
// - the more depth precision is available for features (good)
// - clipping starts appearing sooner when the camera is close to 3d features (bad)
//
// Smaller values worked well for mapbox-gl-js but deckgl was encountering precision issues
// when rendering it's layers using custom layers. This value was experimentally chosen and
// seems to solve z-fighting issues in deckgl while not clipping buildings too close to the camera.
const nearZ = this.height / 50;
// matrix for conversion from location to GL coordinates (-1 .. 1)
let m = mat4.create();
mat4.perspective(m, this._fov, this.width / this.height, nearZ, farZ);
// Apply center of perspective offset
m[8] = (-offset.x * 2) / this.width;
m[9] = (offset.y * 2) / this.height;
mat4.scale(m, m, [1, -1, 1]);
mat4.translate(m, m, [0, 0, -this.cameraToCenterDistance]);
mat4.rotateX(m, m, this._pitch);
mat4.rotateZ(m, m, this.angle);
mat4.translate(m, m, [-x, -y, 0]);
// The mercatorMatrix can be used to transform points from mercator coordinates
// ([0, 0] nw, [1, 1] se) to GL coordinates.
this.mercatorMatrix = mat4.scale(mat4.create(), m, [
this.worldSize,
this.worldSize,
this.worldSize,
]);
// scale vertically to meters per pixel (inverse of ground resolution):
mat4.scale(
m,
m,
vec3.fromValues(
1,
1,
mercatorZfromAltitude(1, this.center.lat) * this.worldSize,
),
);
this.projMatrix = m;
this.invProjMatrix = mat4.invert(mat4.create(), this.projMatrix);
// Make a second projection matrix that is aligned to a pixel grid for rendering raster tiles.
// We're rounding the (floating point) x/y values to achieve to avoid rendering raster images to fractional
// coordinates. Additionally, we adjust by half a pixel in either direction in case that viewport dimension
// is an odd integer to preserve rendering to the pixel grid. We're rotating this shift based on the angle
// of the transformation so that 0°, 90°, 180°, and 270° rasters are crisp, and adjust the shift so that
// it is always <= 0.5 pixels.
const xShift = (this.width % 2) / 2;
const yShift = (this.height % 2) / 2;
const angleCos = Math.cos(this.angle);
const angleSin = Math.sin(this.angle);
const dx = x - Math.round(x) + angleCos * xShift + angleSin * yShift;
const dy = y - Math.round(y) + angleCos * yShift + angleSin * xShift;
const alignedM = mat4.clone(m);
mat4.translate(alignedM, alignedM, [
dx > 0.5 ? dx - 1 : dx,
dy > 0.5 ? dy - 1 : dy,
0,
]);
this.alignedProjMatrix = alignedM;
m = mat4.create();
mat4.scale(m, m, [this.width / 2, -this.height / 2, 1]);
mat4.translate(m, m, [1, -1, 0]);
this.labelPlaneMatrix = m;
m = mat4.create();
mat4.scale(m, m, [1, -1, 1]);
mat4.translate(m, m, [-1, -1, 0]);
mat4.scale(m, m, [2 / this.width, 2 / this.height, 1]);
this.glCoordMatrix = m;
// matrix for conversion from location to screen coordinates
this.pixelMatrix = mat4.multiply(
mat4.create(),
this.labelPlaneMatrix,
this.projMatrix,
);
// inverse matrix for conversion from screen coordinaes to location
m = mat4.invert(mat4.create(), this.pixelMatrix);
if (!m) {
throw new Error('failed to invert matrix');
}
this.pixelMatrixInverse = m;
this.posMatrixCache = {};
this.alignedPosMatrixCache = {};
}
} | the_stack |
import { extend } from '@syncfusion/ej2-base';
import { DataManager, Query, Deferred, UrlAdaptor } from '@syncfusion/ej2-data';
import { Kanban } from './kanban';
import { ActionEventArgs, SaveChanges, DataStateChangeEventArgs, DataSourceChangedEventArgs, PendingState } from './interface';
import { ReturnType } from './type';
import * as events from './constant';
/**
* Kanban data module
*/
export class Data {
private parent: Kanban;
private kanbanData: DataManager;
public dataManager: DataManager;
private query: Query;
private keyField: string;
private isObservable: boolean;
protected dataState: PendingState = { isPending: false, resolver: null, isDataChanged: false };
/**
* Constructor for data module
*
* @param {Kanban} parent Accepts the instance of the Kanban
*/
constructor(parent: Kanban) {
this.parent = parent;
this.keyField = this.parent.cardSettings.headerField;
this.dataState = { isDataChanged: false };
this.isObservable = false;
this.initDataManager(parent.dataSource, parent.query);
this.refreshDataManager();
}
/**
* The function used to initialize dataManager` and query
*
* @param {Object[] | DataManager} dataSource Accepts the dataSource as collection of objects or Datamanager instance.
* @param {Query} query Accepts the query to process the data from collections.
* @returns {void}
* @private
*/
private initDataManager(dataSource: Record<string, any>[] | DataManager, query: Query): void {
this.dataManager = dataSource instanceof DataManager ? <DataManager>dataSource : new DataManager(dataSource);
this.query = query instanceof Query ? query : new Query();
this.kanbanData = new DataManager(this.parent.kanbanData);
}
/**
* The function used to generate updated Query from schedule model
*
* @returns {void}
* @private
*/
public getQuery(): Query {
return this.query.clone();
}
/**
* The function used to get dataSource by executing given Query
*
* @param {Query} query - A Query that specifies to generate dataSource
* @returns {void}
* @private
*/
private getData(query?: Query): Promise<any> {
if (this.parent.dataSource && 'result' in this.parent.dataSource) {
const def: Deferred = this.eventPromise({ requestType: '' }, query);
this.isObservable = true;
return def.promise;
}
return this.dataManager.executeQuery(query);
}
public setState(state: PendingState): Object {
return this.dataState = state;
}
private getStateEventArgument(query: Query): PendingState {
const adaptr: UrlAdaptor = new UrlAdaptor();
const dm: DataManager = new DataManager({ url: '', adaptor: new UrlAdaptor });
const state: { data?: string, pvtData?: Object[] } = adaptr.processQuery(dm, query);
const data: Object = JSON.parse(state.data);
return extend(data, state.pvtData);
}
private eventPromise(args: ActionEventArgs, query?: Query, index?: number): Deferred {
const dataArgs: DataSourceChangedEventArgs = args;
const state: DataStateChangeEventArgs = <DataStateChangeEventArgs>this.getStateEventArgument(query);
const def: Deferred = new Deferred();
const deff: Deferred = new Deferred();
if (args.requestType !== undefined && this.dataState.isDataChanged !== false) {
state.action = <{}>args as ActionEventArgs;
if (args.requestType === 'cardChanged' || args.requestType === 'cardRemoved' || args.requestType === 'cardCreated') {
const editArgs: DataSourceChangedEventArgs = args;
editArgs.promise = deff.promise;
editArgs.state = state;
editArgs.index = index;
this.setState({ isPending: true, resolver: deff.resolve });
dataArgs.endEdit = deff.resolve;
dataArgs.cancelEdit = deff.reject;
this.parent.trigger(events.dataSourceChanged, editArgs);
deff.promise.then(() => {
this.setState({ isPending: true, resolver: def.resolve });
this.parent.trigger(events.dataStateChange, state);
editArgs.addedRecords.forEach((data: Record<string, any>) => {
this.parent.kanbanData.push(data);
});
editArgs.changedRecords.forEach((changedRecord: Record<string, any>) => {
let cardObj: Record<string, any> = this.parent.kanbanData.filter((data: Record<string, any>) =>
data[this.parent.cardSettings.headerField] === changedRecord[this.parent.cardSettings.headerField])[0] as Record<string, any>;
extend(cardObj, changedRecord);
});
editArgs.deletedRecords.forEach((deletedRecord: Record<string, any>) => {
const index: number = this.parent.kanbanData.findIndex((data: Record<string, any>) =>
data[this.parent.cardSettings.headerField] === deletedRecord[this.parent.cardSettings.headerField]);
this.parent.kanbanData.splice(index, 1);
});
}).catch(() => { this.parent.hideSpinner(); void 0});
} else {
this.setState({ isPending: true, resolver: def.resolve });
this.parent.trigger(events.dataStateChange, state);
}
} else {
this.setState({});
def.resolve(this.parent.dataSource);
}
return def;
}
/**
* The function used to get the table name from the given Query
*
* @returns {string} Returns the table name.
* @private
*/
private getTable(): string {
if (this.parent.query) {
const query: Query = this.getQuery();
return query.fromTable;
} else {
return null;
}
}
/**
* The function is used to send the request and get response from datamanager
*
* @returns {void}
* @private
*/
private refreshDataManager(): void {
const dataManager: Promise<any> = this.getData(this.getQuery());
dataManager.then((e: ReturnType) => this.dataManagerSuccess(e)).catch((e: ReturnType) => this.dataManagerFailure(e));
}
/**
* The function is used to handle the success response from dataManager
*
* @param {ReturnType} e Accepts the dataManager success result
* @returns {void}
* @private
*/
private dataManagerSuccess(e: ReturnType, type?: string, offlineArgs?: ActionEventArgs, index?: number): void {
if (this.parent.isDestroyed) { return; }
if (type) {
const resultData: Record<string, any>[] = extend([], e.result, null, true) as Record<string, any>[];
this.parent.kanbanData = resultData;
if (offlineArgs.requestType === 'cardCreated') {
if (!Array.isArray(e)) {
offlineArgs.addedRecords[0] = extend(offlineArgs.addedRecords[0], e);
} else {
this.modifyArrayData(offlineArgs.addedRecords, e);
}
} else if (offlineArgs.requestType === 'cardChanged') {
if (!Array.isArray(e)) {
offlineArgs.changedRecords[0] = extend(offlineArgs.changedRecords[0], e);
} else {
this.modifyArrayData(offlineArgs.changedRecords, e);
}
} else if (offlineArgs.requestType === 'cardRemoved') {
if (!Array.isArray(e)) {
offlineArgs.deletedRecords[0] = extend(offlineArgs.deletedRecords[0], e);
} else {
this.modifyArrayData(offlineArgs.deletedRecords, e);
}
}
this.refreshUI(offlineArgs, index);
} else {
this.parent.trigger(events.dataBinding, e, (args: ReturnType) => {
const resultData: Record<string, any>[] = extend([], args.result, null, true) as Record<string, any>[];
this.parent.kanbanData = resultData;
this.parent.notify(events.dataReady, { processedData: resultData });
this.parent.trigger(events.dataBound, null, () => this.parent.hideSpinner());
});
}
}
/**
* The function is used to handle the failure response from dataManager
*
* @param {ReturnType} e Accepts the dataManager failure result
* @returns {void}
* @private
*/
private dataManagerFailure(e: ReturnType): void {
if (this.parent.isDestroyed) { return; }
this.parent.trigger(events.actionFailure, { error: e }, () => this.parent.hideSpinner());
}
/**
* The function is used to perform the insert, update, delete and batch actions in datamanager
*
* @param {string} updateType Accepts the update type action
* @param {SaveChanges} params Accepts the savechanges params
* @param {string} type Accepts the requestType as string
* @param {Object} data Accepts the data to perform crud action
* @param {number} index Accepts the index to refresh the data into UI
* @returns {void}
* @private
*/
public updateDataManager(updateType: string, params: SaveChanges, type: string, data: Record<string, any>, index?: number): void {
this.parent.showSpinner();
let promise: Promise<any>;
const actionArgs: ActionEventArgs = {
requestType: type, cancel: false, addedRecords: params.addedRecords,
changedRecords: params.changedRecords, deletedRecords: params.deletedRecords
};
this.eventPromise(actionArgs, this.query, index);
this.parent.trigger(events.actionComplete, actionArgs, (offlineArgs: ActionEventArgs) => {
if (!offlineArgs.cancel) {
switch (updateType) {
case 'insert':
promise = this.dataManager.insert(data, this.getTable(), this.getQuery()) as Promise<any>;
break;
case 'update':
promise = this.dataManager.update(this.keyField, data, this.getTable(), this.getQuery()) as Promise<any>;
break;
case 'delete':
promise = this.dataManager.remove(this.keyField, data, this.getTable(), this.getQuery()) as Promise<any>;
break;
case 'batch':
promise = this.dataManager.saveChanges(params, this.keyField, this.getTable(), this.getQuery()) as Promise<any>;
break;
}
if (this.dataManager.dataSource.offline) {
if (!this.isObservable) {
this.kanbanData = this.dataManager;
this.parent.kanbanData = this.dataManager.dataSource.json as Record<string, any>[];
this.refreshUI(offlineArgs, index);
}
} else {
promise.then(() => {
if (this.parent.isDestroyed) { return; }
const dataManager: Promise<any> = this.getData(this.getQuery());
dataManager.then((e: ReturnType) => this.dataManagerSuccess(e, 'DataSourceChange', offlineArgs, index)).catch((e: ReturnType) => this.dataManagerFailure(e));
}).catch((e: ReturnType) => {
this.dataManagerFailure(e);
});
}
}
});
}
private modifyArrayData(onLineData: Record<string, any>[], e: Record<string, any>[]): Record<string, any>[] {
if (onLineData.length === e.length) {
for (let i: number = 0; i < e.length; i++) {
onLineData[i] = extend(onLineData[i], e[i]);
}
}
return onLineData;
}
/**
* The function is used to refresh the UI once the data manager action is completed
*
* @param {ActionEventArgs} args Accepts the ActionEventArgs to refresh UI.
* @param {number} position Accepts the index to refresh UI.
* @returns {void}
*/
public refreshUI(args: ActionEventArgs, position: number): void {
this.parent.layoutModule.columnData = this.parent.layoutModule.getColumnCards();
if (this.parent.swimlaneSettings.keyField) {
this.parent.layoutModule.kanbanRows = this.parent.layoutModule.getRows();
this.parent.layoutModule.swimlaneData = this.parent.layoutModule.getSwimlaneCards();
}
args.addedRecords.forEach((data: Record<string, any>, index: number) => {
if (this.parent.swimlaneSettings.keyField && !data[this.parent.swimlaneSettings.keyField]) {
data[this.parent.swimlaneSettings.keyField] = '';
}
this.parent.layoutModule.renderCardBasedOnIndex(data, position + index);
});
args.changedRecords.forEach((data: Record<string, any>) => {
if (this.parent.swimlaneSettings.keyField && !data[this.parent.swimlaneSettings.keyField]) {
data[this.parent.swimlaneSettings.keyField] = '';
}
this.parent.layoutModule.removeCard(data);
this.parent.layoutModule.renderCardBasedOnIndex(data, position);
if (this.parent.layoutModule.isSelectedCard) {
this.parent.actionModule.SingleCardSelection(data);
}
if (this.parent.sortSettings.field && this.parent.sortSettings.sortBy === 'Index'
&& this.parent.sortSettings.direction === 'Descending' && position > 0) {
--position;
}
});
args.deletedRecords.forEach((data: Record<string, any>) => {
this.parent.layoutModule.removeCard(data);
});
this.parent.layoutModule.refresh();
this.parent.renderTemplates();
this.parent.notify(events.contentReady, {});
this.parent.trigger(events.dataBound, args, () => this.parent.hideSpinner());
}
} | the_stack |
import { expect } from 'chai';
import { Observable, of } from 'rxjs';
import { switchMapTo, mergeMap, take } from 'rxjs/operators';
import { TestScheduler } from 'rxjs/testing';
import { observableMatcher } from '../helpers/observableMatcher';
/** @test {switchMapTo} */
describe('switchMapTo', () => {
let testScheduler: TestScheduler;
beforeEach(() => {
testScheduler = new TestScheduler(observableMatcher);
});
it('should map-and-flatten each item to an Observable', () => {
testScheduler.run(({ hot, cold, expectObservable, expectSubscriptions }) => {
const e1 = hot(' --1-----3--5-------|');
const e1subs = ' ^------------------!';
const e2 = cold(' x-x-x| ', { x: 10 });
// x-x-x|
// x-x-x|
const expected = '--x-x-x-x-xx-x-x---|';
const values = { x: 10 };
const result = e1.pipe(switchMapTo(e2));
expectObservable(result).toBe(expected, values);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should support the deprecated resultSelector', () => {
const results: Array<number[]> = [];
of(1, 2, 3)
.pipe(switchMapTo(of(4, 5, 6), (a, b, i, ii) => [a, b, i, ii]))
.subscribe({
next(value) {
results.push(value);
},
error(err) {
throw err;
},
complete() {
expect(results).to.deep.equal([
[1, 4, 0, 0],
[1, 5, 0, 1],
[1, 6, 0, 2],
[2, 4, 1, 0],
[2, 5, 1, 1],
[2, 6, 1, 2],
[3, 4, 2, 0],
[3, 5, 2, 1],
[3, 6, 2, 2],
]);
},
});
});
it('should support a void resultSelector (still deprecated)', () => {
const results: number[] = [];
of(1, 2, 3)
.pipe(switchMapTo(of(4, 5, 6), void 0))
.subscribe({
next(value) {
results.push(value);
},
error(err) {
throw err;
},
complete() {
expect(results).to.deep.equal([4, 5, 6, 4, 5, 6, 4, 5, 6]);
},
});
});
it('should switch a synchronous many outer to a synchronous many inner', (done) => {
const a = of(1, 2, 3);
const expected = ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'];
a.pipe(switchMapTo(of('a', 'b', 'c'))).subscribe({
next(x) {
expect(x).to.equal(expected.shift());
},
complete: done,
});
});
it('should unsub inner observables', () => {
let unsubbed = 0;
of('a', 'b')
.pipe(
switchMapTo(
new Observable<string>((subscriber) => {
subscriber.complete();
return () => {
unsubbed++;
};
})
)
)
.subscribe();
expect(unsubbed).to.equal(2);
});
it('should switch to an inner cold observable', () => {
testScheduler.run(({ hot, cold, expectObservable, expectSubscriptions }) => {
const x = cold(' --a--b--c--d--e--| ');
const xsubs = [
' ---------^---------! ',
// --a--b--c--d--e--|
' -------------------^----------------!',
];
const e1 = hot(' ---------x---------x---------| ');
const e1subs = ' ^----------------------------! ';
const expected = '-----------a--b--c---a--b--c--d--e--|';
expectObservable(e1.pipe(switchMapTo(x))).toBe(expected);
expectSubscriptions(x.subscriptions).toBe(xsubs);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should switch to an inner cold observable, outer eventually throws', () => {
testScheduler.run(({ hot, cold, expectObservable, expectSubscriptions }) => {
const x = cold(' --a--b--c--d--e--|');
const xsubs = ' ---------^---------! ';
const e1 = hot(' ---------x---------# ');
const e1subs = ' ^------------------! ';
const expected = '-----------a--b--c-# ';
expectObservable(e1.pipe(switchMapTo(x))).toBe(expected);
expectSubscriptions(x.subscriptions).toBe(xsubs);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should switch to an inner cold observable, outer is unsubscribed early', () => {
testScheduler.run(({ hot, cold, expectObservable, expectSubscriptions }) => {
const x = cold(' --a--b--c--d--e--| ');
const xsubs = [
' ---------^---------! ',
// --a--b--c--d--e--|
' -------------------^--! ',
];
const e1 = hot(' ---------x---------x---------|');
const unsub = ' ----------------------! ';
const e1subs = ' ^---------------------! ';
const expected = '-----------a--b--c---a- ';
expectObservable(e1.pipe(switchMapTo(x)), unsub).toBe(expected);
expectSubscriptions(x.subscriptions).toBe(xsubs);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should not break unsubscription chains when result is unsubscribed explicitly', () => {
testScheduler.run(({ hot, cold, expectObservable, expectSubscriptions }) => {
const x = cold('--a--b--c--d--e--| ');
const xsubs = [
' ---------^---------! ',
// --a--b--c--d--e--|
' -------------------^--! ',
];
const e1 = hot(' ---------x---------x---------|');
const e1subs = ' ^---------------------! ';
const expected = '-----------a--b--c---a- ';
const unsub = ' ----------------------! ';
const result = e1.pipe(
mergeMap((x) => of(x)),
switchMapTo(x),
mergeMap((x) => of(x))
);
expectObservable(result, unsub).toBe(expected);
expectSubscriptions(x.subscriptions).toBe(xsubs);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should switch to an inner cold observable, inner never completes', () => {
testScheduler.run(({ hot, cold, expectObservable, expectSubscriptions }) => {
const x = cold(' --a--b--c--d--e- ');
const xsubs = [
' ---------^---------! ',
// --a--b--c--d--e-
' -------------------^ ',
];
const e1 = hot(' ---------x---------y---------| ');
const e1subs = ' ^----------------------------! ';
const expected = '-----------a--b--c---a--b--c--d--e-';
expectObservable(e1.pipe(switchMapTo(x))).toBe(expected);
expectSubscriptions(x.subscriptions).toBe(xsubs);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should handle a synchronous switch to the inner observable', () => {
testScheduler.run(({ hot, cold, expectObservable, expectSubscriptions }) => {
const x = cold(' --a--b--c--d--e--| ');
// prettier-ignore
const xsubs = [
' ---------(^!) ',
' ---------^----------------! '
];
const e1 = hot(' ---------(xx)----------------|');
const e1subs = ' ^----------------------------!';
const expected = '-----------a--b--c--d--e-----|';
expectObservable(e1.pipe(switchMapTo(x))).toBe(expected);
expectSubscriptions(x.subscriptions).toBe(xsubs);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should switch to an inner cold observable, inner raises an error', () => {
testScheduler.run(({ hot, cold, expectObservable, expectSubscriptions }) => {
const x = cold(' --a--b--# ');
const xsubs = ' ---------^-------! ';
const e1 = hot(' ---------x---------x---------|');
const e1subs = ' ^----------------! ';
const expected = '-----------a--b--# ';
expectObservable(e1.pipe(switchMapTo(x))).toBe(expected);
expectSubscriptions(x.subscriptions).toBe(xsubs);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should switch an inner hot observable', () => {
testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => {
const x = hot(' --p-o-o-p---a--b--c--d-| ');
// prettier-ignore
const xsubs = [
' ---------^---------! ',
' -------------------^---! '
];
const e1 = hot(' ---------x---------x---------|');
const e1subs = ' ^----------------------------!';
const expected = '------------a--b--c--d-------|';
expectObservable(e1.pipe(switchMapTo(x))).toBe(expected);
expectSubscriptions(x.subscriptions).toBe(xsubs);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should switch to an inner empty', () => {
testScheduler.run(({ hot, cold, expectObservable, expectSubscriptions }) => {
const x = cold(' | ');
const xsubs = [
' ---------(^!) ',
// |
' -------------------(^!) ',
];
const e1 = hot(' ---------x---------x---------|');
const e1subs = ' ^----------------------------!';
const expected = '-----------------------------|';
expectObservable(e1.pipe(switchMapTo(x))).toBe(expected);
expectSubscriptions(x.subscriptions).toBe(xsubs);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should switch to an inner never', () => {
testScheduler.run(({ hot, cold, expectObservable, expectSubscriptions }) => {
const x = cold(' - ');
const xsubs = [
' ---------^---------! ',
// -
' -------------------^ ',
];
const e1 = hot(' ---------x---------x---------|');
const e1subs = ' ^----------------------------!';
const expected = '------------------------------';
expectObservable(e1.pipe(switchMapTo(x))).toBe(expected);
expectSubscriptions(x.subscriptions).toBe(xsubs);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should switch to an inner that just raises an error', () => {
testScheduler.run(({ hot, cold, expectObservable, expectSubscriptions }) => {
const x = cold(' # ');
const xsubs = ' ---------(^!) ';
const e1 = hot(' ---------x---------x---------|');
const e1subs = ' ^--------! ';
const expected = '---------# ';
expectObservable(e1.pipe(switchMapTo(x))).toBe(expected);
expectSubscriptions(x.subscriptions).toBe(xsubs);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should handle an empty outer', () => {
testScheduler.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' | ');
const e1subs = ' (^!)';
const expected = '| ';
expectObservable(e1.pipe(switchMapTo(of('foo')))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should handle a never outer', () => {
testScheduler.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' -');
const e1subs = ' ^';
const expected = '-';
expectObservable(e1.pipe(switchMapTo(of('foo')))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should handle an outer that just raises and error', () => {
testScheduler.run(({ cold, expectObservable, expectSubscriptions }) => {
const e1 = cold(' # ');
const e1subs = ' (^!)';
const expected = '# ';
expectObservable(e1.pipe(switchMapTo(of('foo')))).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
it('should stop listening to a synchronous observable when unsubscribed', () => {
const sideEffects: number[] = [];
const synchronousObservable = new Observable<number>((subscriber) => {
// This will check to see if the subscriber was closed on each loop
// when the unsubscribe hits (from the `take`), it should be closed
for (let i = 0; !subscriber.closed && i < 10; i++) {
sideEffects.push(i);
subscriber.next(i);
}
});
synchronousObservable.pipe(switchMapTo(of(0)), take(3)).subscribe(() => {
/* noop */
});
expect(sideEffects).to.deep.equal([0, 1, 2]);
});
}); | the_stack |
import { StyleSheet, css } from 'aphrodite';
import debounce from 'lodash/debounce';
import isEqual from 'lodash/isEqual';
import * as React from 'react';
import { SnackMissingDependencies } from 'snack-sdk';
import {
SnackCodeFile,
SnackFile,
SnackFiles,
SnackDependencies,
SnackDependency,
Annotation,
AnnotationAction,
SDKVersion,
} from '../types';
import {
getPackageJsonFromDependencies,
getDependencyAnnotations,
getPackageJsonDependencies,
} from '../utils/dependencies';
import { openEmbeddedSessionFullScreen } from '../utils/embeddedSession';
import { isScript, isPackageJson, isTest } from '../utils/fileUtilities';
import type { FileDependencies } from '../utils/findDependencies';
import { EditorViewProps } from './EditorViewProps';
import Toast from './shared/Toast';
type State = {
files: SnackFiles;
dependencies: SnackDependencies;
missingDependencies: SnackMissingDependencies;
sdkVersion: SDKVersion;
selectedFile: string;
packageJson: SnackCodeFile;
annotations: Annotation[];
uncheckedFiles: Set<string>; // files that are yet to be checked
filesDependencies: { [path: string]: FileDependencies }; // map of all files and their dependencies
getDependencyAction: (
name: string,
version: string,
dependencies: SnackDependencies,
sdkVersion: SDKVersion
) => AnnotationAction;
};
export function withDependencyManager<Props extends EditorViewProps>(
WrappedComponent: React.ComponentType<Props>,
isEmbedded?: boolean
) {
return class DependencyManager extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
const packageJson = getPackageJsonFromDependencies(props.dependencies);
this.state = {
files: {},
dependencies: props.dependencies,
missingDependencies: props.missingDependencies,
sdkVersion: props.sdkVersion,
packageJson,
selectedFile: props.selectedFile,
annotations: getDependencyAnnotations(
packageJson,
props.dependencies,
props.missingDependencies,
props.files,
{},
props.sdkVersion,
this.getDependencyAction
),
uncheckedFiles: new Set(),
filesDependencies: {},
getDependencyAction: this.getDependencyAction,
};
}
static getDerivedStateFromProps(props: Props, state: State) {
const { sdkVersion, files, dependencies, missingDependencies, selectedFile } = props;
let { packageJson } = state;
// Detect changed files and add them to a collection for
// checking them after a debounced timeout.
let uncheckedFiles: Set<string> | undefined;
if (files !== state.files) {
uncheckedFiles = new Set(state.uncheckedFiles);
for (const path in files) {
const file = files[path];
if (
file.type === 'CODE' &&
isScript(path) &&
!isTest(path) &&
file.contents !== state.files[path]?.contents
) {
uncheckedFiles.add(path);
}
}
for (const path in state.files) {
if (!files[path]) {
uncheckedFiles.add(path);
}
}
}
if (
!isPackageJson(selectedFile) ||
isEqual(packageJson, getPackageJsonFromDependencies(state.dependencies))
) {
const newPackageJson = getPackageJsonFromDependencies(dependencies);
packageJson = isEqual(newPackageJson, packageJson) ? packageJson : newPackageJson;
}
return uncheckedFiles ||
files !== state.files ||
dependencies !== state.dependencies ||
missingDependencies !== state.missingDependencies ||
sdkVersion !== state.sdkVersion ||
packageJson !== state.packageJson ||
selectedFile !== state.selectedFile
? {
files,
dependencies,
missingDependencies,
sdkVersion,
packageJson,
selectedFile,
annotations:
dependencies !== state.dependencies ||
missingDependencies !== state.missingDependencies ||
sdkVersion !== state.sdkVersion
? getDependencyAnnotations(
packageJson,
dependencies,
missingDependencies,
files,
state.filesDependencies,
sdkVersion,
state.getDependencyAction
)
: state.annotations,
uncheckedFiles: uncheckedFiles ?? state.uncheckedFiles,
}
: null;
}
componentDidMount() {
this.checkForMissingDependencies();
}
componentDidUpdate(_prevProps: Props, prevState: State) {
if (
prevState.uncheckedFiles !== this.state.uncheckedFiles &&
this.state.uncheckedFiles.size
) {
this.checkForMissingDependencies();
}
}
/**
* Intercept any edits to package.json and debounce updates
* to the dependencies.
*/
private updateFiles = (
updateFn: (files: SnackFiles) => { [path: string]: SnackFile | null }
) => {
this.props.updateFiles((files) => {
const filesUpdate = updateFn(files);
const packageJson: SnackCodeFile = filesUpdate['package.json'] as any;
if (packageJson) {
delete filesUpdate['package.json'];
this.setState(
(st) => ({
packageJson,
annotations: getDependencyAnnotations(
packageJson,
st.dependencies,
st.missingDependencies,
st.files,
st.filesDependencies,
st.sdkVersion,
st.getDependencyAction
),
}),
this.updateDependenciesFromPackageJson
);
}
return filesUpdate;
});
};
/**
* Propagate any edits to package.json to the session dependencies.
* If package.json is not valid, no updates are propagated.
*/
private updateDependenciesFromPackageJson = debounce(() => {
const packageDeps = getPackageJsonDependencies(this.state.packageJson, this.state.sdkVersion);
if (packageDeps) {
this.props.updateDependencies((sessionDeps) => {
const update: { [name: string]: SnackDependency | null } = {};
// Add / update dependencies
for (const name in packageDeps) {
const version = packageDeps[name];
const sessionDep = sessionDeps[name];
if (sessionDep?.version !== version) {
update[name] = {
version,
};
}
}
// Remove dependencies
for (const name in sessionDeps) {
if (!packageDeps[name]) {
update[name] = null;
}
}
return update;
});
}
}, 1000);
/**
* Intercept any updates to dependencies and edit package.json accordingly.
*/
private updateDependencies = (
updateFn: (dependencies: SnackDependencies) => { [name: string]: SnackDependency | null }
) => {
// @ts-ignore
const dependencies: SnackDependencies = this.props.updateDependencies(updateFn);
const packageJson = getPackageJsonFromDependencies(dependencies);
this.setState(() => ({
packageJson,
}));
};
/**
* Checks for missing dependencies in the files that were edited.
*/
private checkForMissingDependencies = debounce(async () => {
const { default: findDependencies } = await import('../utils/findDependencies');
// Find all dependencies for all changed files
const { files, uncheckedFiles } = this.state;
let { filesDependencies } = this.state;
let newFilesDep: { [path: string]: FileDependencies } | undefined;
for (const path of uncheckedFiles) {
const file: SnackCodeFile = files[path] as any;
if (!file) {
if (this.state.filesDependencies[path]) {
newFilesDep = newFilesDep ?? { ...filesDependencies };
delete newFilesDep[path];
}
} else {
try {
const fileDependencies = findDependencies(file.contents, path);
if (!isEqual(fileDependencies, this.state.filesDependencies[path])) {
newFilesDep = newFilesDep ?? { ...filesDependencies };
newFilesDep[path] = fileDependencies;
}
} catch (e) {
// babel could not compile this file, ignore
}
}
}
filesDependencies = newFilesDep ?? filesDependencies;
// Update state
this.setState((state) => ({
uncheckedFiles: new Set<string>(),
filesDependencies,
annotations: newFilesDep
? getDependencyAnnotations(
state.packageJson,
state.dependencies,
state.missingDependencies,
state.files,
filesDependencies,
state.sdkVersion,
state.getDependencyAction
)
: state.annotations,
}));
}, 1000);
private getDependencyAction = (
name: string,
version: string,
dependencies: SnackDependencies,
_sdkVersion: SDKVersion
): AnnotationAction => {
if (isEmbedded) {
return {
title: 'Open full editor to add dependencies',
run: this.handleOpenFullEditor,
};
} else if (dependencies[name]) {
if (dependencies[name].wantedVersion && dependencies[name].wantedVersion !== version) {
return {
title: `Update to ${dependencies[name].wantedVersion}`,
icon: () => (
<svg className={css(styles.icon)} viewBox="0 0 16 16">
<path d="M2,5.09257608 L7.47329684,8.31213064 L7.47329684,14.7092088 L2,11.5325867 L2,5.09257608 Z M2.49245524,4.22207437 L7.97432798,1 L13.506361,4.2238509 L7.92838937,7.41965108 L2.49245524,4.22207437 Z M14,5.09352708 L14,11.5325867 L8.47329684,14.7128733 L8.47329684,8.25995389 L14,5.09352708 Z" />
</svg>
),
run: () =>
this.updateDependencies(() => ({
[name]: { version: dependencies[name].wantedVersion as string },
})),
};
} else if (dependencies[name].error?.message.includes('not found in the registry')) {
return {
title: 'Remove dependency',
run: () =>
this.updateDependencies(() => ({
[name]: null,
})),
};
} else {
return {
title: 'Retry',
run: () =>
this.updateDependencies(() => ({
[name]: { version },
})),
};
}
} else {
return {
title: 'Add dependency',
icon: () => (
<svg className={css(styles.icon)} viewBox="0 0 16 16">
<path d="M2,5.09257608 L7.47329684,8.31213064 L7.47329684,14.7092088 L2,11.5325867 L2,5.09257608 Z M2.49245524,4.22207437 L7.97432798,1 L13.506361,4.2238509 L7.92838937,7.41965108 L2.49245524,4.22207437 Z M14,5.09352708 L14,11.5325867 L8.47329684,14.7128733 L8.47329684,8.25995389 L14,5.09352708 Z" />
</svg>
),
run: () =>
this.updateDependencies(() => ({
[name]: { version },
})),
};
}
};
private handleOpenFullEditor = () => {
openEmbeddedSessionFullScreen(this.props);
};
render() {
const { selectedFile } = this.props;
const { packageJson, annotations } = this.state;
const hasEmbeddedMissingDependencies = isEmbedded
? annotations.some(
({ location, action, severity }) =>
location?.fileName === selectedFile &&
!!action &&
selectedFile !== 'package.json' &&
severity > 2
)
: false;
return (
<>
<WrappedComponent
{...this.props}
files={{ ...this.props.files, 'package.json': packageJson }}
updateFiles={this.updateFiles}
updateDependencies={this.updateDependencies}
annotations={[...annotations, ...this.props.annotations]}
/>
<div>
{hasEmbeddedMissingDependencies && (
<Toast
label={<span>Open full editor to add new dependencies</span>}
actions={[
{
label: `Open`,
action: this.handleOpenFullEditor,
},
]}
/>
)}
</div>
</>
);
}
};
}
const styles = StyleSheet.create({
icon: {
height: 16,
width: 16,
fill: 'currentColor',
verticalAlign: 'middle',
opacity: 0.7,
},
}); | the_stack |
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { Course } from 'app/entities/course.model';
import { ArtemisTestModule } from '../../../test.module';
import { ExamManagementService } from 'app/exam/manage/exam-management.service';
import { Exam } from 'app/entities/exam.model';
import * as chai from 'chai';
import dayjs from 'dayjs';
import { ExamInformationDTO } from 'app/entities/exam-information.model';
import { StudentDTO } from 'app/entities/student-dto.model';
import { StudentExam } from 'app/entities/student-exam.model';
import { ExerciseGroup } from 'app/entities/exercise-group.model';
import { ExamScoreDTO } from 'app/exam/exam-scores/exam-score-dtos.model';
import { StatsForDashboard } from 'app/course/dashboards/instructor-course-dashboard/stats-for-dashboard.model';
import { TextSubmission } from 'app/entities/text-submission.model';
const expect = chai.expect;
describe('Exam Management Service Tests', () => {
let service: ExamManagementService;
let httpMock: HttpTestingController;
const course = { id: 456 } as Course;
const mockExamPopulated: Exam = {
id: 1,
startDate: undefined,
endDate: undefined,
visibleDate: undefined,
publishResultsDate: undefined,
examStudentReviewStart: undefined,
examStudentReviewEnd: undefined,
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ExamManagementService],
imports: [ArtemisTestModule, HttpClientTestingModule],
});
service = TestBed.inject(ExamManagementService);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
it('should create an exam', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockCopyExam = ExamManagementService.convertDateFromClient({ id: 1 });
// WHEN
service.create(course.id!, mockExam).subscribe((res) => expect(res.body).to.eq(mockExam));
// THEN
const req = httpMock.expectOne({ method: 'POST', url: `${service.resourceUrl}/${course.id!}/exams` });
expect(req.request.body).to.include(mockCopyExam);
// CLEANUP
req.flush(mockExam);
tick();
}));
it('should update an exam', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockCopyExam = ExamManagementService.convertDateFromClient({ id: 1 });
// WHEN
service.update(course.id!, mockExam).subscribe((res) => expect(res.body).to.eq(mockExam));
// THEN
const req = httpMock.expectOne({ method: 'PUT', url: `${service.resourceUrl}/${course.id!}/exams` });
expect(req.request.body).to.include(mockCopyExam);
// CLEANUP
req.flush(mockExam);
tick();
}));
it('should find an exam with no students and no exercise groups', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const expected: Exam = { id: 1 };
const mockCopyExam = ExamManagementService.convertDateFromClient(expected);
// WHEN
service.find(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.deep.equal(mockCopyExam));
// THEN
const req = httpMock.expectOne({
method: 'GET',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id}?withStudents=false&withExerciseGroups=false`,
});
expect(req.request.url).to.equal(`${service.resourceUrl}/${course.id!}/exams/${mockExam.id}`);
expect(req.request.params.get('withStudents')).to.equal('false');
expect(req.request.params.get('withExerciseGroups')).to.equal('false');
// CLEANUP
req.flush(expected);
tick();
}));
it('should get the exam title', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const expectedTitle = 'expectedTitle';
// WHEN
service.getTitle(mockExam.id!).subscribe((res) => expect(res.body).to.eq(expectedTitle));
// THEN
const req = httpMock.expectOne({ method: 'GET', url: `api/exams/${mockExam.id!}/title` });
req.flush(expectedTitle);
tick();
}));
it('should get exam scores', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockExamScore: ExamScoreDTO = {
examId: mockExam.id!,
title: '',
averagePointsAchieved: 1,
exerciseGroups: [],
maxPoints: 1,
hasSecondCorrectionAndStarted: false,
studentResults: [],
};
const expectedExamScore = { ...mockExamScore };
// WHEN
service.getExamScores(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.deep.eq(expectedExamScore));
// THEN
const req = httpMock.expectOne({
method: 'GET',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id}/scores`,
});
req.flush(mockExamScore);
tick();
}));
it('should get stats for exam assessment dashboard', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockStatsForDashboard = new StatsForDashboard();
const expectedStatsForDashboard = { ...mockStatsForDashboard };
// WHEN
service.getStatsForExamAssessmentDashboard(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.deep.eq(expectedStatsForDashboard));
// THEN
const req = httpMock.expectOne({
method: 'GET',
url: `${service.resourceUrl}/${course.id}/exams/${mockExam.id}/stats-for-exam-assessment-dashboard`,
});
req.flush(mockStatsForDashboard);
tick();
}));
it('should find all exams for course', fakeAsync(() => {
// GIVEN
const mockExamResponse = [{ ...mockExamPopulated }];
// WHEN
service.findAllExamsForCourse(course.id!).subscribe((res) => expect(res.body).to.deep.equal([mockExamPopulated]));
// THEN
const req = httpMock.expectOne({ method: 'GET', url: `${service.resourceUrl}/${course.id!}/exams` });
req.flush(mockExamResponse);
tick();
}));
it('find all exams for which the instructors have access', fakeAsync(() => {
// GIVEN
const mockExamResponse = [{ ...mockExamPopulated }];
// WHEN
service.findAllExamsAccessibleToUser(course.id!).subscribe((res) => expect(res.body).to.deep.equal([mockExamPopulated]));
// THEN
const req = httpMock.expectOne({ method: 'GET', url: `${service.resourceUrl}/${course.id}/exams-for-user` });
req.flush(mockExamResponse);
tick();
}));
it('should find all current and upcoming exams', fakeAsync(() => {
// GIVEN
const mockExamResponse = [{ ...mockExamPopulated }];
// WHEN
service.findAllCurrentAndUpcomingExams().subscribe((res) => expect(res.body).to.deep.equal([mockExamPopulated]));
// THEN
const req = httpMock.expectOne({ method: 'GET', url: `${service.resourceUrl}/upcoming-exams` });
req.flush(mockExamResponse);
tick();
}));
it('should getExamWithInterestingExercisesForAssessmentDashboard with isTestRun=false', fakeAsync(() => {
// GIVEN
const mockExamResponse = [{ ...mockExamPopulated }];
// WHEN
service
.getExamWithInterestingExercisesForAssessmentDashboard(course.id!, mockExamPopulated.id!, false)
.subscribe((res) => expect(res.body).to.deep.equal([mockExamPopulated]));
// THEN
const req = httpMock.expectOne({
method: 'GET',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExamPopulated.id}/exam-for-assessment-dashboard`,
});
req.flush(mockExamResponse);
tick();
}));
it('should getExamWithInterestingExercisesForAssessmentDashboard with isTestRun=true', fakeAsync(() => {
// GIVEN
const mockExamResponse = [{ ...mockExamPopulated }];
// WHEN
service
.getExamWithInterestingExercisesForAssessmentDashboard(course.id!, mockExamPopulated.id!, true)
.subscribe((res) => expect(res.body).to.deep.equal([mockExamPopulated]));
// THEN
const req = httpMock.expectOne({
method: 'GET',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExamPopulated.id}/exam-for-test-run-assessment-dashboard`,
});
req.flush(mockExamResponse);
tick();
}));
it('should get latest individual end date of exam', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockResponse: ExamInformationDTO = { latestIndividualEndDate: dayjs() };
const expected = { ...mockResponse };
// WHEN
service.getLatestIndividualEndDateOfExam(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.deep.equal(expected));
// THEN
const req = httpMock.expectOne({
method: 'GET',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id!}/latest-end-date`,
});
req.flush(mockResponse);
tick();
}));
it('should delete an exam', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
// WHEN
service.delete(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.be.null);
// THEN
const req = httpMock.expectOne({
method: 'DELETE',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id!}`,
});
req.flush(null);
tick();
}));
it('should add student to exam', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockStudentLogin = 'studentLogin';
// WHEN
service.addStudentToExam(course.id!, mockExam.id!, mockStudentLogin).subscribe((res) => expect(res.body).to.be.null);
// THEN
const req = httpMock.expectOne({
method: 'POST',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id!}/students/${mockStudentLogin}`,
});
req.flush(null);
tick();
}));
it('should add students to exam', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockStudents: StudentDTO[] = [
{ firstName: 'firstName1', lastName: 'lastName1', registrationNumber: '1', login: 'login1' },
{ firstName: 'firstName2', lastName: 'lastName2', registrationNumber: '2', login: 'login2' },
];
const expected: StudentDTO[] = [
{ firstName: 'firstName1', lastName: 'lastName1', registrationNumber: '1', login: 'login1' },
{ firstName: 'firstName2', lastName: 'lastName2', registrationNumber: '2', login: 'login2' },
];
// WHEN
service.addStudentsToExam(course.id!, mockExam.id!, mockStudents).subscribe((res) => expect(res.body).to.deep.equal(mockStudents));
// THEN
const req = httpMock.expectOne({
method: 'POST',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id!}/students`,
});
expect(req.request.body).to.eq(mockStudents);
// CLEAN
req.flush(expected);
tick();
}));
it('should remove student from exam with no participations and submission', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockStudentLogin = 'studentLogin';
// WHEN
service.removeStudentFromExam(course.id!, mockExam.id!, mockStudentLogin).subscribe((res) => expect(res.body).to.be.null);
// THEN
const req = httpMock.expectOne({
method: 'DELETE',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id!}/students/${mockStudentLogin}?withParticipationsAndSubmission=false`,
});
req.flush(null);
tick();
service.removeStudentFromExam(course.id!, mockExam.id!, mockStudentLogin, true).subscribe((res) => expect(res.body).to.be.null);
// THEN
const req2 = httpMock.expectOne({
method: 'DELETE',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id!}/students/${mockStudentLogin}?withParticipationsAndSubmission=true`,
});
req2.flush(null);
tick();
}));
it('should remove student from exam with participations and submission', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockStudentLogin = 'studentLogin';
// WHEN
service.removeStudentFromExam(course.id!, mockExam.id!, mockStudentLogin, true).subscribe((res) => expect(res.body).to.be.null);
// THEN
const req = httpMock.expectOne({
method: 'DELETE',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id!}/students/${mockStudentLogin}?withParticipationsAndSubmission=true`,
});
req.flush(null);
tick();
}));
it('remove all students from an exam', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockResponse = {};
// WHEN
service.removeAllStudentsFromExam(course.id!, mockExam.id!, false).subscribe((resp) => expect(resp.body).to.be.deep.equal({}));
// THEN
const req = httpMock.expectOne({
method: 'DELETE',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id!}/students?withParticipationsAndSubmission=false`,
});
req.flush(mockResponse);
tick();
}));
it('should generate student exams', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockStudentExams: StudentExam[] = [{ exam: mockExam }];
const expected: StudentExam[] = [{ exam: { id: 1 } }];
// WHEN
service.generateStudentExams(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.deep.equal(mockStudentExams));
// THEN
const req = httpMock.expectOne({
method: 'POST',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id!}/generate-student-exams`,
});
req.flush(expected);
tick();
}));
it('should create test run', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockStudentExam: StudentExam = { exam: mockExam };
const expected: StudentExam = { exam: { id: 1 } };
// WHEN
service.createTestRun(course.id!, mockExam.id!, mockStudentExam).subscribe((res) => expect(res.body).to.deep.equal(mockStudentExam));
// THEN
const req = httpMock.expectOne({
method: 'POST',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id!}/test-run`,
});
req.flush(expected);
tick();
}));
it('should delete test run', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockStudentExam: StudentExam = { exam: mockExam, id: 2 };
const expected: StudentExam = { exam: mockExam, id: 2 };
// WHEN
service.deleteTestRun(course.id!, mockExam.id!, mockStudentExam.id!).subscribe((res) => expect(res.body).to.deep.equal(mockStudentExam));
// THEN
const req = httpMock.expectOne({
method: 'DELETE',
url: `${service.resourceUrl}/${course.id}/exams/${mockExam.id}/test-run/${mockStudentExam.id}`,
});
req.flush(expected);
tick();
}));
it('should find all test runs for exam', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockStudentExams: StudentExam[] = [{ exam: mockExam, id: 2 }];
const expected: StudentExam[] = [{ exam: mockExam, id: 2 }];
// WHEN
service.findAllTestRunsForExam(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.deep.equal(mockStudentExams));
// THEN
const req = httpMock.expectOne({
method: 'GET',
url: `${service.resourceUrl}/${course.id}/exams/${mockExam.id}/test-runs`,
});
req.flush(expected);
tick();
}));
it('should generate missing student for exam', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockStudentExams: StudentExam[] = [{ exam: mockExam, id: 2 }];
const expected: StudentExam[] = [{ exam: mockExam, id: 2 }];
// WHEN
service.generateMissingStudentExams(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.deep.equal(mockStudentExams));
// THEN
const req = httpMock.expectOne({
method: 'POST',
url: `${service.resourceUrl}/${course.id}/exams/${mockExam.id}/generate-missing-student-exams`,
});
req.flush(expected);
tick();
}));
it('should start exercises', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockStudentExams: StudentExam[] = [{ exam: mockExam, id: 1 }];
const expected: StudentExam[] = [{ exam: mockExam, id: 1 }];
// WHEN
service.startExercises(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.deep.equal(mockStudentExams));
// THEN
const req = httpMock.expectOne({
method: 'POST',
url: `${service.resourceUrl}/${course.id}/exams/${mockExam.id}/student-exams/start-exercises`,
});
req.flush(expected);
tick();
}));
it('should evaluate quiz exercises', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockEvaluatedExercises = 1;
const expected = 1;
// WHEN
service.evaluateQuizExercises(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.equal(mockEvaluatedExercises));
// THEN
const req = httpMock.expectOne({
method: 'POST',
url: `${service.resourceUrl}/${course.id}/exams/${mockExam.id}/student-exams/evaluate-quiz-exercises`,
});
req.flush(expected);
tick();
}));
it('should assess unsubmitted exam modelling and text participations', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockUnsubmittedExercises = 1;
const expected = 1;
// WHEN
service.assessUnsubmittedExamModelingAndTextParticipations(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.equal(mockUnsubmittedExercises));
// THEN
const req = httpMock.expectOne({
method: 'POST',
url: `${service.resourceUrl}/${course.id}/exams/${mockExam.id}/student-exams/assess-unsubmitted-and-empty-student-exams`,
});
req.flush(expected);
tick();
}));
it('should unlock all repositories', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockRepoCount = 1;
const expected = 1;
// WHEN
service.unlockAllRepositories(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.equal(mockRepoCount));
// THEN
const req = httpMock.expectOne({
method: 'POST',
url: `${service.resourceUrl}/${course.id}/exams/${mockExam.id}/student-exams/unlock-all-repositories`,
});
req.flush(expected);
tick();
}));
it('should lock all repositories', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockRepoCount = 1;
const expected = 1;
// WHEN
service.lockAllRepositories(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.equal(mockRepoCount));
// THEN
const req = httpMock.expectOne({
method: 'POST',
url: `${service.resourceUrl}/${course.id}/exams/${mockExam.id}/student-exams/lock-all-repositories`,
});
req.flush(expected);
tick();
}));
it('should update order', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockExerciseGroups: ExerciseGroup[] = [{ exam: mockExam, id: 1 }];
const expected: ExerciseGroup[] = [{ exam: mockExam, id: 1 }];
// WHEN
service.updateOrder(course.id!, mockExam.id!, mockExerciseGroups).subscribe((res) => expect(res.body).to.deep.equal(mockExerciseGroups));
// THEN
const req = httpMock.expectOne({
method: 'PUT',
url: `${service.resourceUrl}/${course.id}/exams/${mockExam.id}/exercise-groups-order`,
});
req.flush(expected);
tick();
}));
it('should enroll all registered students to exam', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const expected: StudentDTO[] = [
{ firstName: 'firstName1', lastName: 'lastName1', registrationNumber: '1', login: 'login1' },
{ firstName: 'firstName2', lastName: 'lastName2', registrationNumber: '2', login: 'login2' },
];
service.addAllStudentsOfCourseToExam(course.id!, mockExam.id!).subscribe((res) => expect(res.body === null));
const req = httpMock.expectOne({
method: 'POST',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id!}/register-course-students`,
});
req.flush(expected);
tick();
}));
it('should find all locked submissions from exam', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockResponse = [new TextSubmission()];
const expected = [new TextSubmission()];
// WHEN
service.findAllLockedSubmissionsOfExam(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.be.deep.equal(expected));
// THEN
const req = httpMock.expectOne({
method: 'GET',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id!}/lockedSubmissions`,
});
req.flush(mockResponse);
tick();
}));
it('should download the exam from archive', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
const mockResponse = new Blob();
const expected = new Blob();
// WHEN
service.downloadExamArchive(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.deep.eq(expected));
// THEN
const req = httpMock.expectOne({
method: 'GET',
url: `${service.resourceUrl}/${course.id}/exams/${mockExam.id}/download-archive`,
});
req.flush(mockResponse);
tick();
}));
it('should archive the exam', fakeAsync(() => {
// GIVEN
const mockExam: Exam = { id: 1 };
// WHEN
service.archiveExam(course.id!, mockExam.id!).subscribe((res) => expect(res.body).to.deep.eq({}));
// THEN
const req = httpMock.expectOne({
method: 'PUT',
url: `${service.resourceUrl}/${course.id!}/exams/${mockExam.id}/archive`,
});
req.flush({});
tick();
}));
}); | the_stack |
import pDefer from "p-defer";
import should from "should";
import sinon from "sinon";
import { stderr, stdout } from "stdout-stderr";
import { PassThrough } from "stream";
import { ReadableStreamBuffer, WritableStreamBuffer } from "stream-buffers";
import {
Message,
MessageStreamClient,
MessageStreamer,
MessageStreamServer,
MessageType,
} from "../src/message";
function checkMessage(msg: any, type: string, id = "testid", cr = "") {
should(msg).be.an.Object();
should(msg.from).equal(id);
should(msg.type).equal(type);
should(msg.content).equal(`Testing ${type} from ${id}${cr}`);
should(msg.timestamp).be.a.Number();
}
describe("MessageStreamer tests", () => {
it("Should allow using info and error as standalone function", () => {
const outStream = new WritableStreamBuffer();
const errStream = new WritableStreamBuffer();
const ms = new MessageStreamer("MS Test", { outStream, errStream });
const info = ms.info;
const error = ms.error;
info("Testing info");
error("Testing error");
should(ms.messages).have.length(2);
should(ms.messages[0].type).equal("info");
should(ms.messages[0].content).equal("Testing info");
should(ms.messages[0].from).equal("MS Test");
should(ms.messages[1].type).equal("error");
should(ms.messages[1].content).equal("Testing error");
should(ms.messages[1].from).equal("MS Test");
const out = outStream.getContentsAsString();
const err = errStream.getContentsAsString();
should(out).match(/^.*\[MS Test\] INFO: Testing info\n$/);
should(err).match(/^.*\[MS Test\] ERROR: Testing error\n$/);
should(ms.summary).eql({
info: 1,
warning: 0,
error: 1,
task: 0,
stdout: 0,
stderr: 0,
});
});
});
describe("MessageStreamServer tests", () => {
afterEach(() => {
stdout.stop();
stderr.stop();
});
it("Should combine messages onto output stream", () => {
const outStream = new WritableStreamBuffer();
const server = new MessageStreamServer("testid", { outStream });
server.warning("Testing warning from testid");
server.info("Testing info from testid");
server.error("Testing error from testid");
server.log(MessageType.task, "Testing task from testid");
should(server.messages).have.length(4);
checkMessage(server.messages[0], "warning");
checkMessage(server.messages[1], "info");
checkMessage(server.messages[2], "error");
checkMessage(server.messages[3], "task");
const out = outStream.getContentsAsString();
if (out === false) throw should(out).be.ok();
const jsons = out.split("\n").filter((s) => s);
const msgs = jsons.map((s) => JSON.parse(s));
should(msgs).have.length(4);
checkMessage(msgs[0], "warning");
checkMessage(msgs[1], "info");
checkMessage(msgs[2], "error");
checkMessage(msgs[3], "task");
should(server.summary).eql({
info: 1,
warning: 1,
error: 1,
task: 1,
stdout: 0,
stderr: 0,
});
});
it("Should support message ID hierarchy", () => {
const outStream = new WritableStreamBuffer();
const root = new MessageStreamServer("root", { outStream });
const kid1 = new MessageStreamServer("kid1", { parent: root });
const kid2 = new MessageStreamServer("kid2", { parent: kid1 });
root.warning("Testing warning from root");
kid1.info("Testing info from root:kid1");
kid2.error("Testing error from root:kid1:kid2");
root.log(MessageType.task, "Testing task from root");
should(root.messages).have.length(4);
checkMessage(root.messages[0], "warning", "root");
checkMessage(root.messages[1], "info", "root:kid1");
checkMessage(root.messages[2], "error", "root:kid1:kid2");
checkMessage(root.messages[3], "task", "root");
const out = outStream.getContentsAsString();
if (out === false) throw should(out).be.ok();
const jsons = out.split("\n").filter((s) => s);
const msgs = jsons.map((s) => JSON.parse(s));
should(msgs).have.length(4);
checkMessage(msgs[0], "warning", "root");
checkMessage(msgs[1], "info", "root:kid1");
checkMessage(msgs[2], "error", "root:kid1:kid2");
checkMessage(msgs[3], "task", "root");
should(root.summary).eql({
info: 1,
warning: 1,
error: 1,
task: 1,
stdout: 0,
stderr: 0,
});
});
it("Should intercept stdout and stderr", () => {
// tslint:disable:no-console
const outStream = new WritableStreamBuffer();
stdout.start();
stderr.start();
const root = new MessageStreamServer("root", {
outStream,
interceptStdio: true,
});
try {
root.warning("Testing warning from root");
console.log("Testing stdout from root");
console.error("Testing stderr from root");
should(root.messages).have.length(3);
checkMessage(root.messages[0], "warning", "root");
checkMessage(root.messages[1], "stdout", "root", "\n");
checkMessage(root.messages[2], "stderr", "root", "\n");
const out = outStream.getContentsAsString();
if (out === false) throw should(out).be.ok();
const jsons = out.split("\n").filter((s) => s);
const msgs = jsons.map((s) => JSON.parse(s));
should(msgs).have.length(3);
checkMessage(msgs[0], "warning", "root");
checkMessage(msgs[1], "stdout", "root", "\n");
checkMessage(msgs[2], "stderr", "root", "\n");
should(root.summary).eql({
info: 0,
warning: 1,
error: 0,
task: 0,
stdout: 1,
stderr: 1,
});
should(stdout.output).equal("");
should(stderr.output).equal("");
} finally {
root.stopIntercept();
console.log("Testing stdout");
console.error("Testing stderr");
stdout.stop();
stderr.stop();
should(stdout.output).equal("Testing stdout\n");
should(stderr.output).equal("Testing stderr\n");
}
// tslint:enaable:no-console
});
});
describe("MessageStreamClient tests", () => {
it("Should read from input stream", async () => {
const inputStream = new ReadableStreamBuffer();
const outStream = new WritableStreamBuffer();
const errStream = new WritableStreamBuffer();
const client = new MessageStreamClient({
inputStream,
outStream,
errStream
});
const iSpy = sinon.spy();
const wSpy = sinon.spy();
const eSpy = sinon.spy();
const tSpy = sinon.spy();
const done = pDefer<Message>();
let count = 0;
client.info.on("message:*", iSpy);
client.warning.on("message:*", wSpy);
client.error.on("message:*", eSpy);
client.task.on("task:**", () => {
if (++count === 2) done.resolve();
});
client.task.on("task:**", tSpy);
const inMsgs: Message[] = [
{
type: MessageType.warning, content: "Testing warning from testid",
from: "testid", timestamp: 10,
},
{
type: MessageType.info, content: "Testing info from testid",
from: "testid", timestamp: 11,
},
{
type: MessageType.error, content: "Testing error from testid",
from: "testid", timestamp: 12,
},
{
type: MessageType.task, content: "[Created]",
from: "testid", timestamp: 13,
},
{
type: MessageType.task, content: "[Status]: Some status",
from: "testid", timestamp: 13,
},
];
const inStr = inMsgs.map((m) => JSON.stringify(m)).join("\n");
inputStream.put(inStr + "\n");
inputStream.stop();
await done.promise;
const out = outStream.getContentsAsString();
should(out).equal(
"Thu, 01 Jan 1970 00:00:00 GMT [testid] WARNING: Testing warning from testid\n" +
"Thu, 01 Jan 1970 00:00:00 GMT [testid] INFO: Testing info from testid\n"
);
const err = errStream.getContentsAsString();
should(err).equal(
"Thu, 01 Jan 1970 00:00:00 GMT [testid] ERROR: Testing error from testid\n"
);
should(iSpy.callCount).equal(1);
should(iSpy.getCall(0).args[0]).eql(inMsgs[1]);
should(wSpy.callCount).equal(1);
should(wSpy.getCall(0).args[0]).eql(inMsgs[0]);
should(eSpy.callCount).equal(1);
should(eSpy.getCall(0).args[0]).eql(inMsgs[2]);
should(tSpy.callCount).equal(2);
should(tSpy.getCall(0).args[0]).eql("Created");
should(tSpy.getCall(0).args[1]).eql(undefined);
should(tSpy.getCall(1).args[0]).eql("Status");
should(tSpy.getCall(1).args[1]).eql("Some status");
});
});
describe("MessageStreamServer + MessageStreamClient tests", () => {
it("Should pass through events", async () => {
const thru = new PassThrough();
const outStream = new WritableStreamBuffer();
const errStream = new WritableStreamBuffer();
const client = new MessageStreamClient({
inputStream: thru,
outStream,
errStream
});
const server = new MessageStreamServer("testid", { outStream: thru });
const iSpy = sinon.spy();
const wSpy = sinon.spy();
const eSpy = sinon.spy();
const tSpy = sinon.spy();
const done = pDefer<Message>();
client.info.on("message:*", iSpy);
client.warning.on("message:*", wSpy);
client.error.on("message:*", eSpy);
client.task.on("task:**", tSpy);
client.info.on("close", done.resolve);
server.warning("Testing warning from testid");
server.info("Testing info from testid");
server.error("Testing error from testid");
server.log(MessageType.task, "[Created]");
server.log(MessageType.task, "[Status]: Some status");
should(iSpy.callCount).equal(1);
checkMessage(iSpy.getCall(0).args[0], "info");
should(wSpy.callCount).equal(1);
checkMessage(wSpy.getCall(0).args[0], "warning");
should(eSpy.callCount).equal(1);
checkMessage(eSpy.getCall(0).args[0], "error");
should(tSpy.callCount).equal(2);
should(tSpy.getCall(0).args[0]).eql("Created");
should(tSpy.getCall(0).args[1]).eql(undefined);
should(tSpy.getCall(1).args[0]).eql("Status");
should(tSpy.getCall(1).args[1]).eql("Some status");
});
}); | the_stack |
import * as ts from "typescript";
import * as util from "util";
/**
* Error thrown during code generation. Has a node attach allowing to identify the source of the error.
* The error can either be the use of an unsupported language feature, an assertion error or any uncatched compiler error.
*/
export interface CodeGenerationDiagnostic extends Error {
/**
* The node that caused the error
*/
node: ts.Node;
/**
* The code, if available
*/
code: number;
}
export function createCodeGenerationDiagnostic(code: number, message: string, node: ts.Node) {
const error = new Error(message) as CodeGenerationDiagnostic;
error.node = node;
error.code = code;
return error;
}
/**
* Tests if the given object is a code generation error
* @param error the object to test for
* @return {boolean} true if it is a code generation error
*/
export function isCodeGenerationDiagnostic(error: any): error is CodeGenerationDiagnostic {
return typeof(error.node) !== "undefined" && typeof(error.code) === "number" && error instanceof Error;
}
/**
* Attaches the node to the given error or creates an error object with the node attached
* @param error the error object or message
* @param node the node that caused the error
* @return the code generation diagnostic error
*/
export function toCodeGenerationDiagnostic(error: any, node: ts.Node): CodeGenerationDiagnostic {
if (isCodeGenerationDiagnostic(error)) {
return error;
}
if (error instanceof Error) {
const diagnostic = error as CodeGenerationDiagnostic;
diagnostic.node = node;
diagnostic.code = 0;
return diagnostic;
}
return createCodeGenerationDiagnostic(0, error + "", node);
}
/**
* Error thrown if the code generation fails. Stores the node to show the node that caused the error
* in the users code.
*/
export class CodeGenerationDiagnostics {
static toDiagnostic(error: CodeGenerationDiagnostic): ts.Diagnostic {
const message = error.code === 0 ? `${error.message}\n${error.stack}` : error.message;
return {
code: error.code,
messageText: message,
start: error.node.getFullStart(),
length: error.node.getFullWidth(),
category: ts.DiagnosticCategory.Error,
file: error.node.getSourceFile()
};
}
static builtInMethodNotSupported(propertyAccessExpression: ts.PropertyAccessExpression, objectName: string, methodName: string) {
return CodeGenerationDiagnostics.createException(propertyAccessExpression, diagnostics.BuiltInMethodNotSupported, methodName, objectName);
}
static builtInPropertyNotSupported(property: ts.PropertyAccessExpression, objectName: string) {
return CodeGenerationDiagnostics.createException(property, diagnostics.BuiltInPropertyNotSupported, property.name.text, objectName);
}
static builtInDoesNotSupportElementAccess(element: ts.ElementAccessExpression, objectName: string) {
return CodeGenerationDiagnostics.createException(element, diagnostics.BuiltInObjectDoesNotSupportElementAccess, objectName);
}
private static createException(node: ts.Node, diagnostic: { message: string, code: number }, ...args: Array<string | number>) {
const message = util.format(diagnostic.message, ...args);
return createCodeGenerationDiagnostic(diagnostic.code, message, node);
}
static unsupportedLiteralType(node: ts.LiteralLikeNode, typeName: string) {
return CodeGenerationDiagnostics.createException(node, diagnostics.UnsupportedLiteralType, typeName);
}
static unsupportedType(node: ts.Declaration, typeName: string) {
return CodeGenerationDiagnostics.createException(node, diagnostics.UnsupportedType, typeName);
}
static unsupportedIdentifier(identifier: ts.Identifier) {
return CodeGenerationDiagnostics.createException(identifier, diagnostics.UnsupportedIdentifier, identifier.text);
}
static unsupportedBinaryOperation(binaryExpression: ts.BinaryExpression, leftType: string, rightType: string) {
return CodeGenerationDiagnostics.createException(
binaryExpression,
diagnostics.UnsupportedBinaryOperation,
ts.SyntaxKind[binaryExpression.operatorToken.kind],
leftType,
rightType
);
}
static unsupportedUnaryOperation(node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression, type: string) {
return CodeGenerationDiagnostics.createException(node, diagnostics.UnsupportedUnaryOperation, ts.SyntaxKind[node.operator], type);
}
static anonymousEntryFunctionsNotSupported(fun: ts.FunctionLikeDeclaration) {
return CodeGenerationDiagnostics.createException(fun, diagnostics.AnonymousEntryFunctionsUnsupported);
}
static optionalParametersInEntryFunctionNotSupported(optionalParameter: ts.ParameterDeclaration) {
return CodeGenerationDiagnostics.createException(optionalParameter, diagnostics.OptionalParametersNotSupportedForEntryFunction);
}
static genericEntryFunctionNotSupported(fun: ts.FunctionLikeDeclaration) {
return CodeGenerationDiagnostics.createException(fun, diagnostics.GenericEntryFunctionNotSuppoorted);
}
static unsupportedClassReferencedBy(identifier: ts.Identifier) {
return CodeGenerationDiagnostics.createException(identifier, diagnostics.UnsupportedBuiltInClass);
}
static referenceToNonSpeedyJSEntryFunctionFromJS(identifier: ts.Identifier, speedyJSFunctionSymbol: ts.Symbol) {
return CodeGenerationDiagnostics.createException(identifier, diagnostics.ReferenceToNonEntrySpeedyJSFunctionFromJS, speedyJSFunctionSymbol.name);
}
static refereneToNonSpeedyJSFunctionFromSpeedyJS(identifier: ts.Identifier, nonSpeedyJsFunctionSymbol: ts.Symbol) {
return CodeGenerationDiagnostics.createException(identifier, diagnostics.ReferenceToNonSpeedyJSFunctionFromSpeedyJS, nonSpeedyJsFunctionSymbol.name);
}
static overloadedEntryFunctionNotSupported(fun: ts.FunctionLikeDeclaration) {
return CodeGenerationDiagnostics.createException(fun, diagnostics.OverloadedEntryFunctionNotSupported);
}
static unsupportedSyntaxKind(node: ts.Node) {
return CodeGenerationDiagnostics.createException(node, diagnostics.UnsupportedSyntaxKind, ts.SyntaxKind[node.kind]);
}
static unsupportedProperty(propertyExpression: ts.PropertyAccessExpression) {
return CodeGenerationDiagnostics.createException(propertyExpression, diagnostics.UnsupportedProperty);
}
static unsupportedIndexer(node: ts.ElementAccessExpression) {
return CodeGenerationDiagnostics.createException(node, diagnostics.UnsupportedIndexer);
}
static unsupportedCast(node: ts.AsExpression, sourceType: string, targetType: string) {
return CodeGenerationDiagnostics.createException(node, diagnostics.UnsupportedCast, sourceType, targetType);
}
static implicitArrayElementCast(element: ts.Expression, arrayElementType: string, typeOfElementRequiringImplicitCast: string) {
return CodeGenerationDiagnostics.createException(
element,
diagnostics.UnsupportedImplicitArrayElementCast,
typeOfElementRequiringImplicitCast,
arrayElementType
);
}
static unsupportedImplicitCastOfBinaryExpressionOperands(binaryExpression: ts.BinaryExpression, leftOperandType: string, rightOperandType: string) {
return CodeGenerationDiagnostics.createException(
binaryExpression,
diagnostics.UnsupportedImplicitCastOfBinaryExpressionOperands,
leftOperandType,
rightOperandType
);
}
static unsupportedImplicitCastOfArgument(elementNotMatchingArrayElementType: ts.Expression, parameterType: string, argumentType: string) {
return CodeGenerationDiagnostics.createException(
elementNotMatchingArrayElementType,
diagnostics.UnsupportedImplicitCastOfArgument,
argumentType,
parameterType,
parameterType
);
}
static unsupportedImplicitCastOfConditionalResult(conditionalResult: ts.Expression, typeOfConditional: string, typeOfConditionResult: string) {
return CodeGenerationDiagnostics.createException(
conditionalResult,
diagnostics.UnsupportedImplicitCastOfConditionalResult,
typeOfConditionResult,
typeOfConditional,
typeOfConditional
);
}
static unsupportedElementAccessExpression(elementAccessExpression: ts.ElementAccessExpression, argumentExpressionType?: string) {
return CodeGenerationDiagnostics.createException(
elementAccessExpression,
diagnostics.UnsupportedElementAccessExpression,
argumentExpressionType || "undefined"
);
}
static unsupportedImplicitCastOfReturnValue(returnStatement: ts.ReturnStatement, declaredReturnType: string, returnStatementExpressionType: string) {
return CodeGenerationDiagnostics.createException(
returnStatement,
diagnostics.UnsupportedImplicitCastOfReturnValue,
returnStatementExpressionType,
declaredReturnType,
declaredReturnType
);
}
static unsupportedImplicitCast(node: ts.Node, castTargetType: string, actualValueType: string) {
return CodeGenerationDiagnostics.createException(node, diagnostics.UnsupportedImplicitCast, actualValueType, castTargetType, castTargetType);
}
static unsupportedFunctionDeclaration(declaration: ts.Declaration) {
throw CodeGenerationDiagnostics.createException(declaration, diagnostics.UnsupportedFunctionDeclaration);
}
static unsupportedGenericFunction(functionDeclaration: ts.FunctionLikeDeclaration) {
return CodeGenerationDiagnostics.createException(functionDeclaration, diagnostics.UnsupportedGenericFunction);
}
static unsupportedStaticProperties(propertyExpression: ts.PropertyAccessExpression) {
return CodeGenerationDiagnostics.createException(propertyExpression, diagnostics.UnsupportedStaticProperty);
}
static unsupportedNestedFunctionDeclaration(functionDeclaration: ts.FunctionDeclaration | ts.MethodDeclaration) {
return CodeGenerationDiagnostics.createException(functionDeclaration, diagnostics.UnsupportedNestedFunctionDeclaration);
}
static variableDeclarationList(variableDeclarationList: ts.VariableDeclarationList) {
return CodeGenerationDiagnostics.createException(variableDeclarationList, diagnostics.UnsupportedVarDeclaration);
}
static unsupportedOverloadedFunctionDeclaration(declaration: ts.FunctionLikeDeclaration) {
return CodeGenerationDiagnostics.createException(declaration, diagnostics.UnsupportedOverloadedFunctionDeclaration);
}
static unsupportedGenericClass(classDeclaration: ts.ClassDeclaration) {
return CodeGenerationDiagnostics.createException(classDeclaration, diagnostics.UnsupportedGenericClass);
}
static unsupportedClassInheritance(classDeclaration: ts.ClassDeclaration) {
return CodeGenerationDiagnostics.createException(classDeclaration, diagnostics.UnsupportedClassInheritance);
}
static entryFunctionWithCallbackNotSupported(parameter: ts.ParameterDeclaration) {
return CodeGenerationDiagnostics.createException(parameter, diagnostics.UnsupportedEntryFunctionWithCallback);
}
}
/* tslint:disable:max-line-length */
const diagnostics = {
BuiltInMethodNotSupported: {
message: "The method '%s' of the built in object '%s' is not supported.",
code: 100000
},
BuiltInPropertyNotSupported: {
message: "The property '%s' of the built in object '%s' is not supported.",
code: 100001
},
BuiltInObjectDoesNotSupportElementAccess: {
message: "The built in object '%s' does not support element access (%s[index] or $s[index]=value).",
code: 100002
},
UnsupportedBuiltInClass: {
message: "The class referenced by this identifier is not supported.",
code: 100003,
},
UnsupportedLiteralType: {
message: "The literal type '%s' is not supported.",
code: 100004
},
UnsupportedType: {
message: "The type '%s' is not supported.",
code: 100005
},
UnsupportedIdentifier: {
message: "Unsupported type or kind of identifier '%s'.",
code: 100006
},
UnsupportedBinaryOperation: {
message: "The binary operator %s is not supported for the left and right hand side types '%s' and '%s'.",
code: 100007
},
UnsupportedUnaryOperation: {
message: "The unary operator %s is not supported for the type '%s'.",
code: 100008
},
AnonymousEntryFunctionsUnsupported: {
message: "SpeedyJS entry functions need to have a name.",
code: 100009
},
ReferenceToNonEntrySpeedyJSFunctionFromJS: {
message: "SpeedyJS functions referenced from 'normal' JavaScript code needs to be async (the async modifier is missing on the declaration of '%s').",
code: 100010
},
OptionalParametersNotSupportedForEntryFunction: {
message: "Optional parameters or variadic parameters are not supported for SpeedyJS entry functions.",
code: 100011
},
GenericEntryFunctionNotSuppoorted: {
message: "Generic SpeedyJS entry functions are not supported.",
code: 100012
},
OverloadedEntryFunctionNotSupported: {
message: "SpeedyJS entry function cannot be overloaded.",
code: 100013
},
UnsupportedSyntaxKind: {
message: "The syntax kind '%s' is not yet supported.",
code: 100014
},
UnsupportedProperty: {
message: "The kind of property is not yet supported, only object properties are supported.",
code: 1000015
},
UnsupportedIndexer: {
message: "The kind of indexer is not yet supported",
code: 1000016
},
UnsupportedCast: {
message: "Casting from '%s' to '%s' is not yet supported",
code: 1000017
},
UnsupportedImplicitArrayElementCast: {
message: "The array element of type '%s' requires an implicit cast to the array element type '%s'. Implicit casts are not supported. An explicit cast of the element to the array element type is required.",
code: 1000018
},
UnsupportedImplicitCastOfBinaryExpressionOperands: {
message: "No implicit cast for the binary expressions operands (left: %s, right: %s) exists. An explicit cast of either of the operands to the other's type is required.",
code: 1000019
},
UnsupportedImplicitCastOfArgument: {
message: "Unsupported implicit cast of the argument with the type '%s' to the expected parameter type '%s'. An explicit cast of the argument to the type '%s' is required.",
code: 1000020
},
UnsupportedImplicitCastOfConditionalResult: {
message: "Unsupported implicit cast of conditional case with type '%s' to the type '%s' of the whole conditional expression. An explicit cast of the conditional case to the type '%s' is required.",
code: 1000021
},
UnsupportedElementAccessExpression: {
message: "Unsupported element access expression with indexer of type '%s'. Only element access expressions with an integer index are supported.",
code: 1000022
},
UnsupportedImplicitCastOfReturnValue: {
message: "Unsupported implicit cast of return value with the type '%s' to function's return type '%s'. An explicit cast of the return value to the expected return type '%s' is required.",
code: 1000023
},
UnsupportedImplicitCast: {
message: "Unsupported implicit cast of value with the type '%s' to the expected type '%s'. An explicit cast of the value to the type '%s' is required.",
code: 1000024
},
UnsupportedGenericFunction: {
message: "Generic functions and methods are not yet supported.",
code: 1000025
},
UnsupportedStaticProperty: {
message: "Static methods and properties are not yet supported.",
code: 1000026
},
UnsupportedNestedFunctionDeclaration: {
message: "Functions nested inside of other functions that potentially make use of a closure are not yet supported",
code: 1000027
},
UnsupportedFunctionDeclaration: {
message: "Unsupported function declaration. Only function and method declarations are supported.",
code: 1000028
},
UnsupportedVarDeclaration: {
message: "Unsupported 'var' declaration of variable. Only variables with block scope ('let' and 'const') are supported.",
code: 1000029
},
UnsupportedOverloadedFunctionDeclaration: {
message: "Overloaded functions are not yet supported.",
code: 1000030
},
UnsupportedGenericClass: {
message: "Generic classes are not yet supported.",
code: 1000031
},
UnsupportedClassInheritance: {
message: "Class inheritance is not yet supported.",
code: 1000032
},
ReferenceToNonSpeedyJSFunctionFromSpeedyJS: {
message: "The Speedy.js function cannot reference the regular JavaScript function '%s'. Calling JavaScript functions from Speedy.js is not yet supported. Either remove the function call or make the called function a Speedy.js function by adding the \"use speedyjs\" directive.",
code: 1000033
},
UnsupportedEntryFunctionWithCallback: {
message: "Passing callbacks to speedy.js entry functions is not yet supported",
code: 1000034
}
}; | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
class SimilarityRuleApi {
/**
* DynamicsCrm.DevKit SimilarityRuleApi
* @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;
/** Generated Fetch xml from Active rule and rule conditions. */
ActiveRuleFetchXML: DevKit.WebApi.StringValue;
/** Record type of the record being evaluated for potential similarities. */
BaseEntityName: DevKit.WebApi.StringValue;
/** Record type of the record being evaluated for potential similarities. */
BaseEntityTypeCode: DevKit.WebApi.OptionSetValueReadonly;
/** For internal use only. */
ComponentState: DevKit.WebApi.OptionSetValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Description of the similarity detection rule. */
Description: DevKit.WebApi.StringValue;
/** Exchange rate for the currency associated with the SimilarityRule with respect to the base currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Determines whether to flag inactive records as similarities */
ExcludeInactiveRecords: DevKit.WebApi.BooleanValue;
/** Fetch Xml */
FetchXmlList: DevKit.WebApi.StringValue;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Version in which the similarity rule is introduced. */
IntroducedVersion: DevKit.WebApi.StringValue;
/** Is Managed */
IsManaged: DevKit.WebApi.BooleanValueReadonly;
/** Record type of the records being evaluated as potential similarities. */
MatchingEntityName: DevKit.WebApi.StringValue;
/** Record type of the records being evaluated as potential similarities. */
MatchingEntityTypeCode: DevKit.WebApi.OptionSetValueReadonly;
/** Enter the maximum number of keywords and key phrases to use with text analytics. */
MaxKeyWords: DevKit.WebApi.IntegerValue;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** The name of the custom entity. */
name: DevKit.WebApi.StringValue;
/** Enter the maximum number of words in a key phrase to use with text analytics. */
NgramSize: DevKit.WebApi.IntegerValue;
/** Unique identifier for the organization */
OrganizationId: DevKit.WebApi.LookupValueReadonly;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Date and time when the record was created. */
OverwriteTime_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValueReadonly;
/** ConditionXml for similarity rule conditions. */
RuleConditionXml: DevKit.WebApi.StringValue;
/** Unique identifier for entity instances */
SimilarityRuleId: DevKit.WebApi.GuidValue;
/** Unique identifier of the Similarity Rule used when synchronizing customizations for the Microsoft Dynamics 365 client for Outlook */
SimilarityRuleIdUnique: DevKit.WebApi.GuidValueReadonly;
/** Unique identifier of the associated solution. */
SolutionId: DevKit.WebApi.GuidValueReadonly;
/** Status of the Similarity Rule */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Similarity Rule */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
SupportingSolutionId: DevKit.WebApi.GuidValueReadonly;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Exchange rate for the currency associated with the SimilarityRule with respect to the base currency. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace SimilarityRule {
enum BaseEntityTypeCode {
/** 1 */
Account,
/** 10323 */
Account_Project_Price_List,
/** 16 */
AccountLeads,
/** 8040 */
ACIViewMapper,
/** 10686 */
Action_Call,
/** 10685 */
Action_Call_Workflow,
/** 9962 */
Action_Card,
/** 10219 */
Action_Card_Regarding,
/** 10220 */
Action_Card_Role_Setting,
/** 9983 */
Action_Card_Type,
/** 9973 */
Action_Card_User_Settings,
/** 10165 */
Action_Input_Parameter,
/** 10166 */
Action_Output_Parameter,
/** 9968 */
ActionCardUserState,
/** 4200 */
Activity,
/** 10050 */
Activity_File_Attachment,
/** 10107 */
Activity_monitor,
/** 135 */
Activity_Party,
/** 10292 */
Actual,
/** 10332 */
Actual_Data_Export_Deprecated,
/** 10174 */
Adaptive_Card_Configuration,
/** 1071 */
Address,
/** 10205 */
admin_settings_entity,
/** 10587 */
AdminAppState,
/** 9949 */
Advanced_Similarity_Rule,
/** 10162 */
Agent_script,
/** 10688 */
Agent_Script_Answer,
/** 10163 */
Agent_script_step,
/** 10701 */
Agent_Script_Task,
/** 10687 */
Agent_Script_Task_Category,
/** 10588 */
Agent_Status_history,
/** 10413 */
Agreement,
/** 10414 */
Agreement_Booking_Date,
/** 10415 */
Agreement_Booking_Incident,
/** 10416 */
Agreement_Booking_Product,
/** 10417 */
Agreement_Booking_Service,
/** 10418 */
Agreement_Booking_Service_Task,
/** 10419 */
Agreement_Booking_Setup,
/** 10428 */
Agreement_Business_Process,
/** 10420 */
Agreement_Invoice_Date,
/** 10421 */
Agreement_Invoice_Product,
/** 10422 */
Agreement_Invoice_Setup,
/** 10423 */
Agreement_Substatus,
/** 10087 */
AI_Builder_Dataset,
/** 10088 */
AI_Builder_Dataset_File,
/** 10089 */
AI_Builder_Dataset_Record,
/** 10090 */
AI_Builder_Datasets_Container,
/** 10091 */
AI_Builder_File,
/** 10092 */
AI_Builder_File_Attached_Data,
/** 402 */
AI_Configuration,
/** 10081 */
AI_Form_Processing_Document,
/** 401 */
AI_Model,
/** 10084 */
AI_Object_Detection_Bounding_Box,
/** 10082 */
AI_Object_Detection_Image,
/** 10085 */
AI_Object_Detection_Image_Mapping,
/** 10083 */
AI_Object_Detection_Label,
/** 400 */
AI_Template,
/** 10095 */
Analysis_Component,
/** 10096 */
Analysis_Job,
/** 10097 */
Analysis_Result,
/** 10098 */
Analysis_Result_Detail,
/** 132 */
Announcement,
/** 2000 */
Annual_Fiscal_Calendar,
/** 9011 */
App_Config_Master,
/** 9012 */
App_Configuration,
/** 9013 */
App_Configuration_Instance,
/** 9007 */
App_Module_Component,
/** 9009 */
App_Module_Roles,
/** 10526 */
App_Parameter_Definition_Deprecated,
/** 10144 */
App_profile,
/** 10145 */
Application_Extension,
/** 4707 */
Application_File,
/** 1120 */
Application_Ribbons,
/** 10146 */
Application_Tab_Template,
/** 10528 */
Application_Tab_Template_Deprecated,
/** 10531 */
Application_Type_Deprecated,
/** 10021 */
ApplicationUser,
/** 8700 */
AppModule_Metadata,
/** 8702 */
AppModule_Metadata_Async_Operation,
/** 8701 */
AppModule_Metadata_Dependency,
/** 4201 */
Appointment,
/** 127 */
Article,
/** 1082 */
Article_Comment,
/** 1016 */
Article_Template,
/** 10114 */
Asset_Category_Template_Association,
/** 10506 */
Asset_Suggestion,
/** 10115 */
Asset_Template_Association,
/** 10549 */
Assignment_Configuration,
/** 10550 */
Assignment_Configuration_Step,
/** 10621 */
Attach_Skill,
/** 1001 */
Attachment_1001,
/** 1002 */
Attachment_1002,
/** 9808 */
Attribute,
/** 4601 */
Attribute_Map,
/** 10606 */
Audio_File,
/** 10689 */
Audit_Diagnostics_Setting,
/** 4567 */
Auditing,
/** 1094 */
Authorization_Server,
/** 10224 */
Auto_Capture_Rule,
/** 10225 */
Auto_Capture_Settings,
/** 10109 */
Available_Times,
/** 10110 */
Available_Times_Data_Source,
/** 9936 */
Azure_Service_Connection,
/** 10325 */
Batch_Job,
/** 1150 */
Bookable_Resource,
/** 10293 */
Bookable_Resource_Association,
/** 1145 */
Bookable_Resource_Booking,
/** 1146 */
Bookable_Resource_Booking_Header,
/** 10500 */
Bookable_Resource_Booking_Quick_Note,
/** 4421 */
Bookable_Resource_Booking_to_Exchange_Id_Mapping,
/** 10615 */
Bookable_Resource_Capacity_Profile,
/** 1147 */
Bookable_Resource_Category,
/** 1149 */
Bookable_Resource_Category_Assn,
/** 1148 */
Bookable_Resource_Characteristic,
/** 1151 */
Bookable_Resource_Group,
/** 10294 */
Booking_Alert,
/** 10295 */
Booking_Alert_Status,
/** 10296 */
Booking_Change,
/** 10424 */
Booking_Journal,
/** 10297 */
Booking_Rule,
/** 10298 */
Booking_Setup_Metadata,
/** 1152 */
Booking_Status,
/** 10425 */
Booking_Timestamp,
/** 10040 */
BotContent,
/** 4425 */
Bulk_Delete_Failure,
/** 4424 */
Bulk_Delete_Operation,
/** 4405 */
Bulk_Operation_Log,
/** 10299 */
Business_Closure,
/** 4232 */
Business_Data_Localized_Label,
/** 4725 */
Business_Process_Flow_Instance,
/** 10 */
Business_Unit,
/** 6 */
Business_Unit_Map,
/** 4003 */
Calendar,
/** 4004 */
Calendar_Rule,
/** 301 */
Callback_Registration,
/** 4400 */
Campaign,
/** 4402 */
Campaign_Activity,
/** 4404 */
Campaign_Activity_Item,
/** 4403 */
Campaign_Item,
/** 4401 */
Campaign_Response,
/** 300 */
Canvas_App,
/** 10031 */
CanvasApp_Extended_Metadata,
/** 10551 */
Capacity_Profile,
/** 10018 */
CascadeGrantRevokeAccessRecordsTracker,
/** 10019 */
CascadeGrantRevokeAccessVersionTracker,
/** 112 */
Case,
/** 10177 */
Case_Enrichment,
/** 4206 */
Case_Resolution,
/** 10178 */
Case_Suggestion,
/** 10179 */
Case_Suggestion_Request_Payload,
/** 10180 */
Case_Suggestions_Data_Souce,
/** 10427 */
Case_to_Work_Order_Business_Process,
/** 10192 */
Case_Topic,
/** 10195 */
Case_topic_Incident_mapping,
/** 10193 */
Case_Topic_Setting,
/** 10194 */
Case_Topic_Summary,
/** 10066 */
Catalog,
/** 10067 */
Catalog_Assignment,
/** 9959 */
Category,
/** 10512 */
CFS_IoT_Alert_Process_Flow,
/** 10540 */
channel,
/** 3005 */
Channel_Access_Profile,
/** 9400 */
Channel_Access_Profile_Rule,
/** 9401 */
Channel_Access_Profile_Rule_Item,
/** 10589 */
Channel_Capability,
/** 10562 */
Channel_Configuration,
/** 1236 */
Channel_Property,
/** 1234 */
Channel_Property_Group,
/** 10156 */
Channel_Provider_10156,
/** 10523 */
Channel_Provider_10523,
/** 10563 */
Channel_State_Configuration,
/** 1141 */
Characteristic,
/** 10624 */
Characteristic_mapping,
/** 10628 */
Chat_Authentication_Settings,
/** 10633 */
Chat_Widget,
/** 10632 */
Chat_Widget_Languagedeprecated,
/** 10635 */
Chat_Widget_Location,
/** 10042 */
Chatbot,
/** 10043 */
Chatbot_subcomponent,
/** 113 */
Child_Incident_Count,
/** 10300 */
Client_Extension,
/** 36 */
Client_update,
/** 4417 */
Column_Mapping,
/** 8005 */
Comment,
/** 4215 */
Commitment,
/** 10649 */
Communication_Provider_Setting,
/** 10650 */
Communication_Provider_Setting_Entry,
/** 10328 */
Competency_Requirement_Deprecated,
/** 123 */
Competitor,
/** 1004 */
Competitor_Address,
/** 1006 */
Competitor_Product,
/** 26 */
CompetitorSalesLiterature,
/** 10005 */
Component_Layer,
/** 10006 */
Component_Layer_Data_Source,
/** 10301 */
Configuration_10301,
/** 10690 */
Configuration_10690,
/** 3234 */
Connection,
/** 10037 */
Connection_Reference,
/** 3231 */
Connection_Role,
/** 3233 */
Connection_Role_Object_Type_Code,
/** 372 */
Connector,
/** 2 */
Contact,
/** 10329 */
Contact_Price_List,
/** 17 */
ContactInvoices,
/** 22 */
ContactLeads,
/** 19 */
ContactOrders,
/** 18 */
ContactQuotes,
/** 10565 */
Context_item_value,
/** 10568 */
Context_variable,
/** 1010 */
Contract,
/** 1011 */
Contract_Line,
/** 10405 */
Contract_Line_Detail_Performance,
/** 10406 */
Contract_Performance,
/** 2011 */
Contract_Template,
/** 10564 */
Conversation,
/** 10590 */
Conversation_Action,
/** 10591 */
Conversation_Action_Locale,
/** 10617 */
Conversation_Capacity_profile,
/** 10618 */
Conversation_Characteristic,
/** 10206 */
Conversation_Data_Deprecated,
/** 10567 */
Conversation_Sentiment,
/** 10643 */
Conversation_Topic,
/** 10646 */
Conversation_topic_Conversation_mapping,
/** 10644 */
Conversation_Topic_Setting,
/** 10645 */
Conversation_Topic_Summary,
/** 10642 */
ConversationInsight,
/** 10641 */
conversationsuggestionrequestpayload,
/** 10041 */
ConversationTranscript,
/** 10698 */
CTI_Search,
/** 9105 */
Currency,
/** 10069 */
Custom_API,
/** 10070 */
Custom_API_Request_Parameter,
/** 10071 */
Custom_API_Response_Property,
/** 9753 */
Custom_Control,
/** 9755 */
Custom_Control_Default_Config,
/** 9754 */
Custom_Control_Resource,
/** 10561 */
Custom_messaging_account,
/** 10660 */
Custom_messaging_channel,
/** 10658 */
Custom_Messaging_Engagement_Context,
/** 10116 */
Customer_Asset,
/** 10117 */
Customer_Asset_Attachment,
/** 10118 */
Customer_Asset_Category,
/** 4502 */
Customer_Relationship,
/** 10196 */
Customer_Service_historical_analytics,
/** 10238 */
Customer_Voice_alert,
/** 10239 */
Customer_Voice_alert_rule,
/** 10241 */
Customer_Voice_file_response,
/** 10242 */
Customer_Voice_localized_survey_email_template,
/** 10243 */
Customer_Voice_project,
/** 10246 */
Customer_Voice_satisfaction_metric,
/** 10247 */
Customer_Voice_survey,
/** 10240 */
Customer_Voice_survey_email_template,
/** 10248 */
Customer_Voice_survey_invite,
/** 10244 */
Customer_Voice_survey_question,
/** 10245 */
Customer_Voice_survey_question_response,
/** 10249 */
Customer_Voice_survey_reminder,
/** 10250 */
Customer_Voice_survey_response,
/** 10251 */
Customer_Voice_unsubscribed_recipient,
/** 10691 */
Customization_File,
/** 10188 */
Data_Analytics_Admin_Settings_Deprecated,
/** 10189 */
Data_Analytics_Report,
/** 4410 */
Data_Import,
/** 10014 */
Data_Lake_Folder,
/** 10015 */
Data_Lake_Folder_Permission,
/** 10016 */
Data_Lake_Workspace,
/** 10017 */
Data_Lake_Workspace_Permission,
/** 4411 */
Data_Map,
/** 4450 */
Data_Performance_Dashboard,
/** 10103 */
Database_Version,
/** 418 */
Dataflow,
/** 10542 */
Decision_contract,
/** 10543 */
Decision_rule_set,
/** 10333 */
Delegation,
/** 9961 */
DelveActionHub,
/** 7105 */
Dependency,
/** 7108 */
Dependency_Feature,
/** 7106 */
Dependency_Node,
/** 10191 */
Deprecated_Dynamics_Customer_Service_Analytics,
/** 10557 */
Deprecated_Workstream_Entity_Configuration,
/** 1013 */
Discount,
/** 1080 */
Discount_List,
/** 4102 */
Display_String,
/** 4101 */
Display_String_Map,
/** 9508 */
Document_Location,
/** 1189 */
Document_Suggestions,
/** 9940 */
Document_Template,
/** 4414 */
Duplicate_Detection_Rule,
/** 4415 */
Duplicate_Record,
/** 4416 */
Duplicate_Rule_Condition,
/** 4202 */
Email,
/** 4023 */
Email_Hash,
/** 4299 */
Email_Search,
/** 9605 */
Email_Server_Profile,
/** 9997 */
Email_Signature,
/** 2010 */
Email_Template,
/** 9700 */
Entitlement,
/** 10430 */
Entitlement_Application,
/** 9701 */
Entitlement_Channel,
/** 7272 */
Entitlement_Contact,
/** 9704 */
Entitlement_Entity_Allocation_Type_Mapping,
/** 6363 */
Entitlement_Product,
/** 9702 */
Entitlement_Template,
/** 9703 */
Entitlement_Template_Channel,
/** 4545 */
Entitlement_Template_Product,
/** 10592 */
Entity_10592,
/** 9800 */
Entity_9800,
/** 430 */
Entity_Analytics_Config,
/** 10515 */
Entity_Configuration,
/** 432 */
Entity_Image_Configuration,
/** 9810 */
Entity_Key,
/** 4600 */
Entity_Map,
/** 9811 */
Entity_Relationship,
/** 10556 */
Entity_Routing_Context,
/** 10693 */
Entity_Search,
/** 10692 */
Entity_Type,
/** 10221 */
EntityRankingRule,
/** 380 */
Environment_Variable_Definition,
/** 381 */
Environment_Variable_Value,
/** 10336 */
Estimate,
/** 10337 */
Estimate_Line,
/** 10706 */
Event,
/** 4120 */
Exchange_Sync_Id_Mapping,
/** 4711 */
Expander_Event,
/** 10338 */
Expense,
/** 10339 */
Expense_Category,
/** 10340 */
Expense_Receipt,
/** 955 */
Expired_Process,
/** 10010 */
ExportSolutionUpload,
/** 3008 */
External_Party,
/** 9987 */
External_Party_Item,
/** 10656 */
Facebook_Application,
/** 10655 */
Facebook_Engagement_Context,
/** 10657 */
Facebook_Page,
/** 4000 */
FacilityEquipment,
/** 10341 */
Fact,
/** 4204 */
Fax,
/** 9958 */
Feedback,
/** 10342 */
Field_Computation,
/** 1201 */
Field_Permission,
/** 1200 */
Field_Security_Profile,
/** 10431 */
Field_Service_Price_List_Item,
/** 10432 */
Field_Service_Setting,
/** 10433 */
Field_Service_SLA_Configuration,
/** 10434 */
Field_Service_System_Job,
/** 44 */
Field_Sharing,
/** 55 */
FileAttachment,
/** 10237 */
Filter,
/** 30 */
Filter_Template,
/** 10343 */
Find_Work_Event_Deprecated_in_v30,
/** 2004 */
Fixed_Monthly_Fiscal_Calendar,
/** 10033 */
Flow_Machine,
/** 10034 */
Flow_Machine_Group,
/** 4720 */
Flow_Session,
/** 10222 */
flowcardtype,
/** 8003 */
Follow,
/** 10213 */
Forecast,
/** 10211 */
Forecast_Configuration,
/** 10212 */
Forecast_definition,
/** 10214 */
Forecast_recurrence,
/** 10694 */
Form,
/** 10317 */
Fulfillment_Preference,
/** 10119 */
Functional_Location,
/** 10215 */
GDPRData,
/** 10575 */
Geo_Location_Provider,
/** 10516 */
Geofence,
/** 10517 */
Geofence_Event,
/** 10518 */
Geofencing_Settings,
/** 10513 */
Geolocation_Settings,
/** 10514 */
Geolocation_Tracking,
/** 54 */
Global_Search_Configuration,
/** 9600 */
Goal,
/** 9603 */
Goal_Metric,
/** 10038 */
Help_Page,
/** 8840 */
Hierarchy_Rule,
/** 9919 */
Hierarchy_Security_Configuration,
/** 9996 */
HolidayWrapper,
/** 10677 */
Hosted_Control,
/** 10232 */
icebreakersconfig,
/** 431 */
Image_Attribute_Configuration,
/** 1007 */
Image_Descriptor,
/** 4413 */
Import_Data,
/** 4428 */
Import_Entity_Mapping,
/** 9107 */
Import_Job,
/** 4423 */
Import_Log,
/** 4412 */
Import_Source_File,
/** 9931 */
Incident_KnowledgeBaseRecord,
/** 10435 */
Incident_Type,
/** 10436 */
Incident_Type_Characteristic,
/** 10437 */
Incident_Type_Product,
/** 10441 */
Incident_Type_Requirement_Group,
/** 10505 */
Incident_Type_Resolution,
/** 10438 */
Incident_Type_Service,
/** 10439 */
Incident_Type_Service_Task,
/** 10503 */
Incident_Type_Suggestion_Result,
/** 10504 */
Incident_Type_Suggestion_Run_History,
/** 10440 */
Incident_Types_Setup,
/** 126 */
Indexed_Article,
/** 10190 */
Insights,
/** 10411 */
Inspection,
/** 10409 */
Inspection_Attachment,
/** 10412 */
Inspection_Response,
/** 10408 */
Inspection_Template,
/** 10410 */
Inspection_Template_Version,
/** 10344 */
Integration_Job,
/** 10345 */
Integration_Job_Detail,
/** 3000 */
Integration_Status,
/** 4011 */
Inter_Process_Lock,
/** 9986 */
Interaction_for_Email,
/** 1003 */
Internal_Address,
/** 10068 */
Internal_Catalog_Assignment,
/** 7107 */
Invalid_Dependency,
/** 10442 */
Inventory_Adjustment,
/** 10443 */
Inventory_Adjustment_Product,
/** 10444 */
Inventory_Journal,
/** 10445 */
Inventory_Transfer,
/** 1090 */
Invoice,
/** 10346 */
Invoice_Frequency,
/** 10347 */
Invoice_Frequency_Detail,
/** 1091 */
Invoice_Line,
/** 10348 */
Invoice_Line_Detail,
/** 10327 */
Invoice_Process,
/** 10126 */
IoT_Alert,
/** 10142 */
IoT_Alert_to_Case_Process,
/** 10127 */
IoT_Device,
/** 10128 */
IoT_Device_Category,
/** 10129 */
IoT_Device_Command,
/** 10130 */
IoT_Device_Command_Definition,
/** 10131 */
IoT_Device_Data_History,
/** 10132 */
IoT_Device_Property,
/** 10133 */
IoT_Device_Registration_History,
/** 10134 */
IoT_Device_Visualization_Configuration,
/** 10135 */
IoT_Field_Mapping,
/** 10136 */
IoT_Property_Definition,
/** 10137 */
IoT_Provider,
/** 10138 */
IoT_Provider_Instance,
/** 10139 */
IoT_Settings,
/** 4705 */
ISV_Config,
/** 10349 */
Journal,
/** 10350 */
Journal_Line,
/** 10181 */
KB_Enrichment,
/** 10064 */
KeyVaultReference,
/** 9953 */
Knowledge_Article,
/** 9960 */
Knowledge_Article_Category,
/** 10056 */
Knowledge_Article_Image,
/** 9954 */
Knowledge_Article_Incident,
/** 10059 */
Knowledge_article_language_setting,
/** 10182 */
Knowledge_Article_Suggestion,
/** 10183 */
Knowledge_Article_Suggestion_Data_Source,
/** 10061 */
Knowledge_Article_Template,
/** 9955 */
Knowledge_Article_Views,
/** 9930 */
Knowledge_Base_Record,
/** 10053 */
Knowledge_Federated_Article,
/** 10054 */
Knowledge_FederatedArticle_Incident,
/** 10057 */
Knowledge_Interaction_Insight,
/** 10060 */
Knowledge_personalization,
/** 10197 */
Knowledge_search_analytics,
/** 10063 */
Knowledge_search_filter,
/** 10058 */
Knowledge_Search_Insight,
/** 9947 */
Knowledge_Search_Model,
/** 10062 */
Knowledge_search_personal_filter_config,
/** 10207 */
KPI_Event_Data,
/** 10208 */
KPI_Event_Definition,
/** 10594 */
Language_10594,
/** 9957 */
Language_9957,
/** 10695 */
Language_Module,
/** 9875 */
Language_Provisioning_State,
/** 4 */
Lead,
/** 1017 */
Lead_Address,
/** 954 */
Lead_To_Opportunity_Sales_Process,
/** 24 */
LeadCompetitors,
/** 27 */
LeadProduct,
/** 4207 */
Letter,
/** 2027 */
License,
/** 8006 */
Like,
/** 10661 */
LINE_account,
/** 10659 */
LINE_Engagement_Context,
/** 10102 */
List_Operation,
/** 4418 */
List_Value_Mapping,
/** 10634 */
Live_Chat_Context,
/** 10593 */
Live_work_item_event,
/** 10566 */
Live_Work_Item_Participant_Deprecated,
/** 9201 */
LocalConfigStore,
/** 10569 */
Localization,
/** 10636 */
Localized_Survey_Question_Deprecated,
/** 4419 */
Lookup_Mapping,
/** 10167 */
Macro_Action_Template,
/** 10169 */
Macro_Connector,
/** 10170 */
Macro_Run_History,
/** 10168 */
Macro_Solution_Configuration,
/** 9106 */
Mail_Merge_Template,
/** 9606 */
Mailbox,
/** 9608 */
Mailbox_Auto_Tracking_Folder,
/** 9607 */
Mailbox_Statistics,
/** 9609 */
Mailbox_Tracking_Category,
/** 9812 */
Managed_Property,
/** 10065 */
ManagedIdentity,
/** 10733 */
Marketing_Form_Display_Attributes,
/** 4300 */
Marketing_List,
/** 4301 */
Marketing_List_Member,
/** 10519 */
MarketingSiteMap,
/** 10560 */
Masking_Rule,
/** 10547 */
Master_Entity_Routing_Configuration,
/** 10574 */
Message,
/** 4231 */
Metadata_Difference,
/** 10670 */
Microsoft_Teams_account,
/** 10255 */
Microsoft_Teams_Collaboration_entity,
/** 10252 */
Microsoft_Teams_Graph_resource_Entity,
/** 10113 */
Migration_tracker,
/** 9866 */
Mobile_Offline_Profile,
/** 9867 */
Mobile_Offline_Profile_Item,
/** 9868 */
Mobile_Offline_Profile_Item_Association,
/** 9006 */
Model_driven_App,
/** 10026 */
Model_Driven_App_Component_Node,
/** 10025 */
Model_Driven_App_Component_Nodes_Edge,
/** 10024 */
Model_Driven_App_Element,
/** 10027 */
Model_Driven_App_Setting,
/** 10028 */
Model_Driven_App_User_Setting,
/** 10622 */
Model_training_details,
/** 2003 */
Monthly_Fiscal_Calendar,
/** 10253 */
msdyn_msteamssetting,
/** 10254 */
msdyn_msteamssettingsv2,
/** 10216 */
msdyn_relationshipinsightsunifiedconfig,
/** 9912 */
Multi_Select_Option_Value,
/** 9910 */
MultiEntitySearch,
/** 9900 */
Navigation_Setting,
/** 950 */
New_Process,
/** 10079 */
NonRelational_Data_Source,
/** 5 */
Note,
/** 10231 */
Notes_analysis_Config,
/** 10077 */
Notification_10077,
/** 4110 */
Notification_4110,
/** 10147 */
Notification_Field,
/** 10524 */
Notification_Field_Deprecated,
/** 10148 */
Notification_Template,
/** 10525 */
Notification_Template_Deprecated,
/** 10032 */
OData_v4_Data_Source,
/** 4490 */
Office_Document,
/** 9950 */
Office_Graph_Document,
/** 9870 */
Offline_Command_Definition,
/** 10600 */
Omnichannel_Configuration,
/** 10647 */
Omnichannel_historical_analytics,
/** 10576 */
Omnichannel_Personalization,
/** 10577 */
Omnichannel_Queue_Deprecated,
/** 10571 */
Omnichannel_Request,
/** 10601 */
Omnichannel_Sync_Config,
/** 10648 */
Omnichannel_voice_historical_analytics_preview,
/** 10558 */
Ongoing_conversation_Deprecated,
/** 10578 */
Operating_Hour,
/** 3 */
Opportunity,
/** 4208 */
Opportunity_Close,
/** 1083 */
Opportunity_Line,
/** 10353 */
Opportunity_Line_Detail_Deprecated,
/** 10352 */
Opportunity_Line_Resource_Category_Deprecated,
/** 10354 */
Opportunity_Line_Transaction_Category_Deprecated,
/** 10355 */
Opportunity_Line_Transaction_Classification_Deprecated,
/** 10356 */
Opportunity_Project_Price_List,
/** 4503 */
Opportunity_Relationship,
/** 953 */
Opportunity_Sales_Process,
/** 25 */
OpportunityCompetitors,
/** 10679 */
Option,
/** 9809 */
OptionSet,
/** 1088 */
Order,
/** 4209 */
Order_Close,
/** 10446 */
Order_Invoicing_Date,
/** 10447 */
Order_Invoicing_Product,
/** 10448 */
Order_Invoicing_Setup,
/** 10449 */
Order_Invoicing_Setup_Date,
/** 1089 */
Order_Line,
/** 1019 */
Organization,
/** 9699 */
Organization_Insights_Metric,
/** 9690 */
Organization_Insights_Notification,
/** 10029 */
Organization_Setting,
/** 4708 */
Organization_Statistic,
/** 1021 */
Organization_UI,
/** 10302 */
Organizational_Unit,
/** 10075 */
OrganizationDataSyncSubscription,
/** 10076 */
OrganizationDataSyncSubscriptionEntity,
/** 10672 */
Outbound_Configuration,
/** 10673 */
Outbound_message,
/** 7 */
Owner,
/** 4420 */
Owner_Mapping,
/** 10007 */
Package,
/** 10159 */
Pane_tab_configuration,
/** 10160 */
Pane_tool_configuration,
/** 10171 */
Parameter_definition,
/** 10529 */
Parameter_Deprecated,
/** 1095 */
Partner_Application,
/** 10450 */
Payment,
/** 10451 */
Payment_Detail,
/** 10452 */
Payment_Method,
/** 10453 */
Payment_Term,
/** 10049 */
PDF_Setting,
/** 10604 */
Persona_Security_Role_Mapping,
/** 9941 */
Personal_Document_Template,
/** 10602 */
Personal_quick_reply,
/** 10603 */
Personal_sound_setting,
/** 4210 */
Phone_Call,
/** 10651 */
Phone_Number,
/** 952 */
Phone_To_Case_Process,
/** 10202 */
Playbook,
/** 10199 */
Playbook_activity,
/** 10200 */
Playbook_activity_attribute,
/** 10198 */
Playbook_Callable_Context,
/** 10201 */
Playbook_category,
/** 10203 */
Playbook_template,
/** 4605 */
Plug_in_Assembly,
/** 4619 */
Plug_in_Trace_Log,
/** 4602 */
Plug_in_Type,
/** 4603 */
Plug_in_Type_Statistic,
/** 10093 */
PM_Inferred_Task,
/** 10094 */
PM_Recording,
/** 50 */
Position,
/** 8000 */
Post,
/** 10234 */
Post_Configuration,
/** 8002 */
Post_Regarding,
/** 8001 */
Post_Role,
/** 10235 */
Post_Rule_Configuration,
/** 10454 */
Postal_Code,
/** 10554 */
Power_BI_Configuration,
/** 10579 */
Presence,
/** 1022 */
Price_List,
/** 1026 */
Price_List_Item,
/** 10334 */
Pricing_Dimension,
/** 10335 */
Pricing_Dimension_Field_Name,
/** 1404 */
Principal_Sync_Attribute_Map,
/** 10303 */
Priority,
/** 1023 */
Privilege,
/** 31 */
Privilege_Object_Type_Code,
/** 10507 */
Problematic_Asset_Feedback,
/** 4703 */
Process,
/** 9650 */
Process_Configuration,
/** 4704 */
Process_Dependency,
/** 4706 */
Process_Log,
/** 10362 */
Process_Notes,
/** 4710 */
Process_Session,
/** 4724 */
Process_Stage,
/** 4712 */
Process_Trigger,
/** 10035 */
ProcessStageParameter,
/** 1024 */
Product,
/** 1025 */
Product_Association,
/** 10455 */
Product_Inventory,
/** 1028 */
Product_Relationship,
/** 10158 */
Productivity_pane_configuration,
/** 21 */
ProductSalesLiterature,
/** 10233 */
Profile_Album,
/** 10363 */
Project,
/** 10364 */
Project_Approval,
/** 10358 */
Project_Contract_Line_Detail,
/** 10330 */
Project_Contract_Line_Invoice_Schedule,
/** 10331 */
Project_Contract_Line_Milestone,
/** 10357 */
Project_Contract_Line_Resource_Category,
/** 10359 */
Project_Contract_Line_Transaction_Category,
/** 10360 */
Project_Contract_Line_Transaction_Classification,
/** 10361 */
Project_Contract_Project_Price_List,
/** 10365 */
Project_Parameter,
/** 10366 */
Project_Parameter_Price_List,
/** 10367 */
Project_Price_List,
/** 10324 */
Project_Service_Approval,
/** 10326 */
Project_Stages,
/** 10368 */
Project_Task,
/** 10369 */
Project_Task_Dependency,
/** 10370 */
Project_Task_Status_User,
/** 10371 */
Project_Team_Member,
/** 10372 */
Project_Team_Member_Sign_Up_Deprecated_in_v30,
/** 10373 */
Project_Transaction_Category_Deprecated,
/** 1048 */
Property,
/** 10121 */
Property_Asset_Association,
/** 1235 */
Property_Association,
/** 10120 */
Property_Definition,
/** 1333 */
Property_Instance,
/** 10122 */
Property_Log,
/** 1049 */
Property_Option_Set_Item,
/** 10123 */
Property_Template_Association,
/** 10605 */
Provider,
/** 10570 */
Provisioning_State,
/** 10013 */
ProvisionLanguageForUser,
/** 7101 */
Publisher,
/** 7102 */
Publisher_Address,
/** 10456 */
Purchase_Order,
/** 10457 */
Purchase_Order_Bill,
/** 10426 */
Purchase_Order_Business_Process,
/** 10458 */
Purchase_Order_Product,
/** 10459 */
Purchase_Order_Receipt,
/** 10460 */
Purchase_Order_Receipt_Product,
/** 10461 */
Purchase_Order_SubStatus,
/** 2002 */
Quarterly_Fiscal_Calendar,
/** 2020 */
Queue,
/** 2029 */
Queue_Item,
/** 2023 */
QueueItemCount,
/** 2024 */
QueueMemberCount,
/** 4406 */
Quick_Campaign,
/** 10555 */
Quick_reply,
/** 1084 */
Quote,
/** 10462 */
Quote_Booking_Incident,
/** 10463 */
Quote_Booking_Product,
/** 10464 */
Quote_Booking_Service,
/** 10465 */
Quote_Booking_Service_Task,
/** 10466 */
Quote_Booking_Setup,
/** 4211 */
Quote_Close,
/** 10467 */
Quote_Invoicing_Product,
/** 10468 */
Quote_Invoicing_Setup,
/** 1085 */
Quote_Line,
/** 10374 */
Quote_Line_Analytics_Breakdown,
/** 10378 */
Quote_Line_Detail,
/** 10375 */
Quote_Line_Invoice_Schedule,
/** 10377 */
Quote_Line_Milestone,
/** 10376 */
Quote_Line_Resource_Category,
/** 10379 */
Quote_Line_Transaction_Category,
/** 10380 */
Quote_Line_Transaction_Classification,
/** 10381 */
Quote_Project_Price_List,
/** 1144 */
Rating_Model,
/** 1142 */
Rating_Value,
/** 9300 */
Record_Creation_and_Update_Rule,
/** 9301 */
Record_Creation_and_Update_Rule_Item,
/** 4250 */
Recurrence_Rule,
/** 4251 */
Recurring_Appointment,
/** 9814 */
Relationship_Attribute,
/** 9813 */
Relationship_Entity,
/** 4500 */
Relationship_Role,
/** 4501 */
Relationship_Role_Map,
/** 1140 */
Replication_Backlog,
/** 9100 */
Report,
/** 9104 */
Report_Link,
/** 9102 */
Report_Related_Category,
/** 9101 */
Report_Related_Entity,
/** 9103 */
Report_Visibility,
/** 10304 */
Requirement_Characteristic,
/** 10321 */
Requirement_Dependency,
/** 10305 */
Requirement_Group,
/** 10306 */
Requirement_Organization_Unit,
/** 10307 */
Requirement_Relationship,
/** 10308 */
Requirement_Resource_Category,
/** 10309 */
Requirement_Resource_Preference,
/** 10310 */
Requirement_Status,
/** 10508 */
Resolution,
/** 4002 */
Resource,
/** 10382 */
Resource_Assignment,
/** 10383 */
Resource_Assignment_Detail_Deprecated_in_v20,
/** 4010 */
Resource_Expansion,
/** 4007 */
Resource_Group,
/** 10111 */
resource_group_data_source,
/** 10469 */
Resource_Pay_Type,
/** 10386 */
Resource_Request,
/** 10311 */
Resource_Requirement,
/** 10312 */
Resource_Requirement_Detail,
/** 10490 */
Resource_Restriction_Deprecated,
/** 4006 */
Resource_Specification,
/** 10313 */
Resource_Territory,
/** 10351 */
Result_Cache,
/** 90001 */
RevokeInheritedAccessRecordsTracker,
/** 4579 */
Ribbon_Client_Metadata,
/** 1116 */
Ribbon_Command,
/** 1115 */
Ribbon_Context_Group,
/** 1130 */
Ribbon_Difference,
/** 9880 */
Ribbon_Metadata_To_Process,
/** 1117 */
Ribbon_Rule,
/** 1113 */
Ribbon_Tab_To_Command_Mapping,
/** 10078 */
Rich_Text_Attachment,
/** 10470 */
RMA,
/** 10471 */
RMA_Product,
/** 10472 */
RMA_Receipt,
/** 10473 */
RMA_Receipt_Product,
/** 10474 */
RMA_SubStatus,
/** 10387 */
Role_competency_requirement,
/** 10385 */
Role_Price,
/** 10384 */
Role_Price_Markup,
/** 1037 */
Role_Template,
/** 10388 */
Role_Utilization,
/** 9604 */
Rollup_Field,
/** 9511 */
Rollup_Job,
/** 9510 */
Rollup_Properties,
/** 9602 */
Rollup_Query,
/** 10552 */
Routing_configuration,
/** 10553 */
Routing_configuration_step,
/** 8181 */
Routing_Rule_Set,
/** 10548 */
Routing_Rule_Set_Setting,
/** 10580 */
RoutingRequest,
/** 10475 */
RTV,
/** 10476 */
RTV_Product,
/** 10477 */
RTV_Substatus,
/** 10572 */
Rule_Item_10572,
/** 8199 */
Rule_Item_8199,
/** 10544 */
Rulesetentitymapping,
/** 7200 */
RuntimeDependency,
/** 1070 */
Sales_Attachment,
/** 1038 */
Sales_Literature,
/** 32 */
Sales_Process_Instance,
/** 10223 */
salesinsightssettings,
/** 10520 */
SalesSiteMap,
/** 1309 */
Saved_Organization_Insights_Configuration,
/** 4230 */
Saved_View,
/** 10541 */
Scenario,
/** 10314 */
Schedule_Board_Setting,
/** 10322 */
Scheduling_Feature_Flag,
/** 4005 */
Scheduling_Group,
/** 10315 */
Scheduling_Parameter,
/** 10697 */
Script_Task_Trigger,
/** 10696 */
Scriptlet,
/** 4606 */
Sdk_Message,
/** 4607 */
Sdk_Message_Filter,
/** 4613 */
Sdk_Message_Pair,
/** 4608 */
Sdk_Message_Processing_Step,
/** 4615 */
Sdk_Message_Processing_Step_Image,
/** 4616 */
Sdk_Message_Processing_Step_Secure_Configuration,
/** 4609 */
Sdk_Message_Request,
/** 4614 */
Sdk_Message_Request_Field,
/** 4610 */
Sdk_Message_Response,
/** 4611 */
Sdk_Message_Response_Field,
/** 10581 */
Search_Configuration,
/** 10055 */
Search_provider,
/** 10080 */
Search_Telemetry,
/** 1036 */
Security_Role,
/** 10611 */
Self_service,
/** 2001 */
Semiannual_Fiscal_Calendar,
/** 10582 */
Sentiment_analysis,
/** 10595 */
Sentiment_daily_topic,
/** 10596 */
Sentiment_daily_topic_keyword,
/** 10597 */
Sentiment_daily_topic_trending,
/** 4001 */
Service,
/** 4214 */
Service_Activity,
/** 10051 */
Service_Configuration,
/** 20 */
Service_Contract_Contact,
/** 4618 */
Service_Endpoint,
/** 101 */
Service_Plan,
/** 10478 */
Service_Task_Type,
/** 10521 */
ServicesSiteMap,
/** 10573 */
Session,
/** 10619 */
Session_Characteristic,
/** 10209 */
Session_Data_Deprecated,
/** 10583 */
Session_event,
/** 10699 */
Session_Information,
/** 10584 */
Session_participant,
/** 10210 */
Session_Participant_Data_Deprecated,
/** 10598 */
Session_Sentiment,
/** 10149 */
Session_Template,
/** 10527 */
Session_Templates_Deprecated,
/** 10700 */
Session_Transfer,
/** 10030 */
Setting_Definition,
/** 10522 */
SettingsSiteMap,
/** 9509 */
SharePoint_Data,
/** 9507 */
Sharepoint_Document,
/** 9502 */
SharePoint_Site,
/** 10479 */
Ship_Via,
/** 10218 */
SI_Key_Value_Config,
/** 10217 */
siconfig,
/** 9951 */
Similarity_Rule,
/** 4009 */
Site,
/** 4709 */
Site_Map,
/** 10620 */
Skill_Attachment_Rule,
/** 10626 */
Skill_finder_model,
/** 9750 */
SLA,
/** 9751 */
SLA_Item,
/** 10052 */
SLA_KPI,
/** 9752 */
SLA_KPI_Instance,
/** 10175 */
Smartassist_configuration,
/** 10652 */
SMS_Engagement_Context,
/** 10653 */
SMS_Number,
/** 10654 */
SMS_Number_settings,
/** 4216 */
Social_Activity,
/** 99 */
Social_Profile,
/** 1300 */
SocialInsightsConfiguration,
/** 7100 */
Solution,
/** 7103 */
Solution_Component,
/** 10000 */
Solution_Component_Attribute_Configuration,
/** 10001 */
Solution_Component_Configuration,
/** 10012 */
Solution_Component_Data_Source,
/** 7104 */
Solution_Component_Definition,
/** 10002 */
Solution_Component_Relationship_Configuration,
/** 10011 */
Solution_Component_Summary,
/** 10099 */
Solution_Health_Rule,
/** 10100 */
Solution_Health_Rule_Argument,
/** 10101 */
Solution_Health_Rule_Set,
/** 10003 */
Solution_History,
/** 10004 */
Solution_History_Data_Source,
/** 9890 */
SolutionHistoryData,
/** 10607 */
Sound_notification_setting,
/** 10009 */
StageSolutionUpload,
/** 1075 */
Status_Map,
/** 1043 */
String_Map,
/** 129 */
Subject,
/** 29 */
Subscription,
/** 1072 */
Subscription_Clients,
/** 37 */
Subscription_Manually_Tracked_Object,
/** 45 */
Subscription_Statistic_Offline,
/** 46 */
Subscription_Statistic_Outlook,
/** 47 */
Subscription_Sync_Entry_Offline,
/** 48 */
Subscription_Sync_Entry_Outlook,
/** 33 */
Subscription_Synchronization_Information,
/** 10227 */
Suggested_Activity,
/** 10228 */
Suggested_Activity_Data_Source,
/** 10229 */
Suggested_Contact,
/** 10230 */
Suggested_contacts_data_source,
/** 10184 */
Suggestion_Interaction,
/** 10185 */
Suggestion_request_payload,
/** 1190 */
SuggestionCardTemplate,
/** 10186 */
Suggestions_Model_Summary,
/** 10187 */
Suggestions_Setting,
/** 10629 */
Survey_Answer_Option,
/** 10638 */
Survey_Question,
/** 10637 */
Survey_Question_Sequence,
/** 10630 */
Survey_Response,
/** 10631 */
Survey_Response_Value,
/** 1401 */
Sync_Attribute_Mapping,
/** 1400 */
Sync_Attribute_Mapping_Profile,
/** 9869 */
Sync_Error,
/** 7000 */
System_Application_Metadata,
/** 1111 */
System_Chart,
/** 1030 */
System_Form,
/** 4700 */
System_Job,
/** 51 */
System_User_Manager_Map,
/** 14 */
System_User_Principal,
/** 10316 */
System_User_Scheduler_Setting,
/** 42 */
SystemUser_BusinessUnit_Entity_Map,
/** 60 */
SystemUserAuthorizationChangeTracker,
/** 10599 */
Tag,
/** 4212 */
Task,
/** 10480 */
Tax_Code,
/** 10481 */
Tax_Code_Detail,
/** 9 */
Team,
/** 1203 */
Team_Profiles,
/** 1403 */
Team_Sync_Attribute_Mapping_Profiles,
/** 92 */
Team_template,
/** 10073 */
TeamMobileOfflineProfileMembership,
/** 10256 */
Teams_Dialer_Admin_settings,
/** 10671 */
Teams_Engagement_Context,
/** 10124 */
Template_For_Properties,
/** 10150 */
Template_Parameter,
/** 10530 */
Template_Tag_Deprecated,
/** 2013 */
Territory,
/** 9945 */
Text_Analytics_Entity_Mapping,
/** 9948 */
Text_Analytics_Topic,
/** 2015 */
Theme,
/** 10407 */
Three_Dimensional_Model,
/** 10389 */
Time_Entry,
/** 10318 */
Time_Group_Detail,
/** 10390 */
Time_Off_Calendar,
/** 10482 */
Time_Off_Request,
/** 10404 */
Time_Source,
/** 9932 */
Time_Stamp_Date_Mapping,
/** 4810 */
Time_Zone_Definition,
/** 4812 */
Time_Zone_Localized_Name,
/** 4811 */
Time_Zone_Rule,
/** 10703 */
Toolbar,
/** 10702 */
Toolbar_Button,
/** 9946 */
Topic_History,
/** 9944 */
Topic_Model,
/** 9942 */
Topic_Model_Configuration,
/** 9943 */
Topic_Model_Execution_History,
/** 10039 */
Tour,
/** 8050 */
Trace,
/** 8051 */
Trace_Association,
/** 8052 */
Trace_Regarding,
/** 10704 */
Trace_Source_Setting,
/** 35 */
Tracking_information_for_deleted_entities,
/** 10623 */
Training_data_import_configuration,
/** 10625 */
Training_record,
/** 10391 */
Transaction_Category,
/** 10392 */
Transaction_Category_Classification,
/** 10393 */
Transaction_Category_Hierarchy_Element,
/** 10394 */
Transaction_Category_Price,
/** 10395 */
Transaction_Connection,
/** 10319 */
Transaction_Origin,
/** 10396 */
Transaction_Type,
/** 10585 */
Transcript,
/** 4426 */
Transformation_Mapping,
/** 4427 */
Transformation_Parameter_Mapping,
/** 951 */
Translation_Process,
/** 10662 */
Twitter_account,
/** 10667 */
Twitter_Engagement_Context,
/** 10663 */
Twitter_handle,
/** 10674 */
UII_Action,
/** 10675 */
UII_Audit,
/** 10676 */
UII_Context,
/** 10678 */
UII_Non_Hosted_Application,
/** 10680 */
UII_Saved_Session,
/** 10681 */
UII_Session_Transfer,
/** 10682 */
UII_Workflow,
/** 10683 */
UII_Workflow_Step,
/** 10684 */
UII_Workflow_Step_Mapping,
/** 10705 */
Unified_Interface_Settings,
/** 10545 */
Unified_routing_diagnostic,
/** 10546 */
Unified_routing_run,
/** 10108 */
Unified_Routing_Setup_Tracker,
/** 10483 */
Unique_Number,
/** 1055 */
Unit,
/** 1056 */
Unit_Group,
/** 2012 */
Unresolved_Address,
/** 10226 */
UntrackedAppointment,
/** 4220 */
UntrackedEmail,
/** 10104 */
Upgrade_Run,
/** 10105 */
Upgrade_Step,
/** 10106 */
Upgrade_Version,
/** 10608 */
UR_notification_template,
/** 10609 */
UR_Notification_Template_Mapping,
/** 8 */
User,
/** 7001 */
User_Application_Metadata,
/** 1112 */
User_Chart,
/** 1031 */
User_Dashboard,
/** 2501 */
User_Entity_Instance_Data,
/** 2500 */
User_Entity_UI_Settings,
/** 1086 */
User_Fiscal_Calendar,
/** 2016 */
User_Mapping,
/** 52 */
User_Search_Facet,
/** 10707 */
User_Setting,
/** 10610 */
User_settings_10610,
/** 150 */
User_settings_150,
/** 10397 */
User_Work_History,
/** 10074 */
UserMobileOfflineProfileMembership,
/** 1039 */
View,
/** 78 */
Virtual_Entity_Data_Provider,
/** 85 */
Virtual_Entity_Data_Source,
/** 10072 */
Virtual_Entity_Metadata,
/** 10112 */
Virtual_Resource_Group_Resource,
/** 10236 */
Wall_View,
/** 10484 */
Warehouse,
/** 9333 */
Web_Resource,
/** 4800 */
Web_Wizard,
/** 4803 */
Web_Wizard_Access_Privilege,
/** 10664 */
WeChat_account,
/** 10668 */
WeChat_Engagement_Context,
/** 10665 */
WhatsApp_account,
/** 10669 */
WhatsApp_Engagement_Context,
/** 10666 */
WhatsApp_number,
/** 10708 */
Window_Navigation_Rule,
/** 4802 */
Wizard_Page,
/** 10485 */
Work_Order,
/** 10429 */
Work_Order_Business_Process,
/** 10486 */
Work_Order_Characteristic_Deprecated,
/** 10487 */
Work_Order_Details_Generation_Queue_Deprecated,
/** 10488 */
Work_Order_Incident,
/** 10489 */
Work_Order_Product,
/** 10511 */
Work_Order_Resolution,
/** 10491 */
Work_Order_Service,
/** 10492 */
Work_Order_Service_Task,
/** 10493 */
Work_Order_Substatus,
/** 10494 */
Work_Order_Type,
/** 10559 */
Work_Stream,
/** 10616 */
Work_stream_capacity_profile,
/** 10320 */
Work_template,
/** 10036 */
Workflow_Binary,
/** 4702 */
Workflow_Wait_Subscription
}
enum ComponentState {
/** 2 */
Deleted,
/** 3 */
Deleted_Unpublished,
/** 0 */
Published,
/** 1 */
Unpublished
}
enum MatchingEntityTypeCode {
/** 1 */
Account,
/** 10323 */
Account_Project_Price_List,
/** 16 */
AccountLeads,
/** 8040 */
ACIViewMapper,
/** 10686 */
Action_Call,
/** 10685 */
Action_Call_Workflow,
/** 9962 */
Action_Card,
/** 10219 */
Action_Card_Regarding,
/** 10220 */
Action_Card_Role_Setting,
/** 9983 */
Action_Card_Type,
/** 9973 */
Action_Card_User_Settings,
/** 10165 */
Action_Input_Parameter,
/** 10166 */
Action_Output_Parameter,
/** 9968 */
ActionCardUserState,
/** 4200 */
Activity,
/** 10050 */
Activity_File_Attachment,
/** 10107 */
Activity_monitor,
/** 135 */
Activity_Party,
/** 10292 */
Actual,
/** 10332 */
Actual_Data_Export_Deprecated,
/** 10174 */
Adaptive_Card_Configuration,
/** 1071 */
Address,
/** 10205 */
admin_settings_entity,
/** 10587 */
AdminAppState,
/** 9949 */
Advanced_Similarity_Rule,
/** 10162 */
Agent_script,
/** 10688 */
Agent_Script_Answer,
/** 10163 */
Agent_script_step,
/** 10701 */
Agent_Script_Task,
/** 10687 */
Agent_Script_Task_Category,
/** 10588 */
Agent_Status_history,
/** 10413 */
Agreement,
/** 10414 */
Agreement_Booking_Date,
/** 10415 */
Agreement_Booking_Incident,
/** 10416 */
Agreement_Booking_Product,
/** 10417 */
Agreement_Booking_Service,
/** 10418 */
Agreement_Booking_Service_Task,
/** 10419 */
Agreement_Booking_Setup,
/** 10428 */
Agreement_Business_Process,
/** 10420 */
Agreement_Invoice_Date,
/** 10421 */
Agreement_Invoice_Product,
/** 10422 */
Agreement_Invoice_Setup,
/** 10423 */
Agreement_Substatus,
/** 10087 */
AI_Builder_Dataset,
/** 10088 */
AI_Builder_Dataset_File,
/** 10089 */
AI_Builder_Dataset_Record,
/** 10090 */
AI_Builder_Datasets_Container,
/** 10091 */
AI_Builder_File,
/** 10092 */
AI_Builder_File_Attached_Data,
/** 402 */
AI_Configuration,
/** 10081 */
AI_Form_Processing_Document,
/** 401 */
AI_Model,
/** 10084 */
AI_Object_Detection_Bounding_Box,
/** 10082 */
AI_Object_Detection_Image,
/** 10085 */
AI_Object_Detection_Image_Mapping,
/** 10083 */
AI_Object_Detection_Label,
/** 400 */
AI_Template,
/** 10095 */
Analysis_Component,
/** 10096 */
Analysis_Job,
/** 10097 */
Analysis_Result,
/** 10098 */
Analysis_Result_Detail,
/** 132 */
Announcement,
/** 2000 */
Annual_Fiscal_Calendar,
/** 9011 */
App_Config_Master,
/** 9012 */
App_Configuration,
/** 9013 */
App_Configuration_Instance,
/** 9007 */
App_Module_Component,
/** 9009 */
App_Module_Roles,
/** 10526 */
App_Parameter_Definition_Deprecated,
/** 10144 */
App_profile,
/** 10145 */
Application_Extension,
/** 4707 */
Application_File,
/** 1120 */
Application_Ribbons,
/** 10146 */
Application_Tab_Template,
/** 10528 */
Application_Tab_Template_Deprecated,
/** 10531 */
Application_Type_Deprecated,
/** 10021 */
ApplicationUser,
/** 8700 */
AppModule_Metadata,
/** 8702 */
AppModule_Metadata_Async_Operation,
/** 8701 */
AppModule_Metadata_Dependency,
/** 4201 */
Appointment,
/** 127 */
Article,
/** 1082 */
Article_Comment,
/** 1016 */
Article_Template,
/** 10114 */
Asset_Category_Template_Association,
/** 10506 */
Asset_Suggestion,
/** 10115 */
Asset_Template_Association,
/** 10549 */
Assignment_Configuration,
/** 10550 */
Assignment_Configuration_Step,
/** 10621 */
Attach_Skill,
/** 1001 */
Attachment_1001,
/** 1002 */
Attachment_1002,
/** 9808 */
Attribute,
/** 4601 */
Attribute_Map,
/** 10606 */
Audio_File,
/** 10689 */
Audit_Diagnostics_Setting,
/** 4567 */
Auditing,
/** 1094 */
Authorization_Server,
/** 10224 */
Auto_Capture_Rule,
/** 10225 */
Auto_Capture_Settings,
/** 10109 */
Available_Times,
/** 10110 */
Available_Times_Data_Source,
/** 9936 */
Azure_Service_Connection,
/** 10325 */
Batch_Job,
/** 1150 */
Bookable_Resource,
/** 10293 */
Bookable_Resource_Association,
/** 1145 */
Bookable_Resource_Booking,
/** 1146 */
Bookable_Resource_Booking_Header,
/** 10500 */
Bookable_Resource_Booking_Quick_Note,
/** 4421 */
Bookable_Resource_Booking_to_Exchange_Id_Mapping,
/** 10615 */
Bookable_Resource_Capacity_Profile,
/** 1147 */
Bookable_Resource_Category,
/** 1149 */
Bookable_Resource_Category_Assn,
/** 1148 */
Bookable_Resource_Characteristic,
/** 1151 */
Bookable_Resource_Group,
/** 10294 */
Booking_Alert,
/** 10295 */
Booking_Alert_Status,
/** 10296 */
Booking_Change,
/** 10424 */
Booking_Journal,
/** 10297 */
Booking_Rule,
/** 10298 */
Booking_Setup_Metadata,
/** 1152 */
Booking_Status,
/** 10425 */
Booking_Timestamp,
/** 10040 */
BotContent,
/** 4425 */
Bulk_Delete_Failure,
/** 4424 */
Bulk_Delete_Operation,
/** 4405 */
Bulk_Operation_Log,
/** 10299 */
Business_Closure,
/** 4232 */
Business_Data_Localized_Label,
/** 4725 */
Business_Process_Flow_Instance,
/** 10 */
Business_Unit,
/** 6 */
Business_Unit_Map,
/** 4003 */
Calendar,
/** 4004 */
Calendar_Rule,
/** 301 */
Callback_Registration,
/** 4400 */
Campaign,
/** 4402 */
Campaign_Activity,
/** 4404 */
Campaign_Activity_Item,
/** 4403 */
Campaign_Item,
/** 4401 */
Campaign_Response,
/** 300 */
Canvas_App,
/** 10031 */
CanvasApp_Extended_Metadata,
/** 10551 */
Capacity_Profile,
/** 10018 */
CascadeGrantRevokeAccessRecordsTracker,
/** 10019 */
CascadeGrantRevokeAccessVersionTracker,
/** 112 */
Case,
/** 10177 */
Case_Enrichment,
/** 4206 */
Case_Resolution,
/** 10178 */
Case_Suggestion,
/** 10179 */
Case_Suggestion_Request_Payload,
/** 10180 */
Case_Suggestions_Data_Souce,
/** 10427 */
Case_to_Work_Order_Business_Process,
/** 10192 */
Case_Topic,
/** 10195 */
Case_topic_Incident_mapping,
/** 10193 */
Case_Topic_Setting,
/** 10194 */
Case_Topic_Summary,
/** 10066 */
Catalog,
/** 10067 */
Catalog_Assignment,
/** 9959 */
Category,
/** 10512 */
CFS_IoT_Alert_Process_Flow,
/** 10540 */
channel,
/** 3005 */
Channel_Access_Profile,
/** 9400 */
Channel_Access_Profile_Rule,
/** 9401 */
Channel_Access_Profile_Rule_Item,
/** 10589 */
Channel_Capability,
/** 10562 */
Channel_Configuration,
/** 1236 */
Channel_Property,
/** 1234 */
Channel_Property_Group,
/** 10156 */
Channel_Provider_10156,
/** 10523 */
Channel_Provider_10523,
/** 10563 */
Channel_State_Configuration,
/** 1141 */
Characteristic,
/** 10624 */
Characteristic_mapping,
/** 10628 */
Chat_Authentication_Settings,
/** 10633 */
Chat_Widget,
/** 10632 */
Chat_Widget_Languagedeprecated,
/** 10635 */
Chat_Widget_Location,
/** 10042 */
Chatbot,
/** 10043 */
Chatbot_subcomponent,
/** 113 */
Child_Incident_Count,
/** 10300 */
Client_Extension,
/** 36 */
Client_update,
/** 4417 */
Column_Mapping,
/** 8005 */
Comment,
/** 4215 */
Commitment,
/** 10649 */
Communication_Provider_Setting,
/** 10650 */
Communication_Provider_Setting_Entry,
/** 10328 */
Competency_Requirement_Deprecated,
/** 123 */
Competitor,
/** 1004 */
Competitor_Address,
/** 1006 */
Competitor_Product,
/** 26 */
CompetitorSalesLiterature,
/** 10005 */
Component_Layer,
/** 10006 */
Component_Layer_Data_Source,
/** 10301 */
Configuration_10301,
/** 10690 */
Configuration_10690,
/** 3234 */
Connection,
/** 10037 */
Connection_Reference,
/** 3231 */
Connection_Role,
/** 3233 */
Connection_Role_Object_Type_Code,
/** 372 */
Connector,
/** 2 */
Contact,
/** 10329 */
Contact_Price_List,
/** 17 */
ContactInvoices,
/** 22 */
ContactLeads,
/** 19 */
ContactOrders,
/** 18 */
ContactQuotes,
/** 10565 */
Context_item_value,
/** 10568 */
Context_variable,
/** 1010 */
Contract,
/** 1011 */
Contract_Line,
/** 10405 */
Contract_Line_Detail_Performance,
/** 10406 */
Contract_Performance,
/** 2011 */
Contract_Template,
/** 10564 */
Conversation,
/** 10590 */
Conversation_Action,
/** 10591 */
Conversation_Action_Locale,
/** 10617 */
Conversation_Capacity_profile,
/** 10618 */
Conversation_Characteristic,
/** 10206 */
Conversation_Data_Deprecated,
/** 10567 */
Conversation_Sentiment,
/** 10643 */
Conversation_Topic,
/** 10646 */
Conversation_topic_Conversation_mapping,
/** 10644 */
Conversation_Topic_Setting,
/** 10645 */
Conversation_Topic_Summary,
/** 10642 */
ConversationInsight,
/** 10641 */
conversationsuggestionrequestpayload,
/** 10041 */
ConversationTranscript,
/** 10698 */
CTI_Search,
/** 9105 */
Currency,
/** 10069 */
Custom_API,
/** 10070 */
Custom_API_Request_Parameter,
/** 10071 */
Custom_API_Response_Property,
/** 9753 */
Custom_Control,
/** 9755 */
Custom_Control_Default_Config,
/** 9754 */
Custom_Control_Resource,
/** 10561 */
Custom_messaging_account,
/** 10660 */
Custom_messaging_channel,
/** 10658 */
Custom_Messaging_Engagement_Context,
/** 10116 */
Customer_Asset,
/** 10117 */
Customer_Asset_Attachment,
/** 10118 */
Customer_Asset_Category,
/** 4502 */
Customer_Relationship,
/** 10196 */
Customer_Service_historical_analytics,
/** 10238 */
Customer_Voice_alert,
/** 10239 */
Customer_Voice_alert_rule,
/** 10241 */
Customer_Voice_file_response,
/** 10242 */
Customer_Voice_localized_survey_email_template,
/** 10243 */
Customer_Voice_project,
/** 10246 */
Customer_Voice_satisfaction_metric,
/** 10247 */
Customer_Voice_survey,
/** 10240 */
Customer_Voice_survey_email_template,
/** 10248 */
Customer_Voice_survey_invite,
/** 10244 */
Customer_Voice_survey_question,
/** 10245 */
Customer_Voice_survey_question_response,
/** 10249 */
Customer_Voice_survey_reminder,
/** 10250 */
Customer_Voice_survey_response,
/** 10251 */
Customer_Voice_unsubscribed_recipient,
/** 10691 */
Customization_File,
/** 10188 */
Data_Analytics_Admin_Settings_Deprecated,
/** 10189 */
Data_Analytics_Report,
/** 4410 */
Data_Import,
/** 10014 */
Data_Lake_Folder,
/** 10015 */
Data_Lake_Folder_Permission,
/** 10016 */
Data_Lake_Workspace,
/** 10017 */
Data_Lake_Workspace_Permission,
/** 4411 */
Data_Map,
/** 4450 */
Data_Performance_Dashboard,
/** 10103 */
Database_Version,
/** 418 */
Dataflow,
/** 10542 */
Decision_contract,
/** 10543 */
Decision_rule_set,
/** 10333 */
Delegation,
/** 9961 */
DelveActionHub,
/** 7105 */
Dependency,
/** 7108 */
Dependency_Feature,
/** 7106 */
Dependency_Node,
/** 10191 */
Deprecated_Dynamics_Customer_Service_Analytics,
/** 10557 */
Deprecated_Workstream_Entity_Configuration,
/** 1013 */
Discount,
/** 1080 */
Discount_List,
/** 4102 */
Display_String,
/** 4101 */
Display_String_Map,
/** 9508 */
Document_Location,
/** 1189 */
Document_Suggestions,
/** 9940 */
Document_Template,
/** 4414 */
Duplicate_Detection_Rule,
/** 4415 */
Duplicate_Record,
/** 4416 */
Duplicate_Rule_Condition,
/** 4202 */
Email,
/** 4023 */
Email_Hash,
/** 4299 */
Email_Search,
/** 9605 */
Email_Server_Profile,
/** 9997 */
Email_Signature,
/** 2010 */
Email_Template,
/** 9700 */
Entitlement,
/** 10430 */
Entitlement_Application,
/** 9701 */
Entitlement_Channel,
/** 7272 */
Entitlement_Contact,
/** 9704 */
Entitlement_Entity_Allocation_Type_Mapping,
/** 6363 */
Entitlement_Product,
/** 9702 */
Entitlement_Template,
/** 9703 */
Entitlement_Template_Channel,
/** 4545 */
Entitlement_Template_Product,
/** 10592 */
Entity_10592,
/** 9800 */
Entity_9800,
/** 430 */
Entity_Analytics_Config,
/** 10515 */
Entity_Configuration,
/** 432 */
Entity_Image_Configuration,
/** 9810 */
Entity_Key,
/** 4600 */
Entity_Map,
/** 9811 */
Entity_Relationship,
/** 10556 */
Entity_Routing_Context,
/** 10693 */
Entity_Search,
/** 10692 */
Entity_Type,
/** 10221 */
EntityRankingRule,
/** 380 */
Environment_Variable_Definition,
/** 381 */
Environment_Variable_Value,
/** 10336 */
Estimate,
/** 10337 */
Estimate_Line,
/** 10706 */
Event,
/** 4120 */
Exchange_Sync_Id_Mapping,
/** 4711 */
Expander_Event,
/** 10338 */
Expense,
/** 10339 */
Expense_Category,
/** 10340 */
Expense_Receipt,
/** 955 */
Expired_Process,
/** 10010 */
ExportSolutionUpload,
/** 3008 */
External_Party,
/** 9987 */
External_Party_Item,
/** 10656 */
Facebook_Application,
/** 10655 */
Facebook_Engagement_Context,
/** 10657 */
Facebook_Page,
/** 4000 */
FacilityEquipment,
/** 10341 */
Fact,
/** 4204 */
Fax,
/** 9958 */
Feedback,
/** 10342 */
Field_Computation,
/** 1201 */
Field_Permission,
/** 1200 */
Field_Security_Profile,
/** 10431 */
Field_Service_Price_List_Item,
/** 10432 */
Field_Service_Setting,
/** 10433 */
Field_Service_SLA_Configuration,
/** 10434 */
Field_Service_System_Job,
/** 44 */
Field_Sharing,
/** 55 */
FileAttachment,
/** 10237 */
Filter,
/** 30 */
Filter_Template,
/** 10343 */
Find_Work_Event_Deprecated_in_v30,
/** 2004 */
Fixed_Monthly_Fiscal_Calendar,
/** 10033 */
Flow_Machine,
/** 10034 */
Flow_Machine_Group,
/** 4720 */
Flow_Session,
/** 10222 */
flowcardtype,
/** 8003 */
Follow,
/** 10213 */
Forecast,
/** 10211 */
Forecast_Configuration,
/** 10212 */
Forecast_definition,
/** 10214 */
Forecast_recurrence,
/** 10694 */
Form,
/** 10317 */
Fulfillment_Preference,
/** 10119 */
Functional_Location,
/** 10215 */
GDPRData,
/** 10575 */
Geo_Location_Provider,
/** 10516 */
Geofence,
/** 10517 */
Geofence_Event,
/** 10518 */
Geofencing_Settings,
/** 10513 */
Geolocation_Settings,
/** 10514 */
Geolocation_Tracking,
/** 54 */
Global_Search_Configuration,
/** 9600 */
Goal,
/** 9603 */
Goal_Metric,
/** 10038 */
Help_Page,
/** 8840 */
Hierarchy_Rule,
/** 9919 */
Hierarchy_Security_Configuration,
/** 9996 */
HolidayWrapper,
/** 10677 */
Hosted_Control,
/** 10232 */
icebreakersconfig,
/** 431 */
Image_Attribute_Configuration,
/** 1007 */
Image_Descriptor,
/** 4413 */
Import_Data,
/** 4428 */
Import_Entity_Mapping,
/** 9107 */
Import_Job,
/** 4423 */
Import_Log,
/** 4412 */
Import_Source_File,
/** 9931 */
Incident_KnowledgeBaseRecord,
/** 10435 */
Incident_Type,
/** 10436 */
Incident_Type_Characteristic,
/** 10437 */
Incident_Type_Product,
/** 10441 */
Incident_Type_Requirement_Group,
/** 10505 */
Incident_Type_Resolution,
/** 10438 */
Incident_Type_Service,
/** 10439 */
Incident_Type_Service_Task,
/** 10503 */
Incident_Type_Suggestion_Result,
/** 10504 */
Incident_Type_Suggestion_Run_History,
/** 10440 */
Incident_Types_Setup,
/** 126 */
Indexed_Article,
/** 10190 */
Insights,
/** 10411 */
Inspection,
/** 10409 */
Inspection_Attachment,
/** 10412 */
Inspection_Response,
/** 10408 */
Inspection_Template,
/** 10410 */
Inspection_Template_Version,
/** 10344 */
Integration_Job,
/** 10345 */
Integration_Job_Detail,
/** 3000 */
Integration_Status,
/** 4011 */
Inter_Process_Lock,
/** 9986 */
Interaction_for_Email,
/** 1003 */
Internal_Address,
/** 10068 */
Internal_Catalog_Assignment,
/** 7107 */
Invalid_Dependency,
/** 10442 */
Inventory_Adjustment,
/** 10443 */
Inventory_Adjustment_Product,
/** 10444 */
Inventory_Journal,
/** 10445 */
Inventory_Transfer,
/** 1090 */
Invoice,
/** 10346 */
Invoice_Frequency,
/** 10347 */
Invoice_Frequency_Detail,
/** 1091 */
Invoice_Line,
/** 10348 */
Invoice_Line_Detail,
/** 10327 */
Invoice_Process,
/** 10126 */
IoT_Alert,
/** 10142 */
IoT_Alert_to_Case_Process,
/** 10127 */
IoT_Device,
/** 10128 */
IoT_Device_Category,
/** 10129 */
IoT_Device_Command,
/** 10130 */
IoT_Device_Command_Definition,
/** 10131 */
IoT_Device_Data_History,
/** 10132 */
IoT_Device_Property,
/** 10133 */
IoT_Device_Registration_History,
/** 10134 */
IoT_Device_Visualization_Configuration,
/** 10135 */
IoT_Field_Mapping,
/** 10136 */
IoT_Property_Definition,
/** 10137 */
IoT_Provider,
/** 10138 */
IoT_Provider_Instance,
/** 10139 */
IoT_Settings,
/** 4705 */
ISV_Config,
/** 10349 */
Journal,
/** 10350 */
Journal_Line,
/** 10181 */
KB_Enrichment,
/** 10064 */
KeyVaultReference,
/** 9953 */
Knowledge_Article,
/** 9960 */
Knowledge_Article_Category,
/** 10056 */
Knowledge_Article_Image,
/** 9954 */
Knowledge_Article_Incident,
/** 10059 */
Knowledge_article_language_setting,
/** 10182 */
Knowledge_Article_Suggestion,
/** 10183 */
Knowledge_Article_Suggestion_Data_Source,
/** 10061 */
Knowledge_Article_Template,
/** 9955 */
Knowledge_Article_Views,
/** 9930 */
Knowledge_Base_Record,
/** 10053 */
Knowledge_Federated_Article,
/** 10054 */
Knowledge_FederatedArticle_Incident,
/** 10057 */
Knowledge_Interaction_Insight,
/** 10060 */
Knowledge_personalization,
/** 10197 */
Knowledge_search_analytics,
/** 10063 */
Knowledge_search_filter,
/** 10058 */
Knowledge_Search_Insight,
/** 9947 */
Knowledge_Search_Model,
/** 10062 */
Knowledge_search_personal_filter_config,
/** 10207 */
KPI_Event_Data,
/** 10208 */
KPI_Event_Definition,
/** 10594 */
Language_10594,
/** 9957 */
Language_9957,
/** 10695 */
Language_Module,
/** 9875 */
Language_Provisioning_State,
/** 4 */
Lead,
/** 1017 */
Lead_Address,
/** 954 */
Lead_To_Opportunity_Sales_Process,
/** 24 */
LeadCompetitors,
/** 27 */
LeadProduct,
/** 4207 */
Letter,
/** 2027 */
License,
/** 8006 */
Like,
/** 10661 */
LINE_account,
/** 10659 */
LINE_Engagement_Context,
/** 10102 */
List_Operation,
/** 4418 */
List_Value_Mapping,
/** 10634 */
Live_Chat_Context,
/** 10593 */
Live_work_item_event,
/** 10566 */
Live_Work_Item_Participant_Deprecated,
/** 9201 */
LocalConfigStore,
/** 10569 */
Localization,
/** 10636 */
Localized_Survey_Question_Deprecated,
/** 4419 */
Lookup_Mapping,
/** 10167 */
Macro_Action_Template,
/** 10169 */
Macro_Connector,
/** 10170 */
Macro_Run_History,
/** 10168 */
Macro_Solution_Configuration,
/** 9106 */
Mail_Merge_Template,
/** 9606 */
Mailbox,
/** 9608 */
Mailbox_Auto_Tracking_Folder,
/** 9607 */
Mailbox_Statistics,
/** 9609 */
Mailbox_Tracking_Category,
/** 9812 */
Managed_Property,
/** 10065 */
ManagedIdentity,
/** 10733 */
Marketing_Form_Display_Attributes,
/** 4300 */
Marketing_List,
/** 4301 */
Marketing_List_Member,
/** 10519 */
MarketingSiteMap,
/** 10560 */
Masking_Rule,
/** 10547 */
Master_Entity_Routing_Configuration,
/** 10574 */
Message,
/** 4231 */
Metadata_Difference,
/** 10670 */
Microsoft_Teams_account,
/** 10255 */
Microsoft_Teams_Collaboration_entity,
/** 10252 */
Microsoft_Teams_Graph_resource_Entity,
/** 10113 */
Migration_tracker,
/** 9866 */
Mobile_Offline_Profile,
/** 9867 */
Mobile_Offline_Profile_Item,
/** 9868 */
Mobile_Offline_Profile_Item_Association,
/** 9006 */
Model_driven_App,
/** 10026 */
Model_Driven_App_Component_Node,
/** 10025 */
Model_Driven_App_Component_Nodes_Edge,
/** 10024 */
Model_Driven_App_Element,
/** 10027 */
Model_Driven_App_Setting,
/** 10028 */
Model_Driven_App_User_Setting,
/** 10622 */
Model_training_details,
/** 2003 */
Monthly_Fiscal_Calendar,
/** 10253 */
msdyn_msteamssetting,
/** 10254 */
msdyn_msteamssettingsv2,
/** 10216 */
msdyn_relationshipinsightsunifiedconfig,
/** 9912 */
Multi_Select_Option_Value,
/** 9910 */
MultiEntitySearch,
/** 9900 */
Navigation_Setting,
/** 950 */
New_Process,
/** 10079 */
NonRelational_Data_Source,
/** 5 */
Note,
/** 10231 */
Notes_analysis_Config,
/** 10077 */
Notification_10077,
/** 4110 */
Notification_4110,
/** 10147 */
Notification_Field,
/** 10524 */
Notification_Field_Deprecated,
/** 10148 */
Notification_Template,
/** 10525 */
Notification_Template_Deprecated,
/** 10032 */
OData_v4_Data_Source,
/** 4490 */
Office_Document,
/** 9950 */
Office_Graph_Document,
/** 9870 */
Offline_Command_Definition,
/** 10600 */
Omnichannel_Configuration,
/** 10647 */
Omnichannel_historical_analytics,
/** 10576 */
Omnichannel_Personalization,
/** 10577 */
Omnichannel_Queue_Deprecated,
/** 10571 */
Omnichannel_Request,
/** 10601 */
Omnichannel_Sync_Config,
/** 10648 */
Omnichannel_voice_historical_analytics_preview,
/** 10558 */
Ongoing_conversation_Deprecated,
/** 10578 */
Operating_Hour,
/** 3 */
Opportunity,
/** 4208 */
Opportunity_Close,
/** 1083 */
Opportunity_Line,
/** 10353 */
Opportunity_Line_Detail_Deprecated,
/** 10352 */
Opportunity_Line_Resource_Category_Deprecated,
/** 10354 */
Opportunity_Line_Transaction_Category_Deprecated,
/** 10355 */
Opportunity_Line_Transaction_Classification_Deprecated,
/** 10356 */
Opportunity_Project_Price_List,
/** 4503 */
Opportunity_Relationship,
/** 953 */
Opportunity_Sales_Process,
/** 25 */
OpportunityCompetitors,
/** 10679 */
Option,
/** 9809 */
OptionSet,
/** 1088 */
Order,
/** 4209 */
Order_Close,
/** 10446 */
Order_Invoicing_Date,
/** 10447 */
Order_Invoicing_Product,
/** 10448 */
Order_Invoicing_Setup,
/** 10449 */
Order_Invoicing_Setup_Date,
/** 1089 */
Order_Line,
/** 1019 */
Organization,
/** 9699 */
Organization_Insights_Metric,
/** 9690 */
Organization_Insights_Notification,
/** 10029 */
Organization_Setting,
/** 4708 */
Organization_Statistic,
/** 1021 */
Organization_UI,
/** 10302 */
Organizational_Unit,
/** 10075 */
OrganizationDataSyncSubscription,
/** 10076 */
OrganizationDataSyncSubscriptionEntity,
/** 10672 */
Outbound_Configuration,
/** 10673 */
Outbound_message,
/** 7 */
Owner,
/** 4420 */
Owner_Mapping,
/** 10007 */
Package,
/** 10159 */
Pane_tab_configuration,
/** 10160 */
Pane_tool_configuration,
/** 10171 */
Parameter_definition,
/** 10529 */
Parameter_Deprecated,
/** 1095 */
Partner_Application,
/** 10450 */
Payment,
/** 10451 */
Payment_Detail,
/** 10452 */
Payment_Method,
/** 10453 */
Payment_Term,
/** 10049 */
PDF_Setting,
/** 10604 */
Persona_Security_Role_Mapping,
/** 9941 */
Personal_Document_Template,
/** 10602 */
Personal_quick_reply,
/** 10603 */
Personal_sound_setting,
/** 4210 */
Phone_Call,
/** 10651 */
Phone_Number,
/** 952 */
Phone_To_Case_Process,
/** 10202 */
Playbook,
/** 10199 */
Playbook_activity,
/** 10200 */
Playbook_activity_attribute,
/** 10198 */
Playbook_Callable_Context,
/** 10201 */
Playbook_category,
/** 10203 */
Playbook_template,
/** 4605 */
Plug_in_Assembly,
/** 4619 */
Plug_in_Trace_Log,
/** 4602 */
Plug_in_Type,
/** 4603 */
Plug_in_Type_Statistic,
/** 10093 */
PM_Inferred_Task,
/** 10094 */
PM_Recording,
/** 50 */
Position,
/** 8000 */
Post,
/** 10234 */
Post_Configuration,
/** 8002 */
Post_Regarding,
/** 8001 */
Post_Role,
/** 10235 */
Post_Rule_Configuration,
/** 10454 */
Postal_Code,
/** 10554 */
Power_BI_Configuration,
/** 10579 */
Presence,
/** 1022 */
Price_List,
/** 1026 */
Price_List_Item,
/** 10334 */
Pricing_Dimension,
/** 10335 */
Pricing_Dimension_Field_Name,
/** 1404 */
Principal_Sync_Attribute_Map,
/** 10303 */
Priority,
/** 1023 */
Privilege,
/** 31 */
Privilege_Object_Type_Code,
/** 10507 */
Problematic_Asset_Feedback,
/** 4703 */
Process,
/** 9650 */
Process_Configuration,
/** 4704 */
Process_Dependency,
/** 4706 */
Process_Log,
/** 10362 */
Process_Notes,
/** 4710 */
Process_Session,
/** 4724 */
Process_Stage,
/** 4712 */
Process_Trigger,
/** 10035 */
ProcessStageParameter,
/** 1024 */
Product,
/** 1025 */
Product_Association,
/** 10455 */
Product_Inventory,
/** 1028 */
Product_Relationship,
/** 10158 */
Productivity_pane_configuration,
/** 21 */
ProductSalesLiterature,
/** 10233 */
Profile_Album,
/** 10363 */
Project,
/** 10364 */
Project_Approval,
/** 10358 */
Project_Contract_Line_Detail,
/** 10330 */
Project_Contract_Line_Invoice_Schedule,
/** 10331 */
Project_Contract_Line_Milestone,
/** 10357 */
Project_Contract_Line_Resource_Category,
/** 10359 */
Project_Contract_Line_Transaction_Category,
/** 10360 */
Project_Contract_Line_Transaction_Classification,
/** 10361 */
Project_Contract_Project_Price_List,
/** 10365 */
Project_Parameter,
/** 10366 */
Project_Parameter_Price_List,
/** 10367 */
Project_Price_List,
/** 10324 */
Project_Service_Approval,
/** 10326 */
Project_Stages,
/** 10368 */
Project_Task,
/** 10369 */
Project_Task_Dependency,
/** 10370 */
Project_Task_Status_User,
/** 10371 */
Project_Team_Member,
/** 10372 */
Project_Team_Member_Sign_Up_Deprecated_in_v30,
/** 10373 */
Project_Transaction_Category_Deprecated,
/** 1048 */
Property,
/** 10121 */
Property_Asset_Association,
/** 1235 */
Property_Association,
/** 10120 */
Property_Definition,
/** 1333 */
Property_Instance,
/** 10122 */
Property_Log,
/** 1049 */
Property_Option_Set_Item,
/** 10123 */
Property_Template_Association,
/** 10605 */
Provider,
/** 10570 */
Provisioning_State,
/** 10013 */
ProvisionLanguageForUser,
/** 7101 */
Publisher,
/** 7102 */
Publisher_Address,
/** 10456 */
Purchase_Order,
/** 10457 */
Purchase_Order_Bill,
/** 10426 */
Purchase_Order_Business_Process,
/** 10458 */
Purchase_Order_Product,
/** 10459 */
Purchase_Order_Receipt,
/** 10460 */
Purchase_Order_Receipt_Product,
/** 10461 */
Purchase_Order_SubStatus,
/** 2002 */
Quarterly_Fiscal_Calendar,
/** 2020 */
Queue,
/** 2029 */
Queue_Item,
/** 2023 */
QueueItemCount,
/** 2024 */
QueueMemberCount,
/** 4406 */
Quick_Campaign,
/** 10555 */
Quick_reply,
/** 1084 */
Quote,
/** 10462 */
Quote_Booking_Incident,
/** 10463 */
Quote_Booking_Product,
/** 10464 */
Quote_Booking_Service,
/** 10465 */
Quote_Booking_Service_Task,
/** 10466 */
Quote_Booking_Setup,
/** 4211 */
Quote_Close,
/** 10467 */
Quote_Invoicing_Product,
/** 10468 */
Quote_Invoicing_Setup,
/** 1085 */
Quote_Line,
/** 10374 */
Quote_Line_Analytics_Breakdown,
/** 10378 */
Quote_Line_Detail,
/** 10375 */
Quote_Line_Invoice_Schedule,
/** 10377 */
Quote_Line_Milestone,
/** 10376 */
Quote_Line_Resource_Category,
/** 10379 */
Quote_Line_Transaction_Category,
/** 10380 */
Quote_Line_Transaction_Classification,
/** 10381 */
Quote_Project_Price_List,
/** 1144 */
Rating_Model,
/** 1142 */
Rating_Value,
/** 9300 */
Record_Creation_and_Update_Rule,
/** 9301 */
Record_Creation_and_Update_Rule_Item,
/** 4250 */
Recurrence_Rule,
/** 4251 */
Recurring_Appointment,
/** 9814 */
Relationship_Attribute,
/** 9813 */
Relationship_Entity,
/** 4500 */
Relationship_Role,
/** 4501 */
Relationship_Role_Map,
/** 1140 */
Replication_Backlog,
/** 9100 */
Report,
/** 9104 */
Report_Link,
/** 9102 */
Report_Related_Category,
/** 9101 */
Report_Related_Entity,
/** 9103 */
Report_Visibility,
/** 10304 */
Requirement_Characteristic,
/** 10321 */
Requirement_Dependency,
/** 10305 */
Requirement_Group,
/** 10306 */
Requirement_Organization_Unit,
/** 10307 */
Requirement_Relationship,
/** 10308 */
Requirement_Resource_Category,
/** 10309 */
Requirement_Resource_Preference,
/** 10310 */
Requirement_Status,
/** 10508 */
Resolution,
/** 4002 */
Resource,
/** 10382 */
Resource_Assignment,
/** 10383 */
Resource_Assignment_Detail_Deprecated_in_v20,
/** 4010 */
Resource_Expansion,
/** 4007 */
Resource_Group,
/** 10111 */
resource_group_data_source,
/** 10469 */
Resource_Pay_Type,
/** 10386 */
Resource_Request,
/** 10311 */
Resource_Requirement,
/** 10312 */
Resource_Requirement_Detail,
/** 10490 */
Resource_Restriction_Deprecated,
/** 4006 */
Resource_Specification,
/** 10313 */
Resource_Territory,
/** 10351 */
Result_Cache,
/** 90001 */
RevokeInheritedAccessRecordsTracker,
/** 4579 */
Ribbon_Client_Metadata,
/** 1116 */
Ribbon_Command,
/** 1115 */
Ribbon_Context_Group,
/** 1130 */
Ribbon_Difference,
/** 9880 */
Ribbon_Metadata_To_Process,
/** 1117 */
Ribbon_Rule,
/** 1113 */
Ribbon_Tab_To_Command_Mapping,
/** 10078 */
Rich_Text_Attachment,
/** 10470 */
RMA,
/** 10471 */
RMA_Product,
/** 10472 */
RMA_Receipt,
/** 10473 */
RMA_Receipt_Product,
/** 10474 */
RMA_SubStatus,
/** 10387 */
Role_competency_requirement,
/** 10385 */
Role_Price,
/** 10384 */
Role_Price_Markup,
/** 1037 */
Role_Template,
/** 10388 */
Role_Utilization,
/** 9604 */
Rollup_Field,
/** 9511 */
Rollup_Job,
/** 9510 */
Rollup_Properties,
/** 9602 */
Rollup_Query,
/** 10552 */
Routing_configuration,
/** 10553 */
Routing_configuration_step,
/** 8181 */
Routing_Rule_Set,
/** 10548 */
Routing_Rule_Set_Setting,
/** 10580 */
RoutingRequest,
/** 10475 */
RTV,
/** 10476 */
RTV_Product,
/** 10477 */
RTV_Substatus,
/** 10572 */
Rule_Item_10572,
/** 8199 */
Rule_Item_8199,
/** 10544 */
Rulesetentitymapping,
/** 7200 */
RuntimeDependency,
/** 1070 */
Sales_Attachment,
/** 1038 */
Sales_Literature,
/** 32 */
Sales_Process_Instance,
/** 10223 */
salesinsightssettings,
/** 10520 */
SalesSiteMap,
/** 1309 */
Saved_Organization_Insights_Configuration,
/** 4230 */
Saved_View,
/** 10541 */
Scenario,
/** 10314 */
Schedule_Board_Setting,
/** 10322 */
Scheduling_Feature_Flag,
/** 4005 */
Scheduling_Group,
/** 10315 */
Scheduling_Parameter,
/** 10697 */
Script_Task_Trigger,
/** 10696 */
Scriptlet,
/** 4606 */
Sdk_Message,
/** 4607 */
Sdk_Message_Filter,
/** 4613 */
Sdk_Message_Pair,
/** 4608 */
Sdk_Message_Processing_Step,
/** 4615 */
Sdk_Message_Processing_Step_Image,
/** 4616 */
Sdk_Message_Processing_Step_Secure_Configuration,
/** 4609 */
Sdk_Message_Request,
/** 4614 */
Sdk_Message_Request_Field,
/** 4610 */
Sdk_Message_Response,
/** 4611 */
Sdk_Message_Response_Field,
/** 10581 */
Search_Configuration,
/** 10055 */
Search_provider,
/** 10080 */
Search_Telemetry,
/** 1036 */
Security_Role,
/** 10611 */
Self_service,
/** 2001 */
Semiannual_Fiscal_Calendar,
/** 10582 */
Sentiment_analysis,
/** 10595 */
Sentiment_daily_topic,
/** 10596 */
Sentiment_daily_topic_keyword,
/** 10597 */
Sentiment_daily_topic_trending,
/** 4001 */
Service,
/** 4214 */
Service_Activity,
/** 10051 */
Service_Configuration,
/** 20 */
Service_Contract_Contact,
/** 4618 */
Service_Endpoint,
/** 101 */
Service_Plan,
/** 10478 */
Service_Task_Type,
/** 10521 */
ServicesSiteMap,
/** 10573 */
Session,
/** 10619 */
Session_Characteristic,
/** 10209 */
Session_Data_Deprecated,
/** 10583 */
Session_event,
/** 10699 */
Session_Information,
/** 10584 */
Session_participant,
/** 10210 */
Session_Participant_Data_Deprecated,
/** 10598 */
Session_Sentiment,
/** 10149 */
Session_Template,
/** 10527 */
Session_Templates_Deprecated,
/** 10700 */
Session_Transfer,
/** 10030 */
Setting_Definition,
/** 10522 */
SettingsSiteMap,
/** 9509 */
SharePoint_Data,
/** 9507 */
Sharepoint_Document,
/** 9502 */
SharePoint_Site,
/** 10479 */
Ship_Via,
/** 10218 */
SI_Key_Value_Config,
/** 10217 */
siconfig,
/** 9951 */
Similarity_Rule,
/** 4009 */
Site,
/** 4709 */
Site_Map,
/** 10620 */
Skill_Attachment_Rule,
/** 10626 */
Skill_finder_model,
/** 9750 */
SLA,
/** 9751 */
SLA_Item,
/** 10052 */
SLA_KPI,
/** 9752 */
SLA_KPI_Instance,
/** 10175 */
Smartassist_configuration,
/** 10652 */
SMS_Engagement_Context,
/** 10653 */
SMS_Number,
/** 10654 */
SMS_Number_settings,
/** 4216 */
Social_Activity,
/** 99 */
Social_Profile,
/** 1300 */
SocialInsightsConfiguration,
/** 7100 */
Solution,
/** 7103 */
Solution_Component,
/** 10000 */
Solution_Component_Attribute_Configuration,
/** 10001 */
Solution_Component_Configuration,
/** 10012 */
Solution_Component_Data_Source,
/** 7104 */
Solution_Component_Definition,
/** 10002 */
Solution_Component_Relationship_Configuration,
/** 10011 */
Solution_Component_Summary,
/** 10099 */
Solution_Health_Rule,
/** 10100 */
Solution_Health_Rule_Argument,
/** 10101 */
Solution_Health_Rule_Set,
/** 10003 */
Solution_History,
/** 10004 */
Solution_History_Data_Source,
/** 9890 */
SolutionHistoryData,
/** 10607 */
Sound_notification_setting,
/** 10009 */
StageSolutionUpload,
/** 1075 */
Status_Map,
/** 1043 */
String_Map,
/** 129 */
Subject,
/** 29 */
Subscription,
/** 1072 */
Subscription_Clients,
/** 37 */
Subscription_Manually_Tracked_Object,
/** 45 */
Subscription_Statistic_Offline,
/** 46 */
Subscription_Statistic_Outlook,
/** 47 */
Subscription_Sync_Entry_Offline,
/** 48 */
Subscription_Sync_Entry_Outlook,
/** 33 */
Subscription_Synchronization_Information,
/** 10227 */
Suggested_Activity,
/** 10228 */
Suggested_Activity_Data_Source,
/** 10229 */
Suggested_Contact,
/** 10230 */
Suggested_contacts_data_source,
/** 10184 */
Suggestion_Interaction,
/** 10185 */
Suggestion_request_payload,
/** 1190 */
SuggestionCardTemplate,
/** 10186 */
Suggestions_Model_Summary,
/** 10187 */
Suggestions_Setting,
/** 10629 */
Survey_Answer_Option,
/** 10638 */
Survey_Question,
/** 10637 */
Survey_Question_Sequence,
/** 10630 */
Survey_Response,
/** 10631 */
Survey_Response_Value,
/** 1401 */
Sync_Attribute_Mapping,
/** 1400 */
Sync_Attribute_Mapping_Profile,
/** 9869 */
Sync_Error,
/** 7000 */
System_Application_Metadata,
/** 1111 */
System_Chart,
/** 1030 */
System_Form,
/** 4700 */
System_Job,
/** 51 */
System_User_Manager_Map,
/** 14 */
System_User_Principal,
/** 10316 */
System_User_Scheduler_Setting,
/** 42 */
SystemUser_BusinessUnit_Entity_Map,
/** 60 */
SystemUserAuthorizationChangeTracker,
/** 10599 */
Tag,
/** 4212 */
Task,
/** 10480 */
Tax_Code,
/** 10481 */
Tax_Code_Detail,
/** 9 */
Team,
/** 1203 */
Team_Profiles,
/** 1403 */
Team_Sync_Attribute_Mapping_Profiles,
/** 92 */
Team_template,
/** 10073 */
TeamMobileOfflineProfileMembership,
/** 10256 */
Teams_Dialer_Admin_settings,
/** 10671 */
Teams_Engagement_Context,
/** 10124 */
Template_For_Properties,
/** 10150 */
Template_Parameter,
/** 10530 */
Template_Tag_Deprecated,
/** 2013 */
Territory,
/** 9945 */
Text_Analytics_Entity_Mapping,
/** 9948 */
Text_Analytics_Topic,
/** 2015 */
Theme,
/** 10407 */
Three_Dimensional_Model,
/** 10389 */
Time_Entry,
/** 10318 */
Time_Group_Detail,
/** 10390 */
Time_Off_Calendar,
/** 10482 */
Time_Off_Request,
/** 10404 */
Time_Source,
/** 9932 */
Time_Stamp_Date_Mapping,
/** 4810 */
Time_Zone_Definition,
/** 4812 */
Time_Zone_Localized_Name,
/** 4811 */
Time_Zone_Rule,
/** 10703 */
Toolbar,
/** 10702 */
Toolbar_Button,
/** 9946 */
Topic_History,
/** 9944 */
Topic_Model,
/** 9942 */
Topic_Model_Configuration,
/** 9943 */
Topic_Model_Execution_History,
/** 10039 */
Tour,
/** 8050 */
Trace,
/** 8051 */
Trace_Association,
/** 8052 */
Trace_Regarding,
/** 10704 */
Trace_Source_Setting,
/** 35 */
Tracking_information_for_deleted_entities,
/** 10623 */
Training_data_import_configuration,
/** 10625 */
Training_record,
/** 10391 */
Transaction_Category,
/** 10392 */
Transaction_Category_Classification,
/** 10393 */
Transaction_Category_Hierarchy_Element,
/** 10394 */
Transaction_Category_Price,
/** 10395 */
Transaction_Connection,
/** 10319 */
Transaction_Origin,
/** 10396 */
Transaction_Type,
/** 10585 */
Transcript,
/** 4426 */
Transformation_Mapping,
/** 4427 */
Transformation_Parameter_Mapping,
/** 951 */
Translation_Process,
/** 10662 */
Twitter_account,
/** 10667 */
Twitter_Engagement_Context,
/** 10663 */
Twitter_handle,
/** 10674 */
UII_Action,
/** 10675 */
UII_Audit,
/** 10676 */
UII_Context,
/** 10678 */
UII_Non_Hosted_Application,
/** 10680 */
UII_Saved_Session,
/** 10681 */
UII_Session_Transfer,
/** 10682 */
UII_Workflow,
/** 10683 */
UII_Workflow_Step,
/** 10684 */
UII_Workflow_Step_Mapping,
/** 10705 */
Unified_Interface_Settings,
/** 10545 */
Unified_routing_diagnostic,
/** 10546 */
Unified_routing_run,
/** 10108 */
Unified_Routing_Setup_Tracker,
/** 10483 */
Unique_Number,
/** 1055 */
Unit,
/** 1056 */
Unit_Group,
/** 2012 */
Unresolved_Address,
/** 10226 */
UntrackedAppointment,
/** 4220 */
UntrackedEmail,
/** 10104 */
Upgrade_Run,
/** 10105 */
Upgrade_Step,
/** 10106 */
Upgrade_Version,
/** 10608 */
UR_notification_template,
/** 10609 */
UR_Notification_Template_Mapping,
/** 8 */
User,
/** 7001 */
User_Application_Metadata,
/** 1112 */
User_Chart,
/** 1031 */
User_Dashboard,
/** 2501 */
User_Entity_Instance_Data,
/** 2500 */
User_Entity_UI_Settings,
/** 1086 */
User_Fiscal_Calendar,
/** 2016 */
User_Mapping,
/** 52 */
User_Search_Facet,
/** 10707 */
User_Setting,
/** 10610 */
User_settings_10610,
/** 150 */
User_settings_150,
/** 10397 */
User_Work_History,
/** 10074 */
UserMobileOfflineProfileMembership,
/** 1039 */
View,
/** 78 */
Virtual_Entity_Data_Provider,
/** 85 */
Virtual_Entity_Data_Source,
/** 10072 */
Virtual_Entity_Metadata,
/** 10112 */
Virtual_Resource_Group_Resource,
/** 10236 */
Wall_View,
/** 10484 */
Warehouse,
/** 9333 */
Web_Resource,
/** 4800 */
Web_Wizard,
/** 4803 */
Web_Wizard_Access_Privilege,
/** 10664 */
WeChat_account,
/** 10668 */
WeChat_Engagement_Context,
/** 10665 */
WhatsApp_account,
/** 10669 */
WhatsApp_Engagement_Context,
/** 10666 */
WhatsApp_number,
/** 10708 */
Window_Navigation_Rule,
/** 4802 */
Wizard_Page,
/** 10485 */
Work_Order,
/** 10429 */
Work_Order_Business_Process,
/** 10486 */
Work_Order_Characteristic_Deprecated,
/** 10487 */
Work_Order_Details_Generation_Queue_Deprecated,
/** 10488 */
Work_Order_Incident,
/** 10489 */
Work_Order_Product,
/** 10511 */
Work_Order_Resolution,
/** 10491 */
Work_Order_Service,
/** 10492 */
Work_Order_Service_Task,
/** 10493 */
Work_Order_Substatus,
/** 10494 */
Work_Order_Type,
/** 10559 */
Work_Stream,
/** 10616 */
Work_stream_capacity_profile,
/** 10320 */
Work_template,
/** 10036 */
Workflow_Binary,
/** 4702 */
Workflow_Wait_Subscription
}
enum statecode {
/** 1 */
Active,
/** 0 */
Draft
}
enum statuscode {
/** 1 */
Active,
/** 0 */
Draft
}
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':[],'JsWebApi':true,'IsDebugForm':false,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import {
GrpcMessage,
RecursivePartial,
ToProtobufJSONOptions,
} from '@ngx-grpc/common';
import { BinaryReader, BinaryWriter, ByteSource } from 'google-protobuf';
import * as googleProtobuf000 from '@ngx-grpc/well-known-types';
/**
* Message implementation for echo.EchoRequest
*/
export class EchoRequest implements GrpcMessage {
static id = 'echo.EchoRequest';
/**
* Deserialize binary data to message
* @param instance message instance
*/
static deserializeBinary(bytes: ByteSource) {
const instance = new EchoRequest();
EchoRequest.deserializeBinaryFromReader(instance, new BinaryReader(bytes));
return instance;
}
/**
* Check all the properties and set default protobuf values if necessary
* @param _instance message instance
*/
static refineValues(_instance: EchoRequest) {
_instance.message = _instance.message || '';
_instance.shouldThrow = _instance.shouldThrow || false;
_instance.timestamp = _instance.timestamp || undefined;
}
/**
* Deserializes / reads binary message into message instance using provided binary reader
* @param _instance message instance
* @param _reader binary reader instance
*/
static deserializeBinaryFromReader(
_instance: EchoRequest,
_reader: BinaryReader
) {
while (_reader.nextField()) {
if (_reader.isEndGroup()) break;
switch (_reader.getFieldNumber()) {
case 1:
_instance.message = _reader.readString();
break;
case 2:
_instance.shouldThrow = _reader.readBool();
break;
case 3:
_instance.timestamp = new googleProtobuf000.Timestamp();
_reader.readMessage(
_instance.timestamp,
googleProtobuf000.Timestamp.deserializeBinaryFromReader
);
break;
default:
_reader.skipField();
}
}
EchoRequest.refineValues(_instance);
}
/**
* Serializes a message to binary format using provided binary reader
* @param _instance message instance
* @param _writer binary writer instance
*/
static serializeBinaryToWriter(
_instance: EchoRequest,
_writer: BinaryWriter
) {
if (_instance.message) {
_writer.writeString(1, _instance.message);
}
if (_instance.shouldThrow) {
_writer.writeBool(2, _instance.shouldThrow);
}
if (_instance.timestamp) {
_writer.writeMessage(
3,
_instance.timestamp as any,
googleProtobuf000.Timestamp.serializeBinaryToWriter
);
}
}
private _message?: string;
private _shouldThrow?: boolean;
private _timestamp?: googleProtobuf000.Timestamp;
/**
* Message constructor. Initializes the properties and applies default Protobuf values if necessary
* @param _value initial values object or instance of EchoRequest to deeply clone from
*/
constructor(_value?: RecursivePartial<EchoRequest.AsObject>) {
_value = _value || {};
this.message = _value.message;
this.shouldThrow = _value.shouldThrow;
this.timestamp = _value.timestamp
? new googleProtobuf000.Timestamp(_value.timestamp)
: undefined;
EchoRequest.refineValues(this);
}
get message(): string | undefined {
return this._message;
}
set message(value: string | undefined) {
this._message = value;
}
get shouldThrow(): boolean | undefined {
return this._shouldThrow;
}
set shouldThrow(value: boolean | undefined) {
this._shouldThrow = value;
}
get timestamp(): googleProtobuf000.Timestamp | undefined {
return this._timestamp;
}
set timestamp(value: googleProtobuf000.Timestamp | undefined) {
this._timestamp = value;
}
/**
* Serialize message to binary data
* @param instance message instance
*/
serializeBinary() {
const writer = new BinaryWriter();
EchoRequest.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
}
/**
* Cast message to standard JavaScript object (all non-primitive values are deeply cloned)
*/
toObject(): EchoRequest.AsObject {
return {
message: this.message,
shouldThrow: this.shouldThrow,
timestamp: this.timestamp ? this.timestamp.toObject() : undefined,
};
}
/**
* Convenience method to support JSON.stringify(message), replicates the structure of toObject()
*/
toJSON() {
return this.toObject();
}
/**
* Cast message to JSON using protobuf JSON notation: https://developers.google.com/protocol-buffers/docs/proto3#json
* Attention: output differs from toObject() e.g. enums are represented as names and not as numbers, Timestamp is an ISO Date string format etc.
* If the message itself or some of descendant messages is google.protobuf.Any, you MUST provide a message pool as options. If not, the messagePool is not required
*/
toProtobufJSON(
// @ts-ignore
options?: ToProtobufJSONOptions
): EchoRequest.AsProtobufJSON {
return {
message: this.message,
shouldThrow: this.shouldThrow,
timestamp: this.timestamp ? this.timestamp.toProtobufJSON(options) : null,
};
}
}
export module EchoRequest {
/**
* Standard JavaScript object representation for EchoRequest
*/
export interface AsObject {
message?: string;
shouldThrow?: boolean;
timestamp?: googleProtobuf000.Timestamp.AsObject;
}
/**
* Protobuf JSON representation for EchoRequest
*/
export interface AsProtobufJSON {
message?: string;
shouldThrow?: boolean;
timestamp?: googleProtobuf000.Timestamp.AsProtobufJSON | null;
}
}
/**
* Message implementation for echo.EchoResponse
*/
export class EchoResponse implements GrpcMessage {
static id = 'echo.EchoResponse';
/**
* Deserialize binary data to message
* @param instance message instance
*/
static deserializeBinary(bytes: ByteSource) {
const instance = new EchoResponse();
EchoResponse.deserializeBinaryFromReader(instance, new BinaryReader(bytes));
return instance;
}
/**
* Check all the properties and set default protobuf values if necessary
* @param _instance message instance
*/
static refineValues(_instance: EchoResponse) {
_instance.message = _instance.message || '';
_instance.timestamp = _instance.timestamp || undefined;
}
/**
* Deserializes / reads binary message into message instance using provided binary reader
* @param _instance message instance
* @param _reader binary reader instance
*/
static deserializeBinaryFromReader(
_instance: EchoResponse,
_reader: BinaryReader
) {
while (_reader.nextField()) {
if (_reader.isEndGroup()) break;
switch (_reader.getFieldNumber()) {
case 1:
_instance.message = _reader.readString();
break;
case 2:
_instance.timestamp = new googleProtobuf000.Timestamp();
_reader.readMessage(
_instance.timestamp,
googleProtobuf000.Timestamp.deserializeBinaryFromReader
);
break;
default:
_reader.skipField();
}
}
EchoResponse.refineValues(_instance);
}
/**
* Serializes a message to binary format using provided binary reader
* @param _instance message instance
* @param _writer binary writer instance
*/
static serializeBinaryToWriter(
_instance: EchoResponse,
_writer: BinaryWriter
) {
if (_instance.message) {
_writer.writeString(1, _instance.message);
}
if (_instance.timestamp) {
_writer.writeMessage(
2,
_instance.timestamp as any,
googleProtobuf000.Timestamp.serializeBinaryToWriter
);
}
}
private _message?: string;
private _timestamp?: googleProtobuf000.Timestamp;
/**
* Message constructor. Initializes the properties and applies default Protobuf values if necessary
* @param _value initial values object or instance of EchoResponse to deeply clone from
*/
constructor(_value?: RecursivePartial<EchoResponse.AsObject>) {
_value = _value || {};
this.message = _value.message;
this.timestamp = _value.timestamp
? new googleProtobuf000.Timestamp(_value.timestamp)
: undefined;
EchoResponse.refineValues(this);
}
get message(): string | undefined {
return this._message;
}
set message(value: string | undefined) {
this._message = value;
}
get timestamp(): googleProtobuf000.Timestamp | undefined {
return this._timestamp;
}
set timestamp(value: googleProtobuf000.Timestamp | undefined) {
this._timestamp = value;
}
/**
* Serialize message to binary data
* @param instance message instance
*/
serializeBinary() {
const writer = new BinaryWriter();
EchoResponse.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
}
/**
* Cast message to standard JavaScript object (all non-primitive values are deeply cloned)
*/
toObject(): EchoResponse.AsObject {
return {
message: this.message,
timestamp: this.timestamp ? this.timestamp.toObject() : undefined,
};
}
/**
* Convenience method to support JSON.stringify(message), replicates the structure of toObject()
*/
toJSON() {
return this.toObject();
}
/**
* Cast message to JSON using protobuf JSON notation: https://developers.google.com/protocol-buffers/docs/proto3#json
* Attention: output differs from toObject() e.g. enums are represented as names and not as numbers, Timestamp is an ISO Date string format etc.
* If the message itself or some of descendant messages is google.protobuf.Any, you MUST provide a message pool as options. If not, the messagePool is not required
*/
toProtobufJSON(
// @ts-ignore
options?: ToProtobufJSONOptions
): EchoResponse.AsProtobufJSON {
return {
message: this.message,
timestamp: this.timestamp ? this.timestamp.toProtobufJSON(options) : null,
};
}
}
export module EchoResponse {
/**
* Standard JavaScript object representation for EchoResponse
*/
export interface AsObject {
message?: string;
timestamp?: googleProtobuf000.Timestamp.AsObject;
}
/**
* Protobuf JSON representation for EchoResponse
*/
export interface AsProtobufJSON {
message?: string;
timestamp?: googleProtobuf000.Timestamp.AsProtobufJSON | null;
}
} | the_stack |
declare module 'gijgo' {
export = Types;
}
declare module Types {
//Grid
interface GridPager {
limit?: number;
sizes?: Array<number>;
leftControls?: Array<any>;
rightControls?: Array<any>;
}
interface GridColumn {
align?: string;
cssClass?: string;
decimalDigits?: number;
editField?: string;
editor?: any;
events?: any;
field?: string;
filter?: any;
filterable?: boolean;
format?: string;
headerCssClass?: string;
hidden?: boolean;
icon?: string;
minWidth?: number;
mode?: string;
priority?: number;
renderer?: any;
sortable?: boolean;
stopPropagation?: boolean;
title?: string;
tmpl?: string;
tooltip?: string;
type?: string;
width?: number;
}
interface GridParamNames {
direction?: string;
limit?: string;
page?: string;
sortBy?: string;
groupBy?: string;
groupByDirection?: string;
}
interface GridMapping {
dataField?: string;
totalRecordsField?: string;
}
interface GridIcons {
expandRow?: string;
collapseRow?: string;
expandGroup?: string;
collapseGroup?: string;
}
interface GridGrouping {
groupBy: string;
}
interface GridHeaderFilter {
type: string;
}
interface GridInlineEditing {
mode?: string;
managementColumn?: boolean;
}
interface GridOptimisticPersistence {
localStorage: Array<string>;
sessionStorage: Array<string>;
}
interface GridSettings<Entity> {
//Configuration options
autoGenerateColumns?: boolean;
autoLoad?: boolean;
bodyRowHeight?: string;
columnReorder?: boolean;
columns?: Array<GridColumn>;
dataSource?: any;
defaultColumnSettings?: GridColumn;
detailTemplate?: string;
fixedHeader?: boolean;
fontSize?: string;
grouping?: GridGrouping;
headerFilter?: GridHeaderFilter;
headerRowHeight?: string;
icons?: GridIcons;
iconsLibrary?: string;
inlineEditing?: GridInlineEditing;
keepExpandedRows?: boolean;
locale?: string;
mapping?: any;
minWidth?: number;
notFoundText?: string;
optimisticPersistence?: GridOptimisticPersistence;
orderNumberField?: string;
pager?: GridPager;
paramNames?: GridParamNames;
primaryKey?: string;
resizableColumns?: boolean;
resizeCheckInterval?: number;
responsive?: boolean;
rowReorder?: boolean;
rowReorderColumn?: string;
selectionMethod?: string;
selectionType?: string;
showHiddenColumnsAsDetails?: boolean;
title?: string;
toolbarTemplate?: string;
uiLibrary?: string;
width?: number;
params?: any;
//Events
beforeEmptyRowInsert?: (e: any, $row: JQuery) => any;
cellDataBound?: (e: any, $wrapper: JQuery, id: string, column: GridColumn, record: Entity) => any;
cellDataChanged?: (e: any, $cell: JQuery, column: GridColumn, record: Entity, oldValue: any, newValue: any) => any;
columnHide?: (e: any, column: GridColumn) => any;
columnShow?: (e: any, column: GridColumn) => any;
dataBinding?: (e: any, records: Array<Entity>) => any;
dataBound?: (e: any, records: Array<Entity>, totalRecords: number) => any;
dataFiltered?: (e: any, records: Array<Entity>) => any;
destroying?: (e: any) => any;
detailCollapse?: (e: any, detailWrapper: JQuery, id: string) => any;
detailExpand?: (e: any, detailWrapper: JQuery, id: string) => any;
initialized?: (e: any) => any;
pageChanging?: (e: any, newPage: number) => any;
pageSizeChange?: (e: any, newPage: number) => any;
resize?: (e: any, newWidth: number, oldWidth: number) => any;
rowDataBound?: (e: any, $row: JQuery, id: string, record: Entity) => any;
rowDataChanged?: (e: any, id: string, record: Entity) => any;
rowRemoving?: (e: any, $row: JQuery, id: string, record: Entity) => any;
rowSelect?: (e: any, $row: JQuery, id: string, record: Entity) => any;
rowUnselect?: (e: any, $row: JQuery, id: string, record: Entity) => any;
}
interface Grid<Entity, Params> extends JQuery {
addRow(record: Entity): Grid<Entity, Params>;
cancel(id: string): Grid<Entity, Params>;
clear(showNotFoundText?: boolean): Grid<Entity, Params>;
collapseAll(): Grid<Entity, Params>;
count(): number;
destroy(keepTableTag?: boolean, keepWrapperTag?: boolean): void;
downloadCSV(filename?: string, includeAllRecords?: boolean): Grid<Entity, Params>;
edit(id: string): Grid<Entity, Params>;
expandAll(): Grid<Entity, Params>;
//get(position: number): Entity; //TODO: rename to getByPosition to avoid conflicts with jquery.get
getAll(includeAllRecords?: boolean): Array<Entity>;
getById(id: string): Entity;
getChanges(): Array<Entity>;
getCSV(includeAllRecords?: boolean): string;
getSelected(): string;
getSelections(): Array<string>;
hideColumn(field: string): Grid<Entity, Params>;
makeResponsive(): Grid<Entity, Params>;
reload(params?: Params): Grid<Entity, Params>;
removeRow(id: string): Grid<Entity, Params>;
render(response: any): Grid<Entity, Params>;
selectAll(): Grid<Entity, Params>;
setSelected(id: string | number): Grid<Entity, Params>;
showColumn(field: string): Grid<Entity, Params>;
title(text: any): any;
unSelectAll(): Grid<Entity, Params>;
update(id: string): Grid<Entity, Params>;
updateRow(id: string, record: Entity): Grid<Entity, Params>;
}
// Dialog
interface DialogSettings {
autoOpen?: boolean;
closeButtonInHeader?: boolean;
closeOnEscape?: boolean;
draggable?: boolean;
height?: number | string;
locale?: string;
maxHeight?: number;
maxWidth?: number;
minHeight?: number;
minWidth?: number;
modal?: boolean;
resizable?: boolean;
scrollable?: boolean;
title?: string;
uiLibrary?: string;
width?: number;
//Events
closed?: (e: any) => any;
closing?: (e: any) => any;
drag?: (e: any) => any;
dragStart?: (e: any) => any;
dragStop?: (e: any) => any;
initialized?: (e: any) => any;
opened?: (e: any) => any;
opening?: (e: any) => any;
resize?: (e: any) => any;
resizeStart?: (e: any) => any;
resizeStop?: (e: any) => any;
}
interface Dialog extends JQuery {
close(): Dialog;
content(constent: string): string | Dialog;
destroy(keepHtml: boolean): void;
isOpen(): boolean;
open(): Dialog;
}
// Checkbox
interface CheckboxSettings {
uiLibrary?: string;
iconsLibrary?: string;
//Events
change?: (e: any, state: string) => any;
}
interface Checkbox extends JQuery {
//toggle(): Checkbox;
state(value: string): string | Checkbox;
destroy(): void;
}
// DatePicker
interface DatePickerIcons {
rightIcon?: string;
}
interface DatePickerSettings {
showOtherMonths?: boolean;
selectOtherMonths?: boolean;
width?: number;
minDate?: Date | string | Function;
maxDate?: Date | string | Function;
format?: string;
value?: string;
uiLibrary?: string;
iconsLibrary?: string;
weekStartDay?: number;
disableDates?: Array<any> | Function;
disableDaysOfWeek?: Array<number>;
calendarWeeks?: boolean;
keyboardNavigation?: boolean;
locale?: string;
icons?: DatePickerIcons;
size?: string;
modal?: boolean;
header?: boolean;
footer?: boolean;
showOnFocus?: boolean;
showRightIcon?: boolean;
//Events
change?: (e: any) => any;
open?: (e: any) => any;
close?: (e: any) => any;
select?: (e: any, type: string) => any;
}
interface DatePicker extends JQuery {
close(): DatePicker;
destroy(): void;
open(): DatePicker;
value(value?: string): string | DatePicker;
}
// DropDown
interface DropDownIcons {
dropdown?: string;
}
interface DropDownSettings {
dataSource?: any;
textField?: string;
valueField?: string;
selectedField?: string;
width?: number;
maxHeight?: any;
uiLibrary?: string;
iconsLibrary?: string;
icons?: DropDownIcons;
placeholder?: string;
//Events
change?: (e: any) => any;
dataBound?: (e: any) => any;
}
interface DropDown extends JQuery {
value(value: string): string | DropDown;
destroy(): void;
}
// Editor
interface EditorSettings {
height?: number | string;
width?: number | string;
uiLibrary?: string;
iconsLibrary?: string;
locale?: string;
//Events
changing?: (e: any) => any;
changed?: (e: any) => any;
}
interface Editor extends JQuery {
content(html?: string): string | Editor;
destroy(): void;
}
// TimePicker
interface TimePickerSettings {
width?: number;
modal?: boolean;
header?: boolean;
footer?: boolean;
format?: string;
uiLibrary?: string;
value?: string;
mode?: string;
locale?: string;
size?: string;
//Events
change?: (e: any) => any;
open?: (e: any) => any;
close?: (e: any) => any;
select?: (e: any, type: string) => any;
}
interface TimePicker extends JQuery {
close(): TimePicker;
destroy(): void;
open(): TimePicker;
value(value?: string): string | TimePicker;
}
// DateTimePicker
interface DateTimePickerSettings {
datepicker?: Types.DatePickerSettings;
footer?: boolean;
format?: string;
locale?: string;
modal?: boolean;
size?: string;
uiLibrary?: string;
value?: string;
width?: number;
//Events
change?: (e: any) => any;
}
interface DateTimePicker extends JQuery {
destroy(): void;
value(value?: string): string | DateTimePicker;
}
// Slider
interface SliderSettings {
min?: number;
max?: number;
uiLibrary?: string;
value?: string;
width?: number;
//Events
change?: (e: any) => any;
slide?: (e: any, value: number) => any;
}
interface Slider extends JQuery {
destroy(): void;
value(value?: string): string | Slider;
}
// Tree
interface TreeIcons {
expand?: string;
collapse?: string;
}
interface TreeParamNames {
parentId?: string;
}
interface TreeSettings {
autoLoad?: boolean;
selectionType?: string;
cascadeSelection?: boolean;
dataSource?: any;
primaryKey?: string;
textField?: string;
childrenField?: string;
hasChildrenField?: string;
imageCssClassField?: string;
imageUrlField?: string;
imageHtmlField?: string;
disabledField?: string;
width?: number;
border?: boolean;
uiLibrary?: string;
iconsLibrary?: string;
icons?: TreeIcons;
checkboxes?: boolean;
checkedField?: string;
cascadeCheck?: boolean;
dragAndDrop?: boolean;
paramNames?: TreeParamNames;
lazyLoading?: boolean;
//Events
initialized?: (e: any) => any;
dataBinding?: (e: any) => any;
dataBound?: (e: any) => any;
select?: (e: any, node: any, id: string) => any;
unselect?: (e: any, node: any, id: string) => any;
expand?: (e: any, node: any, id: string) => any;
collapse?: (e: any, node: any, id: string) => any;
enable?: (e: any, node: any, id: string) => any;
disable?: (e: any, node: any, id: string) => any;
destroying?: (e: any) => any;
nodeDataBound?: (e: any, node: any, id: string) => any;
checkboxChange?: (e: any, node: any, record: any, state: string) => any;
nodeDrop?: (e: any, id: string, parentId: string, orderNumber: number) => any;
}
interface Tree extends JQuery {
reload(params: any): any;
render(response: any): any;
addNode(data: any, parentNode: any, position: number): Tree;
removeNode(node: any): Tree;
updateNode(id: string, record: any) : Tree;
destroy(): void;
expand(node: any, cascade: boolean): Tree;
collapse(node: any, cascade: boolean) : Tree;
expandAll(): Tree;
collapseAll() : Tree;
getDataById(id: string) : any;
getDataByText(text: string) : any;
getNodeById(id: string) : any;
getNodeByText(id: string) : any;
getAll(): Array<any>;
//select(node: any) : Tree;
unselect(node: any) : Tree;
selectAll() : Tree;
unselectAll() : Tree;
getSelections() : Array<string>;
getChildren(node: any, cascade?: boolean) : Array<any>;
enable(node: any, cascade?: boolean) : Tree;
disable(node: any, cascade?: boolean) : Tree;
enableAll() : Tree;
disableAll() : Tree;
//parents(id: string): Array<string>;
getCheckedNodes() : Array<string>;
checkAll() : Tree;
uncheckAll(): Tree;
check(node: any) : Tree;
uncheck(node: any) : Tree;
}
}
interface JQuery {
grid(settings: Types.GridSettings<any>): Types.Grid<any, any>;
grid<Entity>(settings: Types.GridSettings<Entity>): Types.Grid<Entity, any>;
grid<Entity, Params>(settings: Types.GridSettings<Entity>): Types.Grid<Entity, Params>;
dialog(settings: Types.DialogSettings): Types.Dialog;
checkbox(settings: Types.CheckboxSettings): Types.Checkbox;
datepicker(settings: Types.DatePickerSettings): Types.DatePicker;
dropdown(settings: Types.DropDownSettings): Types.DropDown;
editor(settings: Types.EditorSettings): Types.Editor;
timepicker(settings: Types.TimePickerSettings): Types.TimePicker;
datetimepicker(settings: Types.DateTimePickerSettings): Types.DateTimePicker;
slider(settings: Types.SliderSettings): Types.Slider;
tree(settings: Types.TreeSettings): Types.Tree;
} | the_stack |
import * as Common from '../../core/common/common.js';
import * as Host from '../../core/host/host.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Platform from '../../core/platform/platform.js';
import * as SDK from '../../core/sdk/sdk.js';
import * as UI from '../../ui/legacy/legacy.js';
import {AnimationGroupPreviewUI} from './AnimationGroupPreviewUI.js';
import animationTimelineStyles from './animationTimeline.css.js';
import type {AnimationEffect, AnimationGroup, AnimationImpl} from './AnimationModel.js';
import {AnimationModel, Events} from './AnimationModel.js';
import {AnimationScreenshotPopover} from './AnimationScreenshotPopover.js';
import {AnimationUI} from './AnimationUI.js';
const UIStrings = {
/**
*@description Timeline hint text content in Animation Timeline of the Animation Inspector
*/
selectAnEffectAboveToInspectAnd: 'Select an effect above to inspect and modify.',
/**
*@description Text to clear everything
*/
clearAll: 'Clear all',
/**
*@description Tooltip text that appears when hovering over largeicon pause button in Animation Timeline of the Animation Inspector
*/
pauseAll: 'Pause all',
/**
*@description Title of the playback rate button listbox
*/
playbackRates: 'Playback rates',
/**
*@description Text in Animation Timeline of the Animation Inspector
*@example {50} PH1
*/
playbackRatePlaceholder: '{PH1}%',
/**
*@description Text of an item that pause the running task
*/
pause: 'Pause',
/**
*@description Button title in Animation Timeline of the Animation Inspector
*@example {50%} PH1
*/
setSpeedToS: 'Set speed to {PH1}',
/**
*@description Title of Animation Previews listbox
*/
animationPreviews: 'Animation previews',
/**
*@description Empty buffer hint text content in Animation Timeline of the Animation Inspector
*/
waitingForAnimations: 'Waiting for animations...',
/**
*@description Tooltip text that appears when hovering over largeicon replay animation button in Animation Timeline of the Animation Inspector
*/
replayTimeline: 'Replay timeline',
/**
*@description Text in Animation Timeline of the Animation Inspector
*/
resumeAll: 'Resume all',
/**
*@description Title of control button in animation timeline of the animation inspector
*/
playTimeline: 'Play timeline',
/**
*@description Title of control button in animation timeline of the animation inspector
*/
pauseTimeline: 'Pause timeline',
/**
*@description Title of a specific Animation Preview
*@example {1} PH1
*/
animationPreviewS: 'Animation Preview {PH1}',
};
const str_ = i18n.i18n.registerUIStrings('panels/animation/AnimationTimeline.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
const nodeUIsByNode = new WeakMap<SDK.DOMModel.DOMNode, NodeUI>();
const playbackRates = new WeakMap<HTMLElement, number>();
let animationTimelineInstance: AnimationTimeline;
export class AnimationTimeline extends UI.Widget.VBox implements SDK.TargetManager.SDKModelObserver<AnimationModel> {
#gridWrapper: HTMLElement;
#grid: Element;
#playbackRate: number;
#allPaused: boolean;
#animationsContainer: HTMLElement;
#playbackRateButtons!: HTMLElement[];
#previewContainer!: HTMLElement;
#timelineScrubber!: HTMLElement;
#currentTime!: HTMLElement;
#popoverHelper!: UI.PopoverHelper.PopoverHelper;
#clearButton!: UI.Toolbar.ToolbarButton;
#selectedGroup!: AnimationGroup|null;
#renderQueue!: AnimationUI[];
#defaultDuration: number;
#durationInternal: number;
#timelineControlsWidth: number;
readonly #nodesMap: Map<number, NodeUI>;
#uiAnimations: AnimationUI[];
#groupBuffer: AnimationGroup[];
readonly #previewMap: Map<AnimationGroup, AnimationGroupPreviewUI>;
readonly #symbol: symbol;
readonly #animationsMap: Map<string, AnimationImpl>;
#timelineScrubberLine?: HTMLElement;
#pauseButton?: UI.Toolbar.ToolbarToggle;
#controlButton?: UI.Toolbar.ToolbarToggle;
#controlState?: ControlState;
#redrawing?: boolean;
#cachedTimelineWidth?: number;
#cachedTimelineHeight?: number;
#scrubberPlayer?: Animation;
#gridOffsetLeft?: number;
#originalScrubberTime?: number|null;
#originalMousePosition?: number;
private constructor() {
super(true);
this.element.classList.add('animations-timeline');
this.#gridWrapper = this.contentElement.createChild('div', 'grid-overflow-wrapper');
this.#grid = UI.UIUtils.createSVGChild(this.#gridWrapper, 'svg', 'animation-timeline-grid');
this.#playbackRate = 1;
this.#allPaused = false;
this.createHeader();
this.#animationsContainer = this.contentElement.createChild('div', 'animation-timeline-rows');
const timelineHint = this.contentElement.createChild('div', 'animation-timeline-rows-hint');
timelineHint.textContent = i18nString(UIStrings.selectAnEffectAboveToInspectAnd);
/** @const */ this.#defaultDuration = 100;
this.#durationInternal = this.#defaultDuration;
/** @const */ this.#timelineControlsWidth = 150;
this.#nodesMap = new Map();
this.#uiAnimations = [];
this.#groupBuffer = [];
this.#previewMap = new Map();
this.#symbol = Symbol('animationTimeline');
this.#animationsMap = new Map();
SDK.TargetManager.TargetManager.instance().addModelListener(
SDK.DOMModel.DOMModel, SDK.DOMModel.Events.NodeRemoved, this.nodeRemoved, this);
SDK.TargetManager.TargetManager.instance().observeModels(AnimationModel, this);
UI.Context.Context.instance().addFlavorChangeListener(SDK.DOMModel.DOMNode, this.nodeChanged, this);
}
static instance(): AnimationTimeline {
if (!animationTimelineInstance) {
animationTimelineInstance = new AnimationTimeline();
}
return animationTimelineInstance;
}
get previewMap(): Map<AnimationGroup, AnimationGroupPreviewUI> {
return this.#previewMap;
}
get uiAnimations(): AnimationUI[] {
return this.#uiAnimations;
}
get groupBuffer(): AnimationGroup[] {
return this.#groupBuffer;
}
wasShown(): void {
for (const animationModel of SDK.TargetManager.TargetManager.instance().models(AnimationModel)) {
this.addEventListeners(animationModel);
}
this.registerCSSFiles([animationTimelineStyles]);
}
willHide(): void {
for (const animationModel of SDK.TargetManager.TargetManager.instance().models(AnimationModel)) {
this.removeEventListeners(animationModel);
}
if (this.#popoverHelper) {
this.#popoverHelper.hidePopover();
}
}
modelAdded(animationModel: AnimationModel): void {
if (this.isShowing()) {
this.addEventListeners(animationModel);
}
}
modelRemoved(animationModel: AnimationModel): void {
this.removeEventListeners(animationModel);
}
private addEventListeners(animationModel: AnimationModel): void {
animationModel.ensureEnabled();
animationModel.addEventListener(Events.AnimationGroupStarted, this.animationGroupStarted, this);
animationModel.addEventListener(Events.ModelReset, this.reset, this);
}
private removeEventListeners(animationModel: AnimationModel): void {
animationModel.removeEventListener(Events.AnimationGroupStarted, this.animationGroupStarted, this);
animationModel.removeEventListener(Events.ModelReset, this.reset, this);
}
private nodeChanged(): void {
for (const nodeUI of this.#nodesMap.values()) {
nodeUI.nodeChanged();
}
}
private createScrubber(): HTMLElement {
this.#timelineScrubber = document.createElement('div');
this.#timelineScrubber.classList.add('animation-scrubber');
this.#timelineScrubber.classList.add('hidden');
this.#timelineScrubberLine = this.#timelineScrubber.createChild('div', 'animation-scrubber-line');
this.#timelineScrubberLine.createChild('div', 'animation-scrubber-head');
this.#timelineScrubber.createChild('div', 'animation-time-overlay');
return this.#timelineScrubber;
}
private createHeader(): HTMLElement {
const toolbarContainer = this.contentElement.createChild('div', 'animation-timeline-toolbar-container');
const topToolbar = new UI.Toolbar.Toolbar('animation-timeline-toolbar', toolbarContainer);
this.#clearButton = new UI.Toolbar.ToolbarButton(i18nString(UIStrings.clearAll), 'largeicon-clear');
this.#clearButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, this.reset.bind(this));
topToolbar.appendToolbarItem(this.#clearButton);
topToolbar.appendSeparator();
this.#pauseButton =
new UI.Toolbar.ToolbarToggle(i18nString(UIStrings.pauseAll), 'largeicon-pause', 'largeicon-resume');
this.#pauseButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, this.togglePauseAll.bind(this));
topToolbar.appendToolbarItem(this.#pauseButton);
const playbackRateControl = toolbarContainer.createChild('div', 'animation-playback-rate-control');
playbackRateControl.addEventListener('keydown', this.handlePlaybackRateControlKeyDown.bind(this));
UI.ARIAUtils.markAsListBox(playbackRateControl);
UI.ARIAUtils.setAccessibleName(playbackRateControl, i18nString(UIStrings.playbackRates));
/** @type {!Array<!HTMLElement>} */
this.#playbackRateButtons = [];
for (const playbackRate of GlobalPlaybackRates) {
const button = (playbackRateControl.createChild('button', 'animation-playback-rate-button') as HTMLElement);
button.textContent = playbackRate ? i18nString(UIStrings.playbackRatePlaceholder, {PH1: playbackRate * 100}) :
i18nString(UIStrings.pause);
playbackRates.set(button, playbackRate);
button.addEventListener('click', this.setPlaybackRate.bind(this, playbackRate));
UI.ARIAUtils.markAsOption(button);
UI.Tooltip.Tooltip.install(button, i18nString(UIStrings.setSpeedToS, {PH1: button.textContent}));
button.tabIndex = -1;
this.#playbackRateButtons.push(button);
}
this.updatePlaybackControls();
this.#previewContainer = (this.contentElement.createChild('div', 'animation-timeline-buffer') as HTMLElement);
UI.ARIAUtils.markAsListBox(this.#previewContainer);
UI.ARIAUtils.setAccessibleName(this.#previewContainer, i18nString(UIStrings.animationPreviews));
this.#popoverHelper = new UI.PopoverHelper.PopoverHelper(this.#previewContainer, this.getPopoverRequest.bind(this));
this.#popoverHelper.setDisableOnClick(true);
this.#popoverHelper.setTimeout(0);
const emptyBufferHint = this.contentElement.createChild('div', 'animation-timeline-buffer-hint');
emptyBufferHint.textContent = i18nString(UIStrings.waitingForAnimations);
const container = this.contentElement.createChild('div', 'animation-timeline-header');
const controls = container.createChild('div', 'animation-controls');
this.#currentTime = (controls.createChild('div', 'animation-timeline-current-time monospace') as HTMLElement);
const toolbar = new UI.Toolbar.Toolbar('animation-controls-toolbar', controls);
this.#controlButton =
new UI.Toolbar.ToolbarToggle(i18nString(UIStrings.replayTimeline), 'largeicon-replay-animation');
this.#controlState = ControlState.Replay;
this.#controlButton.setToggled(true);
this.#controlButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, this.controlButtonToggle.bind(this));
toolbar.appendToolbarItem(this.#controlButton);
const gridHeader = container.createChild('div', 'animation-grid-header');
UI.UIUtils.installDragHandle(
gridHeader, this.repositionScrubber.bind(this), this.scrubberDragMove.bind(this),
this.scrubberDragEnd.bind(this), 'text');
this.#gridWrapper.appendChild(this.createScrubber());
if (this.#timelineScrubberLine) {
UI.UIUtils.installDragHandle(
this.#timelineScrubberLine, this.scrubberDragStart.bind(this), this.scrubberDragMove.bind(this),
this.scrubberDragEnd.bind(this), 'col-resize');
}
this.#currentTime.textContent = '';
return container;
}
private handlePlaybackRateControlKeyDown(event: Event): void {
const keyboardEvent = (event as KeyboardEvent);
switch (keyboardEvent.key) {
case 'ArrowLeft':
case 'ArrowUp':
this.focusNextPlaybackRateButton(event.target, /* focusPrevious */ true);
break;
case 'ArrowRight':
case 'ArrowDown':
this.focusNextPlaybackRateButton(event.target);
break;
}
}
private focusNextPlaybackRateButton(target: EventTarget|null, focusPrevious?: boolean): void {
const button = (target as HTMLElement);
const currentIndex = this.#playbackRateButtons.indexOf(button);
const nextIndex = focusPrevious ? currentIndex - 1 : currentIndex + 1;
if (nextIndex < 0 || nextIndex >= this.#playbackRateButtons.length) {
return;
}
const nextButton = this.#playbackRateButtons[nextIndex];
nextButton.tabIndex = 0;
nextButton.focus();
if (target) {
(target as HTMLElement).tabIndex = -1;
}
}
private getPopoverRequest(event: Event): UI.PopoverHelper.PopoverRequest|null {
const element = (event.target as HTMLElement);
if (!element || !element.isDescendant(this.#previewContainer)) {
return null;
}
return {
box: element.boxInWindow(),
show: (popover: UI.GlassPane.GlassPane): Promise<boolean> => {
let animGroup;
for (const [group, previewUI] of this.#previewMap) {
if (previewUI.element === element.parentElement) {
animGroup = group;
}
}
console.assert(typeof animGroup !== 'undefined');
if (!animGroup) {
return Promise.resolve(false);
}
const screenshots = animGroup.screenshots();
if (!screenshots.length) {
return Promise.resolve(false);
}
let fulfill: (arg0: boolean) => void;
const promise = new Promise<boolean>(x => {
fulfill = x;
});
if (!screenshots[0].complete) {
screenshots[0].onload = onFirstScreenshotLoaded.bind(null, screenshots);
} else {
onFirstScreenshotLoaded(screenshots);
}
return promise;
function onFirstScreenshotLoaded(screenshots: HTMLImageElement[]): void {
new AnimationScreenshotPopover(screenshots).show(popover.contentElement);
fulfill(true);
}
},
hide: undefined,
};
}
private togglePauseAll(): void {
this.#allPaused = !this.#allPaused;
if (this.#pauseButton) {
this.#pauseButton.setToggled(this.#allPaused);
}
this.setPlaybackRate(this.#playbackRate);
if (this.#pauseButton) {
this.#pauseButton.setTitle(this.#allPaused ? i18nString(UIStrings.resumeAll) : i18nString(UIStrings.pauseAll));
}
}
private setPlaybackRate(playbackRate: number): void {
this.#playbackRate = playbackRate;
for (const animationModel of SDK.TargetManager.TargetManager.instance().models(AnimationModel)) {
animationModel.setPlaybackRate(this.#allPaused ? 0 : this.#playbackRate);
}
Host.userMetrics.actionTaken(Host.UserMetrics.Action.AnimationsPlaybackRateChanged);
if (this.#scrubberPlayer) {
this.#scrubberPlayer.playbackRate = this.effectivePlaybackRate();
}
this.updatePlaybackControls();
}
private updatePlaybackControls(): void {
for (const button of this.#playbackRateButtons) {
const selected = this.#playbackRate === playbackRates.get(button);
button.classList.toggle('selected', selected);
button.tabIndex = selected ? 0 : -1;
}
}
private controlButtonToggle(): void {
if (this.#controlState === ControlState.Play) {
this.togglePause(false);
} else if (this.#controlState === ControlState.Replay) {
this.replay();
} else {
this.togglePause(true);
}
}
private updateControlButton(): void {
if (!this.#controlButton) {
return;
}
this.#controlButton.setEnabled(Boolean(this.#selectedGroup));
if (this.#selectedGroup && this.#selectedGroup.paused()) {
this.#controlState = ControlState.Play;
this.#controlButton.setToggled(true);
this.#controlButton.setTitle(i18nString(UIStrings.playTimeline));
this.#controlButton.setGlyph('largeicon-play-animation');
} else if (
!this.#scrubberPlayer || !this.#scrubberPlayer.currentTime ||
this.#scrubberPlayer.currentTime >= this.duration()) {
this.#controlState = ControlState.Replay;
this.#controlButton.setToggled(true);
this.#controlButton.setTitle(i18nString(UIStrings.replayTimeline));
this.#controlButton.setGlyph('largeicon-replay-animation');
} else {
this.#controlState = ControlState.Pause;
this.#controlButton.setToggled(false);
this.#controlButton.setTitle(i18nString(UIStrings.pauseTimeline));
this.#controlButton.setGlyph('largeicon-pause-animation');
}
}
private effectivePlaybackRate(): number {
return (this.#allPaused || (this.#selectedGroup && this.#selectedGroup.paused())) ? 0 : this.#playbackRate;
}
private togglePause(pause: boolean): void {
if (this.#scrubberPlayer) {
this.#scrubberPlayer.playbackRate = this.effectivePlaybackRate();
}
if (this.#selectedGroup) {
this.#selectedGroup.togglePause(pause);
const preview = this.#previewMap.get(this.#selectedGroup);
if (preview) {
preview.element.classList.toggle('paused', pause);
}
}
this.updateControlButton();
}
private replay(): void {
if (!this.#selectedGroup) {
return;
}
this.#selectedGroup.seekTo(0);
this.animateTime(0);
this.updateControlButton();
}
duration(): number {
return this.#durationInternal;
}
setDuration(duration: number): void {
this.#durationInternal = duration;
this.scheduleRedraw();
}
private clearTimeline(): void {
this.#uiAnimations = [];
this.#nodesMap.clear();
this.#animationsMap.clear();
this.#animationsContainer.removeChildren();
this.#durationInternal = this.#defaultDuration;
this.#timelineScrubber.classList.add('hidden');
this.#selectedGroup = null;
if (this.#scrubberPlayer) {
this.#scrubberPlayer.cancel();
}
this.#scrubberPlayer = undefined;
this.#currentTime.textContent = '';
this.updateControlButton();
}
private reset(): void {
this.clearTimeline();
if (this.#allPaused) {
this.togglePauseAll();
} else {
this.setPlaybackRate(this.#playbackRate);
}
for (const group of this.#groupBuffer) {
group.release();
}
this.#groupBuffer = [];
this.#previewMap.clear();
this.#previewContainer.removeChildren();
this.#popoverHelper.hidePopover();
this.renderGrid();
}
private animationGroupStarted({data}: Common.EventTarget.EventTargetEvent<AnimationGroup>): void {
this.addAnimationGroup(data);
}
private addAnimationGroup(group: AnimationGroup): void {
function startTimeComparator(left: AnimationGroup, right: AnimationGroup): 0|1|- 1 {
if (left.startTime() === right.startTime()) {
return 0;
}
return left.startTime() > right.startTime() ? 1 : -1;
}
const previewGroup = this.#previewMap.get(group);
if (previewGroup) {
if (this.#selectedGroup === group) {
this.syncScrubber();
} else {
previewGroup.replay();
}
return;
}
this.#groupBuffer.sort(startTimeComparator);
// Discard oldest groups from buffer if necessary
const groupsToDiscard = [];
const bufferSize = this.width() / 50;
while (this.#groupBuffer.length > bufferSize) {
const toDiscard = this.#groupBuffer.splice(this.#groupBuffer[0] === this.#selectedGroup ? 1 : 0, 1);
groupsToDiscard.push(toDiscard[0]);
}
for (const g of groupsToDiscard) {
const discardGroup = this.#previewMap.get(g);
if (!discardGroup) {
continue;
}
discardGroup.element.remove();
this.#previewMap.delete(g);
g.release();
}
// Generate preview
const preview = new AnimationGroupPreviewUI(group);
this.#groupBuffer.push(group);
this.#previewMap.set(group, preview);
this.#previewContainer.appendChild(preview.element);
preview.removeButton().addEventListener('click', this.removeAnimationGroup.bind(this, group));
preview.element.addEventListener('click', this.selectAnimationGroup.bind(this, group));
preview.element.addEventListener('keydown', this.handleAnimationGroupKeyDown.bind(this, group));
UI.ARIAUtils.setAccessibleName(
preview.element, i18nString(UIStrings.animationPreviewS, {PH1: this.#groupBuffer.indexOf(group) + 1}));
UI.ARIAUtils.markAsOption(preview.element);
if (this.#previewMap.size === 1) {
const preview = this.#previewMap.get(this.#groupBuffer[0]);
if (preview) {
preview.element.tabIndex = 0;
}
}
}
private handleAnimationGroupKeyDown(group: AnimationGroup, event: KeyboardEvent): void {
switch (event.key) {
case ' ':
case 'Enter':
this.selectAnimationGroup(group);
break;
case 'Backspace':
case 'Delete':
this.removeAnimationGroup(group, event);
break;
case 'ArrowLeft':
case 'ArrowUp':
this.focusNextGroup(group, /* target */ event.target, /* focusPrevious */ true);
break;
case 'ArrowRight':
case 'ArrowDown':
this.focusNextGroup(group, /* target */ event.target);
}
}
private focusNextGroup(group: AnimationGroup, target: EventTarget|null, focusPrevious?: boolean): void {
const currentGroupIndex = this.#groupBuffer.indexOf(group);
const nextIndex = focusPrevious ? currentGroupIndex - 1 : currentGroupIndex + 1;
if (nextIndex < 0 || nextIndex >= this.#groupBuffer.length) {
return;
}
const preview = this.#previewMap.get(this.#groupBuffer[nextIndex]);
if (preview) {
preview.element.tabIndex = 0;
preview.element.focus();
}
if (target) {
(target as HTMLElement).tabIndex = -1;
}
}
private removeAnimationGroup(group: AnimationGroup, event: Event): void {
const currentGroupIndex = this.#groupBuffer.indexOf(group);
Platform.ArrayUtilities.removeElement(this.#groupBuffer, group);
const previewGroup = this.#previewMap.get(group);
if (previewGroup) {
previewGroup.element.remove();
}
this.#previewMap.delete(group);
group.release();
event.consume(true);
if (this.#selectedGroup === group) {
this.clearTimeline();
this.renderGrid();
}
const groupLength = this.#groupBuffer.length;
if (groupLength === 0) {
(this.#clearButton.element as HTMLElement).focus();
return;
}
const nextGroup = currentGroupIndex >= this.#groupBuffer.length ?
this.#previewMap.get(this.#groupBuffer[this.#groupBuffer.length - 1]) :
this.#previewMap.get(this.#groupBuffer[currentGroupIndex]);
if (nextGroup) {
nextGroup.element.tabIndex = 0;
nextGroup.element.focus();
}
}
private selectAnimationGroup(group: AnimationGroup): void {
function applySelectionClass(this: AnimationTimeline, ui: AnimationGroupPreviewUI, group: AnimationGroup): void {
ui.element.classList.toggle('selected', this.#selectedGroup === group);
}
if (this.#selectedGroup === group) {
this.togglePause(false);
this.replay();
return;
}
this.clearTimeline();
this.#selectedGroup = group;
this.#previewMap.forEach(applySelectionClass, this);
this.setDuration(Math.max(500, group.finiteDuration() + 100));
for (const anim of group.animations()) {
this.addAnimation(anim);
}
this.scheduleRedraw();
this.#timelineScrubber.classList.remove('hidden');
this.togglePause(false);
this.replay();
}
private addAnimation(animation: AnimationImpl): void {
function nodeResolved(this: AnimationTimeline, node: SDK.DOMModel.DOMNode|null): void {
uiAnimation.setNode(node);
if (node && nodeUI) {
nodeUI.nodeResolved(node);
nodeUIsByNode.set(node, nodeUI);
}
}
let nodeUI = this.#nodesMap.get(animation.source().backendNodeId());
if (!nodeUI) {
nodeUI = new NodeUI(animation.source());
this.#animationsContainer.appendChild(nodeUI.element);
this.#nodesMap.set(animation.source().backendNodeId(), nodeUI);
}
const nodeRow = nodeUI.createNewRow();
const uiAnimation = new AnimationUI(animation, this, nodeRow);
animation.source().deferredNode().resolve(nodeResolved.bind(this));
this.#uiAnimations.push(uiAnimation);
this.#animationsMap.set(animation.id(), animation);
}
private nodeRemoved(
event: Common.EventTarget.EventTargetEvent<{node: SDK.DOMModel.DOMNode, parent: SDK.DOMModel.DOMNode}>): void {
const {node} = event.data;
const nodeUI = nodeUIsByNode.get(node);
if (nodeUI) {
nodeUI.nodeRemoved();
}
}
private renderGrid(): void {
/** @const */ const gridSize = 250;
const gridWidth = (this.width() + 10).toString();
const gridHeight = ((this.#cachedTimelineHeight || 0) + 30).toString();
this.#gridWrapper.style.width = gridWidth + 'px';
this.#gridWrapper.style.height = gridHeight.toString() + 'px';
this.#grid.setAttribute('width', gridWidth);
this.#grid.setAttribute('height', gridHeight.toString());
this.#grid.setAttribute('shape-rendering', 'crispEdges');
this.#grid.removeChildren();
let lastDraw: number|undefined = undefined;
for (let time = 0; time < this.duration(); time += gridSize) {
const line = UI.UIUtils.createSVGChild(this.#grid, 'rect', 'animation-timeline-grid-line');
line.setAttribute('x', (time * this.pixelMsRatio() + 10).toString());
line.setAttribute('y', '23');
line.setAttribute('height', '100%');
line.setAttribute('width', '1');
}
for (let time = 0; time < this.duration(); time += gridSize) {
const gridWidth = time * this.pixelMsRatio();
if (lastDraw === undefined || gridWidth - lastDraw > 50) {
lastDraw = gridWidth;
const label = UI.UIUtils.createSVGChild(this.#grid, 'text', 'animation-timeline-grid-label');
label.textContent = i18n.TimeUtilities.millisToString(time);
label.setAttribute('x', (gridWidth + 10).toString());
label.setAttribute('y', '16');
}
}
}
scheduleRedraw(): void {
this.#renderQueue = [];
for (const ui of this.#uiAnimations) {
this.#renderQueue.push(ui);
}
if (this.#redrawing) {
return;
}
this.#redrawing = true;
this.renderGrid();
this.#animationsContainer.window().requestAnimationFrame(this.render.bind(this));
}
private render(timestamp?: number): void {
while (this.#renderQueue.length && (!timestamp || window.performance.now() - timestamp < 50)) {
const animationUI = this.#renderQueue.shift();
if (animationUI) {
animationUI.redraw();
}
}
if (this.#renderQueue.length) {
this.#animationsContainer.window().requestAnimationFrame(this.render.bind(this));
} else {
this.#redrawing = undefined;
}
}
onResize(): void {
this.#cachedTimelineWidth = Math.max(0, this.#animationsContainer.offsetWidth - this.#timelineControlsWidth) || 0;
this.#cachedTimelineHeight = this.#animationsContainer.offsetHeight;
this.scheduleRedraw();
if (this.#scrubberPlayer) {
this.syncScrubber();
}
this.#gridOffsetLeft = undefined;
}
width(): number {
return this.#cachedTimelineWidth || 0;
}
private resizeWindow(animation: AnimationImpl): boolean {
let resized = false;
// This shows at most 3 iterations
const duration = animation.source().duration() * Math.min(2, animation.source().iterations());
const requiredDuration = animation.source().delay() + duration + animation.source().endDelay();
if (requiredDuration > this.#durationInternal) {
resized = true;
this.#durationInternal = requiredDuration + 200;
}
return resized;
}
private syncScrubber(): void {
if (!this.#selectedGroup) {
return;
}
this.#selectedGroup.currentTimePromise()
.then(this.animateTime.bind(this))
.then(this.updateControlButton.bind(this));
}
private animateTime(currentTime: number): void {
if (this.#scrubberPlayer) {
this.#scrubberPlayer.cancel();
}
this.#scrubberPlayer = this.#timelineScrubber.animate(
[{transform: 'translateX(0px)'}, {transform: 'translateX(' + this.width() + 'px)'}],
{duration: this.duration(), fill: 'forwards'});
this.#scrubberPlayer.playbackRate = this.effectivePlaybackRate();
this.#scrubberPlayer.onfinish = this.updateControlButton.bind(this);
this.#scrubberPlayer.currentTime = currentTime;
this.element.window().requestAnimationFrame(this.updateScrubber.bind(this));
}
pixelMsRatio(): number {
return this.width() / this.duration() || 0;
}
private updateScrubber(_timestamp: number): void {
if (!this.#scrubberPlayer) {
return;
}
this.#currentTime.textContent = i18n.TimeUtilities.millisToString(this.#scrubberPlayer.currentTime || 0);
if (this.#scrubberPlayer.playState.toString() === 'pending' || this.#scrubberPlayer.playState === 'running') {
this.element.window().requestAnimationFrame(this.updateScrubber.bind(this));
} else if (this.#scrubberPlayer.playState === 'finished') {
this.#currentTime.textContent = '';
}
}
private repositionScrubber(event: Event): boolean {
if (!this.#selectedGroup) {
return false;
}
// Seek to current mouse position.
if (!this.#gridOffsetLeft) {
this.#gridOffsetLeft = this.#grid.totalOffsetLeft() + 10;
}
const {x} = (event as any); // eslint-disable-line @typescript-eslint/no-explicit-any
const seekTime = Math.max(0, x - this.#gridOffsetLeft) / this.pixelMsRatio();
this.#selectedGroup.seekTo(seekTime);
this.togglePause(true);
this.animateTime(seekTime);
// Interface with scrubber drag.
this.#originalScrubberTime = seekTime;
this.#originalMousePosition = x;
return true;
}
private scrubberDragStart(event: Event): boolean {
if (!this.#scrubberPlayer || !this.#selectedGroup) {
return false;
}
this.#originalScrubberTime = this.#scrubberPlayer.currentTime;
this.#timelineScrubber.classList.remove('animation-timeline-end');
this.#scrubberPlayer.pause();
const {x} = (event as any); // eslint-disable-line @typescript-eslint/no-explicit-any
this.#originalMousePosition = x;
this.togglePause(true);
return true;
}
private scrubberDragMove(event: Event): void {
const {x} = (event as any); // eslint-disable-line @typescript-eslint/no-explicit-any
const delta = x - (this.#originalMousePosition || 0);
const currentTime =
Math.max(0, Math.min((this.#originalScrubberTime || 0) + delta / this.pixelMsRatio(), this.duration()));
if (this.#scrubberPlayer) {
this.#scrubberPlayer.currentTime = currentTime;
}
this.#currentTime.textContent = i18n.TimeUtilities.millisToString(Math.round(currentTime));
if (this.#selectedGroup) {
this.#selectedGroup.seekTo(currentTime);
}
}
private scrubberDragEnd(_event: Event): void {
if (this.#scrubberPlayer) {
const currentTime = Math.max(0, this.#scrubberPlayer.currentTime || 0);
this.#scrubberPlayer.play();
this.#scrubberPlayer.currentTime = currentTime;
}
this.#currentTime.window().requestAnimationFrame(this.updateScrubber.bind(this));
}
}
export const GlobalPlaybackRates = [1, 0.25, 0.1];
const enum ControlState {
Play = 'play-outline',
Replay = 'replay-outline',
Pause = 'pause-outline',
}
export class NodeUI {
element: HTMLDivElement;
readonly #description: HTMLElement;
readonly #timelineElement: HTMLElement;
#node?: SDK.DOMModel.DOMNode|null;
constructor(_animationEffect: AnimationEffect) {
this.element = document.createElement('div');
this.element.classList.add('animation-node-row');
this.#description = this.element.createChild('div', 'animation-node-description');
this.#timelineElement = this.element.createChild('div', 'animation-node-timeline');
UI.ARIAUtils.markAsApplication(this.#timelineElement);
}
nodeResolved(node: SDK.DOMModel.DOMNode|null): void {
if (!node) {
UI.UIUtils.createTextChild(this.#description, '<node>');
return;
}
this.#node = node;
this.nodeChanged();
Common.Linkifier.Linkifier.linkify(node).then(link => this.#description.appendChild(link));
if (!node.ownerDocument) {
this.nodeRemoved();
}
}
createNewRow(): Element {
return this.#timelineElement.createChild('div', 'animation-timeline-row');
}
nodeRemoved(): void {
this.element.classList.add('animation-node-removed');
this.#node = null;
}
nodeChanged(): void {
let animationNodeSelected = false;
if (this.#node) {
animationNodeSelected = (this.#node === UI.Context.Context.instance().flavor(SDK.DOMModel.DOMNode));
}
this.element.classList.toggle('animation-node-selected', animationNodeSelected);
}
}
export class StepTimingFunction {
steps: number;
stepAtPosition: string;
constructor(steps: number, stepAtPosition: string) {
this.steps = steps;
this.stepAtPosition = stepAtPosition;
}
static parse(text: string): StepTimingFunction|null {
let match = text.match(/^steps\((\d+), (start|middle)\)$/);
if (match) {
return new StepTimingFunction(parseInt(match[1], 10), match[2]);
}
match = text.match(/^steps\((\d+)\)$/);
if (match) {
return new StepTimingFunction(parseInt(match[1], 10), 'end');
}
return null;
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.